i have these two parts of code.
Adding to the arraylist doesn't work, f arrylist is always empty. In the output debug window, the only message that i receive is Unparseable date: "2014-12-09 00:00:00.0" for each Fattura.
private ArrayList<Fattura> getFatture() throws SQLException {
String localDb;
String unformattedQuery;
ArrayList<Fattura> ftt = new ArrayList<Fattura>();
if (this.serviceSelection.getSelectedItem() == "Energia") {
localDb = EmailCheckerGUI.DbEnergia;
unformattedQuery = ServiceQuery.RECUPERAFATTUREENERGIA.getQuery();
} else {
localDb = EmailCheckerGUI.DbGas;
unformattedQuery = ServiceQuery.RECUPERAFATTUREGAS.getQuery();
}
DbHandlerContext db = new DbHandlerContext(new SqlServerConcrete(EmailCheckerGUI.user, EmailCheckerGUI.pwd, localDb));
String formattedQuery = String.format(unformattedQuery,
BillIntervalContainer.getFormattedMinDataFatt("MM/dd/yyyy"),
BillIntervalContainer.getFormattedMaxDataFatt("MM/dd/yyyy"),
BillIntervalContainer.minFattNumber, BillIntervalContainer.maxFattNumber);
ResultSet r = db.executeQuery(formattedQuery);
while (r.next()) {
try {
boolean addingelement = false;
String ioError = "";
try {
addingelement = ftt.add(new Fattura(r.getInt("id"), r.getString("servizio"), r.getString("email"),
r.getString("denominazione"), r.getString("data_fattura"), r.getString("data_scadenza"), r.getString("path_fattura"),
r.getInt("inviato"), r.getString("report"), r.getInt("numero_fattura"), r.getInt("id_documento")));
} catch (IOException ex) {
Logger.getLogger(EmailCheckerGUI.class.getName()).log(Level.SEVERE, null, ex);
ioError = ex.getMessage();
}
if (!addingelement) {
if (!"".equals(ioError)) {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura"));
} else {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura") + ": " + ioError);
}
} else {
System.out.println(r.getString("numero_fattura"));
}
} catch (ParseException ex) {
System.out.println(ex.getMessage());
}
}
return ftt;
}
and
Fattura( int id, String service, String email,
String name, String dateBill, String dateScad, String path,
int sent, String report, int billNumber, int idDocument) throws ParseException, IOException{
this.id = id;
this.service = service;
this.email = email;
this.name = name;
this.path = path;
this.report = report;
this.sent = sent;
this.billNumber = billNumber;
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").parse(dateBill);
this.dateScad = new SimpleDateFormat("yyyy-MM-dd").parse(dateScad);
this.idDocument = idDocument;
this.pdfDocument = new PdfValidator(null, this.name, dateBill, String.valueOf(this.billNumber), String.valueOf(0), this.path);
}
Any idea of where i'm wrong?
Thanks
You are using week year : YYYY instead of year yyyy. Please take a look at the SimpleDateFormat documentation. You'll find all the patterns and some usefull examples.
Now yyyy-MM-dd will only parse 2014-12-09. If you have also time after date you should use something like :
yyyy-MM-dd HH:mm:ss.S
Or You can use .format instead of .parse :
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
but watch out that MM can't be lowercase.
Related
I am trying to parse a csv and map the fields to a POJO class. However I can see that the mapping is not achieved correctly.
I am trying to map the header from a POJO file to the csv.
public class CarCSVFileInputBean {
private long Id;
private String shortName;
private String Name;
private String Type;
private String Environment;
//getter and setters
}
Can someone please take a look at my code:
public class carCSVUtil {
private static Log log = LogFactory.getLog(carCSVUtil.class);
private static final List<String> fileHeaderFields = new ArrayList<String>();
private static final String UTF8CHARSET = "UTF-8";
static {
for (Field f : carCSVFileInputBean.class.getDeclaredFields()) {
fileHeaderFields.add(f.getName());
}
}
public static List<carCSVFileInputBean> getCSVInputList(InputStream inputStream) {
CSVReader reader = null;
List<carCSVFileInputBean> csvList = null;
carCSVFileInputBean inputRecord = null;
String[] header = null;
String[] row = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream, UTF8CHARSET));
csvList = new ArrayList<carCSVFileInputBean>();
header = reader.readNext();
boolean isEmptyLine = true;
while ((row = reader.readNext()) != null) {
isEmptyLine = true;
if (!(row.length == 1 && StringUtils.isBlank(row[0]))) { // not an empty line, not even containing ','
inputRecord = new carCSVFileInputBean();
isEmptyLine = populateFields(inputRecord, header, row);
if (!isEmptyLine)
csvList.add(inputRecord);
}
}
} catch (IOException e) {
log.debug("IOException while accessing carCSVFileInputBean: " + e);
return null;
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while accessing carCSVFileInputBean: " + e);
return null;
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while copying carCSVFileInputBean properties: " + e);
return null;
} catch (Exception e) {
log.debug("Exception while parsing CSV file: " + e);
return null;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ioe) {}
}
return csvList;
}
protected static boolean populateFields(carCSVFileInputBean inputRecord, String[] header, String[] row) throws IllegalAccessException, InvocationTargetException {
boolean isEmptyLine = true;
for (int i = 0; i < row.length; i++) {
String val = row[i];
if (!StringUtils.isBlank(val)) {
BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val);
isEmptyLine = false;
}
}
return isEmptyLine;
}
}
I found the solution - the headers in the csv file are expected to begin with a lowercase.
I'm trying to get a Date to Gmt+7 from listview Adapter :
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
_teamlist.clear();
db = new DBHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<TeamModel> team_list = getTeams2();
for (int i = 0; i < team_list.size(); i++) {
String tdate = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
Date datex = null;
try {
datex = sdf.parse(tdate);
} catch (ParseException e) {
e.printStackTrace();
}
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamdate(datex); ///// here the probleme !!!!!
_teamlist.add(_TeamModel);
}
}
in this line '_TeamModel.setTeamdate(datex)' the error : "setTeamdate java.lang.String in TeamModel cannot be applied to java.util.Date "
My get/set class TeamModel:
public class TeamModel {
public String teamdate="";
....
public String getTeamdate() {
return teamdate;
}
public void setTeamdate(String teamdate) {
this.teamdate = teamdate;
}
}
i tried to change teamdate in this class to date from string but it mess up my DBHelper
thanks to "mithrop" for his help, this's what i did to fix the problem :
String tname = team_list.get(i).getTeamname();
String topponent = team_list.get(i).getTeamopponent();
String tdate111 = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+9"));
Date datex = null;
try {
datex = sdf.parse(tdate111);
} catch (ParseException e) {
e.printStackTrace();
}
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String tdate = sdf.format(datex);
System.out.println(tdate);
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamname(tname);
_TeamModel.setTeamopponent(topponent);
_TeamModel.setTeamdate(tdate);
_teamlist.add(_TeamModel);
I'd like to know why my iterator shows only one result from my jsp. Here's my code in s:iterator:
<s:iterator value="origins" var="items">
<s:select list="#items" label="Select origin" name="origin">
</s:select>
</s:iterator>
And here's my code from action:
public class QueryAction{
private Sector sectorBean = null;
private List<String> origins;
private List<String> destinations;
public List<String> getOrigins() {
return origins;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
public List<String> getDestinations() {
return destinations;
}
public void setDestinations(List<String> destinations) {
this.destinations = destinations;
}
public String listing() {
SectorDA sda = new SectorDAImpl();
origins = sda.getOrigins();
destinations = sda.getDestinations();
return "success";
}
}
The values of both origin and destination are : New York, New Orleans, Michigan, Memphis, Chicago, and Pittsburgh. And both only showed Chicago. Can anyone help me?
-UPDATE-
I've discovered why the iterator shows only one result. It's because of the class' corresponding DA. Here are the codes:
private static final String GET_ALL_SECTORS = "SELECT cSectorId, cOrigin, cDestination, cWeekDay1, cWeekDay2, mFirstClassFare, mBusinessClassFare, mEconomyClassFare FROM Sector";
#Override
public List<Sector> getAllSectors() {
List<Sector> sectors = new ArrayList<Sector>();
Statement stat = null;
try {
stat = DatabaseConnector.getConnection().createStatement();
ResultSet rs = stat.executeQuery(GET_ALL_SECTORS);
if(rs.next()) {
String sectorId = rs.getString(1);
String origin = rs.getString(2);
String destination = rs.getString(3);
String weekDay1 = rs.getString(4);
String weekDay2 = rs.getString(5);
BigDecimal fcFare = rs.getBigDecimal(6);
BigDecimal bcFare = rs.getBigDecimal(7);
BigDecimal ecFare = rs.getBigDecimal(8);
Sector e = new Sector(sectorId, origin, destination, weekDay1, weekDay2, fcFare, bcFare, ecFare);
sectors.add(e);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return sectors;
}
Please help me.
I have using Google (GDATA) Gmail API for retrieving the contact list from gmail, It is working successfully on windows environment, but when I run the same code on Linux, I get error of Invalid Credentials.
I googled it, but can't get much help,
here is my code
public static String getGmailContactList() {
String response = "";
StringBuilder str = new StringBuilder();
String statusString = "";
ArrayList list = new ArrayList();
ContactsService myService = new ContactsService("");
String email = "xxxxx#gmail.com";
String password = "xxxxxxxx";
try
{
try
{
myService.setUserCredentials(email, password);
}
catch (AuthenticationException ex)
{
ex.printStackTrace();
//****I got exception here when using this code on LINUX ENVIORMENT** ***
}
response = printAllContacts(myService, email);
Iterator itr = list.iterator();
while (itr.hasNext())
{
ArrayList contact = (ArrayList) itr.next();
try
{
str.append(contact.get(1)).append(",");
}
catch (Exception e)
{
log.debug("Exception ocurred inside fethching gmail contact >
>
>
" + e);
str.append("no contacts found");
}
str.substring(0, str.length() - 1);
}
}
catch (Exception ae)
{
response = statusString;
log.debug("Exception ocurred inside ReadContacts : getGmailContactList()" + ae);
}
return response;
}
public static String printAllContacts(ContactsService myService, String emailSent)//
throws ServiceException, IOException
{
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/" + emailSent + "/full");
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(100);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
String phones = null;
String emails = null;
log.debug(resultFeed.getTitle().getPlainText());
StringBuilder contacts = new StringBuilder();
contacts.append("<?xml version=\"1.0\"><Contacts>");
for (int i = 0; i < resultFeed.getEntries().size(); i++)
{
contacts.append("<Contact>");
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi())
{
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
contacts.append("<Name>").append(fullNameToDisplay).append("</Name>");
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
StringBuilder emailIds = new StringBuilder();
if (entry.hasEmailAddresses())
{
List<Email> email = entry.getEmailAddresses();
if (email != null && email.size() > 0)
{
for (Email e : email)
{
emailIds.append(e.getAddress()).append(",");
}
emailIds.trimToSize();
if (emailIds.indexOf(",") != -1)
{
emails = emailIds.substring(0, emailIds.lastIndexOf(","));
}
contacts.append("<Email>").append(emails).append("</Email>");
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
contacts.append("</Contact>");
}
contacts.append("</Contacts>");
return contacts.toString();
}
so where I am lacking behind, some sort of help will be appriciated
here is the stack trace
com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:660)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at com.gmail.ReadContacts.getGmailContactList(ReadContacts.java:55)
We've got some data to store on S3 and want to be able to fetch the most recently uploaded file.
Any suggestions on the best way to accomplish this?
We're currently using the jets3t library.
Using Spring Boot:
#Service
public class AWSS3Service {
private static final Logger LOGGER = LogManager.getLogger(AWSS3Service.class);
#Autowired
private AmazonS3 amazonS3;
#Value("${aws.s3.bucket}")
private String bucketName;
#Value("${aws.s3.folder.download}")
private String foldernameDownload;
public byte[] downloadFile(final String typeName) {
byte[] content = null;
LOGGER.info("Downloading most recent file from {}", typeName);
ObjectListing objects = amazonS3.listObjects(bucketName,foldernameDownload+"/"+ typeName+"/");
Date tempDate = null;
S3ObjectSummary recentObj = null;
List<S3ObjectSummary> objectSummaries = objects.getObjectSummaries();
for (S3ObjectSummary objectSummary : objectSummaries) {
if (objectSummary.getSize()<=0)
continue;
Date modifiedDate = objectSummary.getLastModified();
if(tempDate == null || modifiedDate.compareTo(tempDate) > 0) {
tempDate = modifiedDate;
recentObj = objectSummary;
}
}
String obKey ="";
if(recentObj != null)
obKey = recentObj.getKey();
else
return content;//no files found
S3Object s3Object = amazonS3.getObject(bucketName,obKey);
S3ObjectInputStream stream = s3Object.getObjectContent();
try {
content = IOUtils.toByteArray(stream);
LOGGER.info("File downloaded successfully.");
s3Object.close();
} catch(final IOException ex) {
LOGGER.error("IO Error Message= {}", ex.getMessage());
}
return content;
}
}
This might help..
S3Service s3Service = new S3Service(providerCredentials);
Date tempDate = null;
S3Object recentObj = null;
for(S3Object object : s3Service.listObjects("bucketName")) {
modifiedDate =(Date)object.getMetadata(BaseStorageItem.METADATA_HEADER_LAST_MODIFIED_DATE);
if(tempDate == null) {
tempDate = modifiedDate;
} else {
if(modifiedDate.compareTo(tempDate) < 0) {
tempDate = modifiedDate;
recentObj = object;
}
}
}
I have not tested this code. Hope this helps..