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;
}
Related
I'm making the bot for Google Dictionary using this API https://dictionaryapi.dev/. It's supposed to show word definitions in different languages. And the bot works just fine for English and Spanish. But there's an IOException every time I put in Russian words. What can be the cause of it?
Here's my Bot class.
Bot.java:
public void onUpdateReceived(Update update) {
//Model model = new Model();
WordModel wordModel = new WordModel();
Message message = update.getMessage();
if (message != null && message.hasText())
{
switch (message.getText()) {
case "/english":
DictionaryEntry.setLanguage("en");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/russian":
DictionaryEntry.setLanguage("ru");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/spanish":
DictionaryEntry.setLanguage("es");
sendMsg(message, DictionaryEntry.getLanguage());
break;
default:
if (!message.getText().contains("/")) {
try {
sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
} catch (IOException e) {
sendMsg(message, "Не найдено");
sendMsg(message, DictionaryEntry.getUrl().toString());
}
}
break;
}
}
}
public void sendMsg(Message message, String text) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendMsgs(Message message, List<String> words) {
for (int i = 0; i < words.size(); i++) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(words.get(i));
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
And here's my DictionaryEntry class where I process JSON string that I get from URL.
DictionaryEntry.java:
private static String language = "ru";
public static String getLanguage() {
return language;
}
public static void setLanguage(String language) {
DictionaryEntry.language = language;
}
public static URL getUrl() {
return url;
}
private static URL url;
public static List<String> getWords(String message, WordModel wordModel) throws IOException {
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/" + message);
Scanner in = new Scanner((InputStream) url.getContent());
String result = "";
while (in.hasNext())
{
result += in.nextLine();
}
String result2 = result.replaceAll("\"", "\\\"");
List<WordModel> models = new ArrayList<>();
List<String> results = new ArrayList<>();
int count = 0;
try {
JSONArray mainArray = new JSONArray(result2);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject wordEntry = mainArray.getJSONObject(i);
String wordName = wordEntry.getString("word");
wordModel.setWord(wordName);
JSONArray meaningsArray = wordEntry.getJSONArray("meanings");
for (int j = 0; j < meaningsArray.length(); j++) {
JSONObject meaningEntry = meaningsArray.getJSONObject(j);
JSONArray definitionsArray = meaningEntry.getJSONArray("definitions");
for (int k = 0; k < definitionsArray.length(); k++) {
//count++;
JSONObject definitionEntry = definitionsArray.getJSONObject(k);
String definition = definitionEntry.getString("definition");
wordModel.setDefinition(definition);
if (definitionEntry.has("example")) {
count++;
String example = definitionEntry.getString("example");
wordModel.setExample(example);
}
else {
wordModel.setExample("No examples found");
}
models.add(wordModel);
results.add("Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample());
}
}
}
/*result = "Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample();*/
} catch (JSONException e) {
count = 50;
}
results.add(url.toString());
return results;
}
Here's the stack trace:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
at java.base/java.net.URL.getContent(URL.java:1181)
at DictionaryEntry.getWords(DictionaryEntry.java:73)
at Bot.onUpdateReceived(Bot.java:91)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)
+ URLEncoder.encode(message, "UTF-8")
You are sending a HTTP request. The URL should be appropriate for the used encoding.
There are more aspects of using the right charset/encoding, but this might already be sufficient. The site probably uses UTF-8, as that can handle the full Unicode range.
400 is BAD REQUEST.
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/"
+ URLEncoder.encode(message, "UTF-8"));
And
Scanner in = new Scanner((InputStream) url.getContent(),
StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNextLine())
{
sb.append(in.nextLine()).append('\n');
}
String result = sb.toString();
Check in your environment that the file was in utf-8u format Because Cyrillic may not be supported
I have already uploaded the excel file in my local directory but the problem is that I can't read it from that location.
I am using struts 1.1 ,db2.
package mj.eps.action;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.mj.eps.dto.business.auction.UploadObject;
import com.mj.eps.dto.training.IndexValueReportObject;
import com.mj.eps.framework.util.FileScaner;
import com.mj.eps.framework.util.IConstant;
public class IndexValueAction extends EPSBaseAction{
public IndexValueAction() {
super();
}
#SuppressWarnings("unchecked")
#Override
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Vector<String> vector = new Vector<String>();
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
try{
String contentType = request.getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in =
new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead =
in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary =
contentType.substring(
lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos =
(
(file.substring(0, boundaryLocation))
.getBytes())
.length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd-MM-yy hh-mm-ss");
saveFile = saveFile.substring(0, saveFile.indexOf("."))+ "-"+ df.format(dt)+ ".xls";
String uploadFilePath = "";
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if(endPos > dataBytes.length )
endPos = dataBytes.length;
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String[]> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId=0;
try {
File outFile = new File(uploadFilePath + saveFile);
ServletConfig config = getServlet();
ServletContext sc = config.getServletContext();
boolean retVal = false;
boolean exists = true;
String filepath = outFile.getAbsolutePath();
String realPath = sc.getRealPath("virusCheck.properties");
exists = FileScaner.loadProperty(realPath);
if (exists) {
retVal = FileScaner.checkVirus(realPath, filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>Virus found!!"));
}
if (retVal) {
retVal = FileScaner.checkFileSign(filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>File type not supported!!"));
}
}
}
else {
}
if (retVal) {
}
if (errors.isEmpty())
{
***FileInputStream inputStream=new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows=read_sheet.getRows();
for (int j=1;j<rows;j++){
String[] fields=new String[4];
for(int i=0;i<fields.length;i++)
{
Cell cell=read_sheet.getCell(i,j);
fields[i]=cell.getContents().trim();
if(fields[0] != null ){
try{
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
}else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
}
catch(Exception e1)
{
int k=i+1;
errorVector.add("Invalid data at field "+k);
System.out.println(" err1 :" + e1.toString());
errorId = 1;
}
}
}
if(!(fields[0] == null || (fields[0].trim().equals(""))))
{
rowVector.add(fields);
}
else{
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
if (errorId == 0) {
int row = 0;
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
IndexValueReportObject indexValueReportObj =
new IndexValueReportObject();
String[] fields =
rowVector.elementAt(i);
System.out.println("abc>>>>>"+fields[0]);
System.out.println("abc>>>>>>>>>>>>>"+fields[1]);
System.out.println("abc>>>>>>>>>>>>>>>>>"+fields[2]);
System.out.println("abc>>>>>>>>>>>>>>>>>>>>>>>"+fields[3]);
try{
indexValueReportObj
.setDate(
Timestamp.valueOf(fields[0]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Date at row " + (row+1));
}
try{
indexValueReportObj
.setPlatts(
new BigDecimal(fields[1]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Platts Value at row " + (row+1));
}
try{
indexValueReportObj
.setArgus(
new BigDecimal(fields[2]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Argus Value at row " + (row+1));
}
try{
indexValueReportObj
.setTsi(
new BigDecimal(fields[3]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid TSI value at row " + (row+1));
}
indexObjectVector.add(
indexValueReportObj);
}
} else {
vector.add(
"No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
String filePathAndName=uploadFilePath + saveFile;
System.out.println("indexObjectVector"+indexObjectVector);
request.setAttribute(
IConstant.INDEX_OBJECT_VECTOR,
indexObjectVector);
request.getSession().setAttribute(
IConstant.FILE_NAME,
filePathAndName);
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
} else {
vector.add("File Type mismatch ");
}
} catch (Exception e) {
vector.add("No excel has been selected ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
forward = mapping.findForward("failureUpload");
} else {
forward = mapping.findForward("success");
}
return forward;
}
}
In Workbook portion I want to read the excel file from local directory. When I run this code in debug mode, the control is going into exception block and forward it in my success page. So can some one please help me with this? I put sysout in that portion but nothing shows. I am using JXl for excel read and write. My confusion is in 3 star portion.
Not an answer, but a partial refactoring.
This is an abomination of an action. There is zero way this should have ever passed any code review:
Actions and business logic should be completely separate.
Methods should be responsible for a single responsibility. This method:
Checks content type (arguably reasonable since that's web-related)
Manually parses the form (inexcusable; use a library)
Processes an Excel file (inexcusable; extract) which in turn:
Validates against business logic
Converts Excel values to BO values
The amount of un-equivalent work the action does defies explanation. This makes it essentially impossible to reason about, debug, fix, or anything. The below is a very rough start of refactoring, but you have another day or two of work to properly isolate levels of functionality and error handling (which is wrong, by the way, because you never check vector, possibly the worst-named variable in history, for errors, it's just thrown away?!?!?!)
public class IndexValueAction extends EPSBaseAction {
public IndexValueAction() {
super();
}
boolean isValidContentType(contentType) {
return (contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)
}
String readContent(request) throws Exception {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
totalBytesRead += in.read(dataBytes, totalBytesRead, formDataLength);
}
return new String(dataBytes);
}
void scanFile(realPath, outFilePath, errors) throws Exception {
if (!FileScanner.loadProperty(realPath)) {
return false;
}
if (!FileScanner.cleanFile(outFilePath)) {
FileScaner.cleanFile(outFilePath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>Virus found!!"));
return;
}
if (!FileScanner.checkFileSign(outFilePath)) {
FileScaner.cleanFile(filepath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>File type not supported!!"));
}
}
IndexValueReportObject loadIndexValueReportObject(String[] fields, int i, Vector<String> vector) {
IndexValueReportObject indexValueReportObj = new IndexValueReportObject();
try {
indexValueReportObj.setDate(Timestamp.valueOf(fields[0]));
} catch (Exception e) {
vector.add("Invalid Date at row " + (i + 2));
}
try {
indexValueReportObj.setPlatts(new BigDecimal(fields[1]));
} catch (Exception e) {
vector.add("Invalid Platts Value at row " + (i + 2));
}
try {
indexValueReportObj.setArgus(new BigDecimal(fields[2]));
} catch (Exception e) {
vector.add("Invalid Argus Value at row " + (i + 2));
}
try {
indexValueReportObj.setTsi(new BigDecimal(fields[3]));
} catch (Exception e) {
vector.add("Invalid TSI value at row " + (i + 2));
}
return indexValueReportObj;
}
#Override
#SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Vector<String> vector = new Vector<String>();
if (!isValidContentType(request.getContentType())) {
vector.add("File Type mismatch");
return mapping.findForward("failureUpload");
}
String file;
try {
file = readContent(request);
} catch (Exception e) {
vector.add("No excel has been selected");
return mapping.findForward("failureUpload");
}
ActionErrors errors = new ActionErrors();
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = file.substring(0, boundaryLocation).getBytes().length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy hh-mm-ss");
String fileSuffix = "-" + df.format(new Date()) + ".xls";
saveFile = saveFile.substring(0, saveFile.indexOf(".")) + fileSuffix;
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
String uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if (endPos > dataBytes.length) {
endPos = dataBytes.length;
}
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String []> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId = 0;
try {
ServletContext sc = getServlet().getServletContext();
String realPath = sc.getRealPath("virusCheck.properties");
File outFile = new File(uploadFilePath + saveFile);
String outFilePath = outFile.getAbsolutePath();
scanFile(realPath, outFilePath, errors);
if (errors.isEmpty()) {
FileInputStream inputStream = new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows = read_sheet.getRows();
for (int j = 1; j < rows; j++) {
String[] fields = new String[4];
for(int i = 0; i < fields.length; i++) {
Cell cell = read_sheet.getCell(i, j);
fields[i] = cell.getContents().trim();
if (fields[0] != null) {
try {
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
} else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
} catch(Exception e1) {
int k = i+1;
errorVector.add("Invalid data at field " + k);
errorId = 1;
}
}
}
if (!(fields[0] == null || (fields[0].trim().equals("")))) {
rowVector.add(fields);
} else {
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
if (errorId == 0) {
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
String[] fields = rowVector.elementAt(i);
indexObjectVector.add(loadIndexValueReportObject(loadIndexValueReportObject(fields, i, vector)));
}
} else {
vector.add("No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
request.setAttribute(IConstant.INDEX_OBJECT_VECTOR, indexObjectVector);
request.getSession().setAttribute(IConstant.FILE_NAME, uploadFilePath + saveFile);
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
return mapping.findForward("failureUpload");
}
return mapping.findForward("success");
}
}
I'm trying to read gmail messages using showmsg.java in the javamail sample package, and I keep getting this error when I run it. The program compiles fine though.
Here's the error message:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/internet/ParseException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: javax.mail.internet.ParseException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Here's the code:
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
/*
* Demo app that exercises the Message interfaces.
* Show information about and contents of messages.
*
* #author John Mani
* #author Bill Shannon
*/
public class msgshow {
static String protocol;
static String host = null;
static String user = null;
static String password = null;
static String mbox = null;
static String url = null;
static int port = -1;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = false;
static boolean showMessage = false;
static boolean showAlert = false;
static boolean saveAttachments = false;
static int attnum = 1;
public static void main(String argv[]) {
int optind;
InputStream msgStream = System.in;
for (optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-v")) {
verbose = true;
} else if (argv[optind].equals("-D")) {
debug = true;
} else if (argv[optind].equals("-f")) {
mbox = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-p")) {
port = Integer.parseInt(argv[++optind]);
} else if (argv[optind].equals("-s")) {
showStructure = true;
} else if (argv[optind].equals("-S")) {
saveAttachments = true;
} else if (argv[optind].equals("-m")) {
showMessage = true;
} else if (argv[optind].equals("-a")) {
showAlert = true;
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println(
"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
System.out.println(
"\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
System.out.println(
"or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
System.exit(1);
} else {
break;
}
}
try {
// Get a Properties object
Properties props = System.getProperties();
// Get a Session object
Session session = Session.getInstance(props, null);
session.setDebug(debug);
if (showMessage) {
MimeMessage msg;
if (mbox != null)
msg = new MimeMessage(session,
new BufferedInputStream(new FileInputStream(mbox)));
else
msg = new MimeMessage(session, msgStream);
dumpPart(msg);
System.exit(0);
}
// Get a Store object
Store store = null;
if (url != null) {
URLName urln = new URLName(url);
store = session.getStore(urln);
if (showAlert) {
store.addStoreListener(new StoreListener() {
public void notification(StoreEvent e) {
String s;
if (e.getMessageType() == StoreEvent.ALERT)
s = "ALERT: ";
else
s = "NOTICE: ";
System.out.println(s + e.getMessage());
}
});
}
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();
// Connect
if (host != null || user != null || password != null)
store.connect(host, port, user, password);
else
store.connect();
}
// Open the Folder
Folder folder = store.getDefaultFolder();
if (folder == null) {
System.out.println("No default folder");
System.exit(1);
}
if (mbox == null)
mbox = "INBOX";
folder = folder.getFolder(mbox);
if (folder == null) {
System.out.println("Invalid folder");
System.exit(1);
}
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
int totalMessages = folder.getMessageCount();
if (totalMessages == 0) {
System.out.println("Empty folder");
folder.close(false);
store.close();
System.exit(1);
}
if (verbose) {
int newMessages = folder.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
}
if (optind >= argv.length) {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
// dumpPart(msgs[i]);
}
} else {
while (optind < argv.length) {
int msgnum = Integer.parseInt(argv[optind++]);
System.out.println("Getting message number: " + msgnum);
Message m = null;
try {
m = folder.getMessage(msgnum);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
}
}
}
folder.close(false);
store.close();
} catch (Exception ex) {
System.out.println("Oops, got exception! " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
/** Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.out.write(c);
**/
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}
String filename = p.getFileName();
if (filename != null)
pr("FILENAME: " + filename);
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure && !saveAttachments)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
} else {
if (!showStructure && !saveAttachments) {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
} else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
}
} else {
// just a separator
pr("---------------------------");
}
}
/*
* If we're saving attachments, write out anything that
* looks like an attachment into an appropriately named
* file. Don't overwrite existing files to prevent
* mistakes.
*/
if (saveAttachments && level != 0 && p instanceof MimeBodyPart &&
!p.isMimeType("multipart/*")) {
String disp = p.getDisposition();
// many mailers don't include a Content-Disposition
if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
if (filename == null)
filename = "Attachment" + attnum++;
pr("Saving attachment to file " + filename);
try {
File f = new File(filename);
if (f.exists())
// XXX - could try a series of names
throw new IOException("file exists");
((MimeBodyPart)p).saveFile(f);
} catch (IOException ex) {
pr("Failed to save attachment: " + ex);
}
pr("---------------------------");
}
}
}
public static void dumpEnvelope(Message m) throws Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
}
// REPLY TO
if ((a = m.getReplyTo()) != null) {
for (int j = 0; j < a.length; j++)
pr("REPLY TO: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
InternetAddress ia = (InternetAddress)a[j];
if (ia.isGroup()) {
InternetAddress[] aa = ia.getGroup(false);
for (int k = 0; k < aa.length; k++)
pr(" GROUP: " + aa[k].toString());
}
}
}
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for (int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
}
String[] uf = flags.getUserFlags(); // get the user flag strings
for (int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
}
pr("FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader("X-Mailer");
if (hdrs != null)
pr("X-Mailer: " + hdrs[0]);
else
pr("X-Mailer NOT available");
}
static String indentStr = " ";
static int level = 0;
/**
* Print a, possibly indented, string.
*/
public static void pr(String s) {
if (showStructure)
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
}
The command I'm using to run is java msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS] and the command I'm using to compile it is javac -cp ".:./:./lib:./lib/*" msgshow.java. The javax.mail.jar is contained in the lib folder
This is some alternate code that's much shorter and gets the same errors:
import java.util.*;
import java.io.*;
import javax.mail.*;
import smtp;
import imaps;
//import java.mail.*;
//import com.sun.mail.*;
public class AccessGmail {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
try
{
Properties prop = new Properties();
prop.load(new FileInputStream(new File("smtp.properties")));
Session session = Session.getDefaultInstance(prop, null);
String pass = scan.next();
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com","shane.l.gvoice#gmail.com",pass);
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
int messageCount = inbox.getMessageCount();
System.out.println("Message Count: "+messageCount);
}
catch (FileNotFoundException e){}
catch (IOException e){}
catch(NoSuchProviderException e){}
catch(MessagingException e){}
}
}
You're not setting the CLASSPATH when you're running the program so it's not finding the javax.mail.jar file:
java -cp ".:lib/javax.mail.jar" msgshow -D -T imaps -H imap.gmail.com -U [USER] -P [PASS]
I am able to update table while running this , but not able to save. I am getting the below error.
SQL Error: 1364, SQLState: HY000 - Field 'AccCode' doesn't have a
default value org.hibernate.HibernateException:
org.hibernate.exception.GenericJDBCException: could not insert:
[com.anm.more.dao.AccMast].
public class AccmastAutoUpdate {
/*
* Created class for auto update of accmast table from .csv file through ftp
*/
enter code here
private static final Logger logger = Logger.getLogger(AccmastAutoUpdate.class);
static MailTicket mail = new MailTicket();
static StringBuffer storeMsg = new StringBuffer();
static int totalcount = 0;
static int errorRecCount = 0;
static int successRecCount = 0;
public static void main(String args[]) {
MoreUtils moreUtils = new MoreUtils();
Properties ps = moreUtils.getPropertyLoad("com/anm/more/bundle/Messages.properties");
String folderLoc = moreUtils.getPropertyValueByLabel(ps, "task_ftp_download");
folderLoc = folderLoc.replace("\\", "/");
System.out.println("Entering AccmastAutoUpdate");
File folder = new File(folderLoc);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String filename = listOfFiles[i].getName();
if (filename.startsWith("Accmast") && listOfFiles[i].getName().endsWith(".csv")) {
logger.info(filename);
boolean flag = insertToAccmast(folderLoc + "/" + filename);
if (flag) {
File file = new File(folderLoc + "/" + filename);
}
storeMsg.append(System.getProperty("line.separator"));
storeMsg.append("Total Records : " + totalcount + " Success Records : " + successRecCount + " Failed Records : " + errorRecCount);
}
}
}
private static boolean insertToAccmast(String fileloc) {
// TODO Auto-generated method stub
boolean flag = false;
String AccCode = null;
String Account = null;
String Site = null;
String Phone = null;
// String Disp_Deno = null;
String Address = null;
String AccType = null;
// String Shortage_Deno = null;
String Fax = null;
String AccTeam = null;
String Status = null;
String City = null;
String State = null;
String Territory = null;
String URL = null;
String Pincode = null; // int
String Country = null;
String Industry = null;
String conttype = null;
String SiteCode = null;
String acccode1 = null;
String SiteID = null;
String ContactName = null;
String ServiceArea = null;
String BillId = null;
String ResponseHours = null;
String ResolutionHours = null;
String comments = null;
String AccBranchCode = null;
String AccBranchName = null;
String ZonalCode = null;
String acc_createdby = null;
String NSBID = null;
String Bank = null;
String AccessibilityType; // double
String AccessibilityTimeFrom; // double
String AccessibilityTimeTo = null;
String HubLocation = null;
String SubLocation = null;
String GLNumber = null;
String NumberOfATM = null; // double
String acc_createddate = null; // Date
DateFormat getDate = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
try {
CsvReader csvReader = new CsvReader(fileloc, ',');
boolean firstline = true;
while (csvReader.readRecord()) {
if (firstline) {
firstline = false;
continue;
}
try {
totalcount++;
csvReader.get(0);
AccCode = csvReader.get(0);
Account = csvReader.get(1);
Site = csvReader.get(2);
Phone = csvReader.get(4);
Address = csvReader.get(5);
AccType = csvReader.get(6);
Fax = csvReader.get(7);
AccTeam = csvReader.get(8);
Status = csvReader.get(9);
City = csvReader.get(10);
State = csvReader.get(11);
Territory = csvReader.get(12);
URL = csvReader.get(13);
Pincode = csvReader.get(14);
Country = csvReader.get(15);
Industry = csvReader.get(16);
conttype = csvReader.get(17);
SiteCode = csvReader.get(18);
acccode1 = csvReader.get(19);
SiteID = csvReader.get(20);
ContactName = csvReader.get(21);
ServiceArea = csvReader.get(22);
BillId = csvReader.get(23);
ResponseHours = csvReader.get(24);
ResolutionHours = csvReader.get(25);
comments = csvReader.get(26);
AccBranchCode = csvReader.get(27);
AccBranchName = csvReader.get(28);
ZonalCode = csvReader.get(29);
acc_createdby = csvReader.get(30);
NSBID = csvReader.get(32);
Bank = csvReader.get(33);
AccessibilityType = csvReader.get(34);
AccessibilityTimeFrom = csvReader.get(35);
AccessibilityTimeTo = csvReader.get(36);
HubLocation = csvReader.get(37);
SubLocation = csvReader.get(38);
GLNumber = csvReader.get(39);
NumberOfATM = csvReader.get(40);
acc_createddate = csvReader.get(31);
AccMast accmast = new AccMast();
if (Pincode != null && Pincode != "" && Pincode.trim().length() <= 0) {
int PincodeNo = Integer.parseInt(Pincode);
accmast.setPincode(PincodeNo);
} else {
accmast.setPincode(123456);
}
if (NumberOfATM != null && NumberOfATM != "" && NumberOfATM.trim().length() <= 0) {
long NumberOfATMNo = Long.parseLong(NumberOfATM);
accmast.setNumberOfAtm(NumberOfATMNo);
} else {
accmast.setNumberOfAtm(0 L);
}
if (AccessibilityTimeFrom != null && AccessibilityTimeFrom != "" && AccessibilityTimeFrom.trim().length() <= 0) {
long AccessibilityTimeFromNo = Long.parseLong(AccessibilityTimeFrom);
accmast.setAccessibilityTimeFrom(AccessibilityTimeFromNo);
} else {
accmast.setAccessibilityTimeFrom(0 L);
}
if (AccessibilityTimeTo != null && AccessibilityTimeTo != "" && AccessibilityTimeTo.trim().length() <= 0) {
long AccessibilityTimeToNo = Long.parseLong(AccessibilityTimeTo);
accmast.setAccessibilityTimeTo(AccessibilityTimeToNo);
} else {
accmast.setAccessibilityTimeTo(0 L);
}
accmast.setAccCode(AccCode);
accmast.setAccount(Account);
accmast.setSite(Site);
accmast.setPhone(Phone);
accmast.setAddress(Address);
accmast.setAccType(AccType);
accmast.setFax(Fax);
accmast.setAccTeam(AccTeam);
accmast.setStatus(Status);
accmast.setCity(City);
accmast.setState(State);
accmast.setTerritory(Territory);
accmast.setUrl(URL);
accmast.setCountry(Country);
accmast.setIndustry(Industry);
accmast.setConttype(conttype);
accmast.setSiteCode(SiteCode);
accmast.setAcccode1(acccode1);
accmast.setSiteId(SiteID);
accmast.setContactName(ContactName);
accmast.setServiceArea(ServiceArea);
accmast.setBillId(BillId);
accmast.setResponseHours(ResponseHours);
accmast.setResolutionHours(ResolutionHours);
accmast.setComments(comments);
accmast.setAccBranchCode(AccBranchCode);
accmast.setAccBranchName(AccBranchName);
accmast.setZonalCode(ZonalCode);
accmast.setAccCreatedby(acc_createdby);
accmast.setNsbid(NSBID);
accmast.setBank(Bank);
//value has been sets accmast.setAccessibilityType(AccessibilityType);
accmast.setHubLocation(HubLocation);
accmast.setSubLocation(SubLocation);
accmast.setGlnumber(GLNumber);
//Date has been set accmast.setAccCreateddate(getDate.parse(acc_createddate));
AccMastDAO amd = new AccMastDAO();
//obj accmast able to view the content while debuggin.
//primary key is varchar in database.
boolean flag1 = amd.load(AccMast.class, AccCode);
if (flag1) {
amd.update(accmast);
} else {
amd.save(accmast);
}
successRecCount++;
System.out.println("Properties saved in accmast table object");
} catch (Exception ex) {
errorRecCount++;
storeMsg.append("AccMast : " + AccCode + "& Account : " + Account + " Failed");
storeMsg.append(System.getProperty("line.separator"));
ex.printStackTrace();
}
}
} catch (FileNotFoundException e) {
storeMsg.append(e.getMessage());
return false;
} catch (Exception e) {
errorRecCount++;
storeMsg.append(e.getMessage());
logger.info(e.getMessage());
return false;
}
return true;
}
}
//boolean method is working fine.
public boolean load(Class < ? > classType, Object id) {
Session session = super.getSession();
Object ob1 = (Object) session.get(classType, (Serializable) id);
if (ob1 != null) {
return true;
} else {
return false;
}
}
Based on your error code, check out this link:
Error: SQLSTATE[HY000]: General error: 1364 Field ‘xyz’ doesn’t have a default value
Otherwise, be sure that you're not updating a column constraint from NULL to NOT NULL if you don't provide a default value for already existing values to fill in.
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();
}
}