Helo, I've got this code, which query the instances in calendarcontract:
Uri uri = Uri.parse(CalendarContract.Instances.CONTENT_URI + "/" +
Long.toString(from) + "/" +
Long.toString(to));
String[] mProjection =
{
CalendarContract.Instances._ID,
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.CALENDAR_ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.EVENT_COLOR,
CalendarContract.Instances.DTSTART,
CalendarContract.Instances.DTEND,
CalendarContract.Instances.EVENT_TIMEZONE,
CalendarContract.Instances.EVENT_END_TIMEZONE,
CalendarContract.Instances.DURATION,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.RDATE,
CalendarContract.Instances.EXDATE
};
ContentResolver cr2 = this.c.getContentResolver();
String selection2 = "( " + selection_allcalendars + " (" + CalendarContract.Instances.RRULE + " IS NOT NULL) AND (deleted != 1) AND (" + CalendarContract.Instances.ALL_DAY + " = 0))";
Cursor cur2 = cr2.query(uri, mProjection, selection2, null, CalendarContract.Instances.DTSTART + " ASC");
How can I remove double instances from query? I want to use a "GROUP BY" clause, but I don't know how to do that.
Please help me :-)
Thanks!
Edit:
I want to group by EVENT_ID, because I get multiple entries. This ist the whole code I use for recurring events:
ContentResolver cr2 = this.c.getContentResolver();
String selection2 = "( " + selection_allcalendars + " (" + CalendarContract.Instances.RRULE + " IS NOT NULL) AND (deleted != 1) AND (" + CalendarContract.Instances.ALL_DAY + " = 0))";
Cursor cur2 = cr2.query(uri, mProjection, selection2, null, CalendarContract.Instances.DTSTART + " ASC");
ArrayList<String> checkexists = new ArrayList<>();
while (cur2.moveToNext()) {
String eventid = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.EVENT_ID));
if(checkexists.contains(eventid)) {
}
else {
checkexists.add(eventid);
String rrule = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.RRULE));
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
Long dtstart;
try {
dtstart = Long.parseLong(cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.DTSTART)));
dtstart = tz.getOffset(dtstart) + dtstart;
} catch (NumberFormatException e) {
dtstart = 0l;
}
Long dtend;
try {
dtend = dtstart + RFC2445ToMilliseconds(cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.DURATION)));
/* dtend = Long.parseLong(cur.getString(cur.getColumnIndex(CalendarContract.Events.DTEND)));
dtend = tz.getOffset(dtend) + dtend; */
} catch (NumberFormatException e) {
dtend = 0l;
}
Calendar cal4 = Calendar.getInstance();
cal4.setTimeInMillis(dtstart);
LocalDate localdate = new LocalDate(cal4.get(Calendar.YEAR), cal4.get(Calendar.MONTH) + 1, cal4.get(Calendar.DAY_OF_MONTH));
long calendar_id = Long.valueOf(cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.CALENDAR_ID)));
String id = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances._ID));
String title = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.TITLE));
String eventlocation = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.EVENT_LOCATION));
String description = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.DESCRIPTION));
String eventcolor = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.EVENT_COLOR));
String eventtimezone = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.EVENT_TIMEZONE));
String eventtimezone_end = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.EVENT_END_TIMEZONE));
String duration = cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.DURATION));
int allday = Integer.valueOf(cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.ALL_DAY)));
rrule = "RRULE:" + rrule;
long lastrecurrencetime;
if(rrule.contains("UNTIL")) {
lastrecurrencetime = RruleHelper.getUntil(rrule).getTimeInMillis();
}
else {
lastrecurrencetime = -1;
}
//System.out.println("EEE: " + title + " " + rrule);
try {
ArrayList<ReadEvent> recurrenceevents = new ArrayList<>();
for (LocalDate date : LocalDateIteratorFactory.createLocalDateIterable(rrule, localdate, true)) {
// System.out.println("GGG:" + title + " " + i);
Calendar newcal_from = Calendar.getInstance();
newcal_from.setTimeInMillis(dtstart);
newcal_from.set(Calendar.DAY_OF_MONTH, date.getDayOfMonth());
newcal_from.set(Calendar.MONTH, date.getMonthOfYear() - 1);
newcal_from.set(Calendar.YEAR, date.getYear());
long dtstart_new = newcal_from.getTimeInMillis();
long dtend_new = dtstart_new + RFC2445ToMilliseconds(cur2.getString(cur2.getColumnIndex(CalendarContract.Instances.DURATION)));
if (dtstart_new >= from && dtstart_new <= to) {
ReadEvent newreadevent = new ReadEvent(calendar_id, id, eventid, title, eventlocation, description, eventcolor, dtstart_new, dtend_new, eventtimezone, eventtimezone_end, duration, allday, rrule);
newreadevent.setFirstReccurenceTime(dtstart);
newreadevent.setLastReccurenceTime(lastrecurrencetime);
if(!checkIfAlreadyExits(readevent, newreadevent)) {
//newreadevent.setReccurenceCount(i);
readevent.add(newreadevent);
}
}
if (dtstart_new > to) {
break;
}
}
} catch (Exception e) {
}
}
}
Related
I debugging my application then I tried clicking twice and fast on the pretty dialog button and it print twice I expect that even I clicked twice it will not print twice.
I tried error handler codes but it was not working.
prettyDialog.addButton("YES",
R.color.navy_blue,
R.color.gold_yellow,
new PrettyDialogCallback() {
#Override
public void onClick() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
raw_serial = String.valueOf(Build.SERIAL);
serial_final = raw_serial.substring(raw_serial.length() - 7);
nf = new DecimalFormat("000000");
DateFormat dateFormat = new SimpleDateFormat("MMddyyyy");
Date date = new Date();
ticket_date = dateFormat.format(date).toString();
DateFormat datetimeformat = new SimpleDateFormat("HHmmss");
Date time = new Date();
ticket_time = datetimeformat.format(time).toString();
transaction_no = serial_final + ticket_date + ticket_time + nf.format(setting_last_transaction_no);
trace_no = merchant_code + serial_final + ticket_date + ticket_time + nf.format(ref_trace_no);
print_card_no = Cardno.substring(Cardno.length() - 4);
String print_balance;
print_balance = "P" + String.valueOf(Balance);
int balancespace = 0;
int balancelength = 0;
balancelength = print_balance.length();
balancespace = 13 - balancelength;
for (int j = 0; j < balancespace; j++) {
print_balance = " " + print_balance;
}
int print = PrinterInterface.open();
Log.e("print", String.valueOf(print));
int querystatus = PrinterInterface.queryStatus();
Log.e("querystatus", String.valueOf(querystatus));
DateFormat dateformatforprint = new SimpleDateFormat("MMM.dd,yyyy");
Date dateformatprint = new Date();
String datetoprint = dateformatforprint.format(dateformatprint).toString();
DateFormat timeformattoprint = new SimpleDateFormat("HH:mm");
Date timeformat = new Date();
String timetoprint = timeformattoprint.format(timeformat).toString();
String finalStation = "";
Log.e("asdasd", "asdasd");
if (print >= 0) {
byte[] arryTitle = null;
byte[] arryTrx = null;
byte[] arrySubtitle = null;
byte[] arryBody1 = null;
byte[] arryspace1 = null;
byte[] arryFooter = null;
//test
try {
arryTitle = ("\n" + "TRIPKO" + "\n" + "\n").getBytes("UTF-8");
arryTrx = ("TRX: " + transaction_no + "\n" +
trace_no + "\n").getBytes("UTF-8");
arrySubtitle = ("Date & Time : " + datetoprint + " " + timetoprint + "\n" +
"Merchant Name: " + subcompany_name.toUpperCase() + "\n" +
"Branch : " + terminal_name.toUpperCase() + "\n" +
"-------------------------------" + "\n" +
"\n").getBytes("UTF-8");
arryBody1 = ("Card No. : " + " **** **** **** " + print_card_no + "\n" +
"Trans Type : " + " " + type_name.toUpperCase() + "\n" +
"Current Balance : " + print_balance + "\n" +
"-------------------------------" + "\n" +
"\n").getBytes("UTF-8");
arryFooter = ("Customer Service" + "\n"
+ "Hotline#: TRIPKO(678-1234)" + "\n" +
"\n").getBytes("UTF-8");
arryspace1 = "\n".getBytes("UTF-8");
} catch (Throwable e) {
e.printStackTrace();
}
begin();
if (querystatus == 1) {
writeLineBreak(20);
write(arryspace1);
alignment(1);
Fontsize(16);
boldFont(2);
doublewidth();
write(arryTitle);
backtonormal();
nextline();
Fontsize(0);
write(arryTrx);
alignment(0);
write(arrySubtitle);
write(arryBody1);
alignment(1);
write(arryFooter);
write(arryspace1);
write(arryspace1);
write(arryspace1);
write(arryspace1);
insertData(company_id,
subcompany_id,
terminal_id,
setting_control_no,
Cardno,
Balance,
transaction_no,
trace_no,
device_serial);
setting_last_transaction_no += 1;
ref_trace_no += 1;
updateTicket(String.valueOf(setting_last_transaction_no),
String.valueOf(ref_trace_no));
DBBackup();
end();
btnCheckBalance.setEnabled(true);
btnCheckBalance.setClickable(true);
Intent intent2 = new Intent(getContext(), UpdateSendingServices.class);
getActivity().startService(intent2);
} else {
//OpenNoPaper();
}
}
PrinterInterface.close();
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
totalBalance.setText("P 0.00");
btnCheckBalance.setEnabled(true);
btnCheckBalance.setClickable(true);
}
});
prettyDialog.dismiss();
}
})
.show();
I expect that it will not print twice even I clicked the "YES" pretty dialog button.
i think you can just do a trick like this
create a count variable count=0;. In button click, validate condition such that if(count==0) show dialog and make count = 1. (with this dialog will not open second time) while dismissing dialog make count = 0 again.
I think this will work
Hope it helps.
if(count == 0){
count = 1 ;
//showdialog process
}
and right before dismiss()
......
count = 0;
prettyDialog.dismiss();
I've been implementing an app, and was doing a DAO class with a function, which would return all events on current day. But, I have a small bug. For example: we have 2 events - event1(02:00-03:00) and event2(14:00-16:00). And we want event1 to be the first in the row. Okay, we have implemented a sort which does it, but! event2 is 1516024800000 ms and event1 is 1542618000000.
I know that to give u a working sample would be helpful, but i am not able to...
Here is this function:
public List<Schedule> getScheduleByDate(int year, int month, int day, String Account) {
List<Schedule> schedules = new ArrayList<>();
List<CalendarClass> calendarClasses = mCalendarClassDao.getTrueCalendars();
/*if(Account.equals("ANONYMOUS")){
return schedules;
}*/
String[] INSTANCE_PROJECTION = new String[]{
CalendarContract.Instances.CALENDAR_ID, // 0
CalendarContract.Instances.TITLE, // 1
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.DTSTART,
CalendarContract.Instances.DTEND,
CalendarContract.Instances.DISPLAY_COLOR,
CalendarContract.Instances.EVENT_COLOR,
CalendarContract.Instances.EVENT_COLOR_KEY,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.OWNER_ACCOUNT,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.ORIGINAL_INSTANCE_TIME
};
Calendar startTime = Calendar.getInstance();
startTime.set(year, month, day, 0, 0, 0);
long time = startTime.getTimeInMillis();
//time -= 1000;
//end fix
Calendar endTime = Calendar.getInstance();
endTime.set(year, month, day, 23, 59, 59);
long endMillis = endTime.getTimeInMillis();
for (int i = 0; i < calendarClasses.size(); ++i) {
//String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + time + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'" + " ))";
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.READ_CALENDAR}, 1000);
}
String selection = CalendarContract.Instances.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'";
//Cursor cursor = mContext.getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, selection, null, null);
// sort
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, time);
ContentUris.appendId(builder, endMillis);
Cursor cursor = mContext.getContentResolver().query(builder.build(),
INSTANCE_PROJECTION,
selection,
null,
CalendarContract.Instances.DTSTART);
while (cursor.moveToNext()){
Log.wtf("1", "1");
Schedule schedule = new Schedule();
schedule.setTitle(cursor.getString(1));
schedule.setDesc(cursor.getString(2));
schedule.setTime(cursor.getLong(3));
schedule.setTime_end(cursor.getLong(4));
schedule.setColor(cursor.getInt(5));
schedule.setLocation(cursor.getString(9));
schedule.setAccount(cursor.getString(10));
schedule.setRepeat(cursor.getString(11));
schedules.add(schedule);
}
cursor.close();
}
Log.wtf("wtf", String.valueOf(schedules.size()));
if (schedules.size() > 1) {
int i = 0;
int goodPairsCounter = 0;
while (true) {
long time1 = schedules.get(i).getTime();
long time2 = schedules.get(i + 1).getTime();
Log.wtf("TIME", String.valueOf(time1) + " - " + String.valueOf(time2));
Log.wtf("TIME", schedules.get(i).getTitle() + " - " + schedules.get(i+1).getTitle());
if (time1 > time2) {
Log.wtf("TIME", "hop");
Schedule sh = new Schedule(schedules.get(i).getId(), schedules.get(i).getColor(), schedules.get(i).getTitle(), schedules.get(i).getDesc(), schedules.get(i).getLocation(), schedules.get(i).getState(), schedules.get(i).getTime(), schedules.get(i).getTime_end(), schedules.get(i).getYear(), schedules.get(i).getRepeat(), schedules.get(i).getAccount());
schedules.remove(i);
schedules.add(i + 1, sh);
goodPairsCounter = 0;
} else {
goodPairsCounter++;
}
i++;
if (i == schedules.size() - 1) {
i = 0;
}
if (goodPairsCounter == schedules.size() - 1) break;
}
}
return schedules;
}
Here is a screenshot
Need to know how to solve this problem
CLOSED. Didn't solve it yet. If you are stuck then just find another approach
I want to convert dataframe to Array of Json using Java and Spark version 1.6, for which am converting the data from
Dataframe -> Json -> RDD -> Array
where the data looks like this.
[
{
"prtdy_pgm_x":"P818_C",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Cost",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:19.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
{
"prtdy_pgm_x":"P818_I",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Tooling",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:20.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
{
"prtdy_pgm_x":"P818_W",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Weight",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:20.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
......
]
so I wrote my code something like this.
if(cmnTableNames != null && cmnTableNames.length > 0)
{
for(int i=0; i < cmnTableNames.length; i++)
{
String cmnTableName = cmnTableNames[i];
DataFrame cmnTableContent = null;
if(cmnTableName.contains("PTR_security_t"))
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName + " where fbrn04_snapshot_d = '" + snapshotId + "'");
}
else
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName);
}
String cmnTable = cmnTableName.substring(cmnTableName.lastIndexOf(".") + 1);
if (cmnTableContent.count() > 0)
{
String cmnStgTblDir = hdfsPath + "/staging/" + rptName + "/common/" + cmnTable;
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2); //This Part, takes more time than usual contains large set of data.
String output = "["+result+"]";
ArrayList<String> outputList = new ArrayList<String>();
outputList.add(output);
JavaRDD<String> finalOutputRDD = sc.parallelize(outputList);
String cmnStgMrgdDir = cmnStgTblDir + "/mergedfile";
if(dfs.exists(new Path(cmnStgTblDir + "/mergedfile"))) dfs.delete(new Path(cmnStgTblDir + "/mergedfile"), true);
finalOutputRDD.coalesce(1).saveAsTextFile(cmnStgMrgdDir, GzipCodec.class);
fileStatus = dfs.getFileStatus(new Path(cmnStgMrgdDir + "/part-00000.gz"));
dfs.setPermission(fileStatus.getPath(),FsPermission.createImmutable((short) 0770));
dfs.rename(new Path(cmnStgMrgdDir + "/part-00000.gz"), new Path(CommonPath + "/" + cmnTable + ".json.gz"));
}
else
{
System.out.println("There are no records in " + cmnTableName);
}
}
}
else
{
System.out.println("The common table lists are null.");
}
sc.stop();
but while reduce function is applied it's taking more time
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2); //This Part, takes more time than usual contains large set of data.
the table with the partition "PTR_security_t" is huge and takes a lot of time compared to other tables which don't have partitions (40-50 mins odd for 588kb)
I Tried Applying Lambda but i ended up with Task not serializable error. Check the code below.
if(cmnTableNames != null && cmnTableNames.length > 0)
{
List<String> commonTableList = Arrays.asList(cmnTableNames);
DataFrame commonTableDF = sqc.createDataset(commonTableList,Encoders.STRING()).toDF();
commonTableDF.toJavaRDD().foreach(cmnTableNameRDD -> {
DataFrame cmnTableContent = null;
String cmnTableName = cmnTableNameRDD.mkString();
if(cmnTableName.contains("PTR_security_t"))
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName + " where fbrn04_snapshot_d = '" + snapshotId + "'");
}
else
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName);
}
String cmnTable = cmnTableName.substring(cmnTableName.lastIndexOf(".") + 1);
if (cmnTableContent.count() > 0)
{
String cmnStgTblDir = hdfsPath + "/staging/" + rptName + "/common/" + cmnTable;
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2);
String output = "["+result+"]";
ArrayList<String> outputList = new ArrayList<String>();
outputList.add(output);
JavaRDD<String> finalOutputRDD = sc.parallelize(outputList);
String cmnStgMrgdDir = cmnStgTblDir + "/mergedfile";
if(dfs.exists(new Path(cmnStgTblDir + "/mergedfile"))) dfs.delete(new Path(cmnStgTblDir + "/mergedfile"), true);
finalOutputRDD.coalesce(1).saveAsTextFile(cmnStgMrgdDir, GzipCodec.class);
fileStatus = dfs.getFileStatus(new Path(cmnStgMrgdDir + "/part-00000.gz"));
dfs.setPermission(fileStatus.getPath(),FsPermission.createImmutable((short) 0770));
dfs.rename(new Path(cmnStgMrgdDir + "/part-00000.gz"), new Path(CommonPath + "/" + cmnTable + ".json.gz"));
}
else
{
System.out.println("There are no records in " + cmnTableName);
}
});
}
else
{
System.out.println("The common table lists are null.");
}
sc.stop();
is there any efficient way where i can enhance my Performance ?
Why doesn't this query work?
query = "SELECT itm.itemId, itm.itemModel, itm.itemDescription, "
+ " itmImages.imageFileName, part.participant_id "
+ " FROM Users user "
+ " INNER JOIN user.participant part "
+ " INNER JOIN part.addresses addr "
+ " INNER JOIN part.item itm "
+ " INNER JOIN itm.itemImages itmImages "
+ " WHERE user.userType LIKE '%borrow%') AND itm.itemDescription LIKE '%mower%') AND addr.addressType = 'primary'";
It always returns all items, disregards itemDescription LIKE... I checked the database and all of the join ids are fine
This works:
query = "SELECT user"
+ " FROM Users user "
+ " INNER JOIN user.participant part "
+ " INNER JOIN part.addresses addr "
+ " WHERE user.userType LIKE '%borrow%') AND addr.addressType = 'primary'";
I have a table Users. It has a one-to-many association with table Participant.
In Users.java I have..
private Set<Participant> participant = new HashSet<Participant>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.Participant")
#JoinColumn(name = "user_id")
public Set<Participant> getParticipant() {
return participant;
}
public void setParticipant(Set<Participant> participant) {
this.participant = participant;
}
This join works fine.
In Participant.java I have
private Set<Addresses> addresses = new HashSet<Addresses>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.Addresses")
#JoinColumn(name = "participant_id")
public Set<Addresses> getAddresses() {
return addresses;
}
public void setAddresses(Set<Addresses> addresses) {
this.addresses = addresses;
}
And
private Set item = new HashSet();
With
#OneToMany
#JoinTable(name = "echomarket.hibernate.Items")
#JoinColumn(name = "participant_id")
public Set<Items> getItem() {
return item;
}
No association statement with regard to Users.
In Addresses.java I make no associations.
In Items.java I have
private Set<ItemImages> itemImages = new HashSet<ItemImages>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.ItemImages")
#JoinColumn(name = "itemId")
public Set<ItemImages> getItemImages() {
return itemImages;
}
public void setItemImages(Set<ItemImages> itemImages) {
this.itemImages = itemImages;
}
In ItemImages.java I make no associations...
Very much thanks for your help. If you need more information, please just ask...
Liz
Couldn't get the above INNER JOIN query to work-- intended for a search that involves many tables. I tested each JOIN independently successfully, but together the JOIN does not work. Also had problems with query recognizing LIKE statement. I worked really hard to find solutions. So I rewrote with the following, data gathering is split in two query calls. The following works:
public String SearchResults() {
Session sb = null;
Transaction tx = null;
String queryString = "";
String forceString = this.found_zip_codes;
List results = null;
String fromStatement = "";
if (this.lenderOrBorrower == 2) {
this.which = "borrow";
} else {
this.which = "lend";
}
this.imageLibrary = this.which + "_images";
fromStatement = " SELECT part "
+ " FROM Participant part "
+ " INNER JOIN part.addresses addr "
+ " WHERE addr.addressType = 'primary' ";
if (ubean.getComDetailID() != null) {
fromStatement = fromStatement + " AND part.communityId = \'" + ubean.getComDetailID() + "\' ";
} else {
fromStatement = fromStatement + " AND part.communityId = ''";
}
if (this.postalCode.isEmpty() == false) {
fromStatement = fromStatement + " OR addr.postalCode LIKE \'" + this.postalCode + "%\'";
}
try {
sb = hib_session();
tx = sb.beginTransaction();
results = sb.createQuery(fromStatement).list();
tx.commit();
} catch (Exception ex) {
tx.rollback();
Logger.getLogger(SearchesBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
tx = null;
sb = null;
}
String[] pids = new String[results.size()];
String hold_pid = "";
if (results != null) {
if (results.size() > 0) {
for (int i = 0; i < results.size(); i++) {
Participant cArray = (Participant) results.get(i);
if (cArray.getParticipant_id().isEmpty() == false) {
hold_pid = "\'" + cArray.getParticipant_id() + "\'";
pids[i] = hold_pid;
}
}
hold_pid = String.join(",", pids);
}
}
results = null;
fromStatement = " FROM Items itm WHERE itm.itemType = :which "
+ (hold_pid.isEmpty() ? "" : " AND itm.participant_id IN ( " + hold_pid + " )");
if ((this.startDate.isEmpty() == false) && (this.endDate.isEmpty() == false)) {
try {
queryString = queryString + " OR ";
queryString = queryString + " ( itm.dateCreated >= \'" + this.startDate + "\' AND itm.dateCreated <= \'" + this.endDate + "\' ) ";
} catch (Exception ex) {
Logger.getLogger(SearchesBean.class.getName()).log(Level.INFO, null, ex);
}
}
forceString = this.keyword;
if (forceString.isEmpty() == false) {
queryString = queryString + " OR ";
queryString = queryString + " (itm.itemDescription like \'%" + forceString + "%\' OR itm.itemModel like \'%" + forceString + "%\')";
}
if ((this.categoryId != -2)) {
queryString = queryString + " OR";
queryString = queryString + " itm.categoryId = " + this.categoryId;
}
fromStatement = fromStatement + queryString;
try {
sb = hib_session();
tx = sb.beginTransaction();
results = sb.createQuery(fromStatement).setParameter("which", this.which).list();
tx.commit();
} catch (Exception ex) {
tx.rollback();
Logger.getLogger(SearchesBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
tx = null;
sb = null;
}
this.itemDetail = results;
return "search";
}
I was using the exact same query yesterday and it was working fine today I made a few changes to flow of the program and the query no longer returns and rows.
the first function that my programs goes to:
public void prepareSummary(Date startDate , Date endDate)
{
int getStartDay = getDayFromDate(startDate);
int getStartMonth = getMonthFromDate(startDate);
//
int getEndDay = getDayFromDate(endDate);
int getEndMonth = getMonthFromDate(endDate);
int getYear = getYearFromDate(startDate);
if(getStartMonth <= getEndMonth)
{
if(getStartMonth == getEndMonth)
{
if(getStartDay < getEndDay)
{
while(getStartDay <= getEndDay)
{
Calendar cal = Calendar.getInstance();
cal.set( getYear, getStartMonth, getStartDay);
Date queryStart = getStartOfDay(cal.getTime());
Date queryEnd = getEndOfDay(cal.getTime());
List<Object[]> res = getSumList(queryStart, queryEnd);
doQuery(res);
++getStartDay;
}
}
else
{
}
}
else
{
}
}
else
{
}
}
Here is what getSumList looks like:
public List<Object[]> getSumList(Date start, Date end) {
String query = "";
query += "SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s , GradeNames g , SpecieNames p, ShiftTimes t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " AND s.specieNameIndex = p.nameIndex "
+ " AND s.gradeNameIndex = g.nameIndex"
+ " AND s.shiftIndex = t.shiftIndex"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";
Query q = em.createQuery(query);
q.setParameter("start", start);
q.setParameter("end", end);
return q.getResultList();
}
This next function doesn't matter at this point because nothing is being executed because the list length is zero:
private void doQuery(List<Object[]> obj)
{
int length = obj.size();
String grade = null;
Long standingCount = (long) 0;
System.out.println("Length" + length);
for (int i = 0; i < length; ++i) {
// HAVE A LIST OF ALL ITEMS PULLED FROM DATABASE
Object[] tmpObj = obj.get(i);
Long tmpCount = (Long) tmpObj[0];
String tmpSpecieName = (String) tmpObj[1];
Double tmpThickness = Double.parseDouble(getSpecie().getThicknessFromSpecie(tmpSpecieName));
String tmpLength = getSpecie().getLengthFromSpecie(tmpSpecieName);
String tmpGradeName = (String) tmpObj[2];
String tmpShift = (String) tmpObj[3];
tmpSpecieName = getSpecie().getSpecieFromSpecie(tmpSpecieName);
//// END OF ALL ITEMS PULLED FROM DATABASE
if (grade != pullGradeName(tmpGradeName) && grade != null) {
System.out.println("Count:" + standingCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
// do previous insert
grade = pullGradeName(tmpGradeName);
} else if (grade != pullGradeName(tmpGradeName) && grade == null) {
grade = pullGradeName(tmpGradeName);
} else if (grade == pullGradeName(tmpGradeName)) {
standingCount = standingCount + tmpCount;
}
System.out.println("Count:" + tmpCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
}
}
Check the SQL that is generated, and the tables you are querying over. As the query requires inner joins, if one of the tables was cleared, it would return no results. If you want to get a 0 count, you need to use an outer join syntax which isn't possible in JPA unless you use object level mappings:
"SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s outer join s.specialNameIndex p,"
+ " outer join s.gradeNameIndex g, outer join s.shiftIndex t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";