Java/J2EE Internal Server Error - java

I have a DaoHibernateImpl file which is breaking my application. Here is the code for this and its xml.
public class OfferBankDaoHibernateImpl extends GenericDaoHibernateImpl<OfferBank, Long> implements OfferBankDao {
static Logger log = Logger.getLogger(OfferBankDaoHibernateImpl.class);
private ResourceManager rMgr = new ResourceManager(this);
public List<OfferBank> findOfferBankByName(String offerBankNm) throws AppException {
List<OfferBank> offerBanks = new ArrayList<OfferBank>();
try {
// offerBanks =
// sessionFactory.getCurrentSession().createCriteria(OfferBank.class)
// .add( Restrictions.eq("offerBankNm", offerBankNm))
// .list();
offerBanks = sessionFactory.getCurrentSession().createQuery("from OfferBank ob where ob.offerBankNm = '" + offerBankNm + "'").list();
} catch (GenericJDBCException e) {
log.error(e.getMessage(), e);
throw new AppException(e.getMessage(), e);
} catch (HibernateException e) {
log.error(e.getMessage(), e);
throw new AppException(e.getMessage(), e);
}
return offerBanks;
}
public Object[] getOfferBanks(List<String> offerBankTypes, int startPos, int endPos, List<Long> statusIds) {
int totalRowCount = 1000000;
try {
if (endPos == 0) {
endPos = totalRowCount;
}
String dataSql = rMgr.get("sql.offer_bank_get_banks");
dataSql += " " + rMgr.get("sql.offer_bank_get_banks_types_where");
if (!statusIds.isEmpty()) {
dataSql += " " + rMgr.get("sql.offer_bank_get_banks_status_where");
}
dataSql += " " + rMgr.get("sql.offer_banks_get_banks_group_by");
log.debug("query : " + dataSql);
SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
if (!statusIds.isEmpty()) {
dataQuery.setParameterList("offerBankStatusIds", statusIds);
}
dataQuery.setParameterList("offerBankTypes", offerBankTypes).setParameter("start", startPos).setParameter("end", endPos);
List offerBankList = dataQuery.list();
return makeOfferBankTO(offerBankList);
} catch (RuntimeException e) {
log.error("Error getOfferBanks(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)");
throw e;
}
}
public Object[] getOfferBanksByBanner(List<String> offerBankTypes, int startPos, int endPos, List<Long> statusIds) {
int totalRowCount = 1000000;
try {
if (endPos == 0) {
endPos = totalRowCount;
}
String dataSql = rMgr.get("sql.offer_bank_get_banks_by_banner");
dataSql += " " + rMgr.get("sql.offer_bank_get_banks_types_where");
if (!statusIds.isEmpty()) {
dataSql += " " + rMgr.get("sql.offer_bank_get_banks_status_where");
}
dataSql += " " + rMgr.get("sql.offer_banks_get_banks_by_banner_group_by");
log.debug("query : " + dataSql);
SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
if (!statusIds.isEmpty()) {
dataQuery.setParameterList("offerBankStatusIds", statusIds);
}
dataQuery.setParameterList("offerBankTypes", offerBankTypes).setParameter("start", startPos).setParameter("end", endPos);
List offerBankList = dataQuery.list();
return makeOfferBankTO(offerBankList);
} catch (RuntimeException e) {
log.error("Error getOfferBanksByBanner(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)");
throw e;
}
}
public Object[] getOfferBankById(List<Long> offerBankIds) {
int startPos = 1;
int endPos = 100000;
String dataSql = rMgr.get("sql.offer_bank_get_banks");
dataSql += " " + rMgr.get("sql.offer_bank_get_banks_ids_where");
dataSql += " " + rMgr.get("sql.offer_banks_get_banks_group_by");
log.debug("sql= " + dataSql);
SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
dataQuery.setParameterList("offerBankIds", offerBankIds).setParameter("start", startPos).setParameter("end", endPos);
List offerBankList = dataQuery.list();
return makeOfferBankTO(offerBankList);
}
private Object[] makeOfferBankTO(List offerBankList) {
int totalRowCount = 0;
List<OfferBankTO> offerBankTOs = new ArrayList<OfferBankTO>();
Iterator iter = offerBankList.iterator();
while (iter.hasNext()) {
Object[] row = (Object[]) iter.next();
OfferBankTO ob = new OfferBankTO();
ob.setOfferBankId(((BigDecimal) row[0]).longValue());
ob.setPromotionalPeriodId(((BigDecimal) row[1]).longValue());
ob.setOfferBankName(row[2].toString());
ob.setOfferBankStatusDesc(row[3].toString());
if (row[4] != null) {
ob.setStartDate(DateFormats.dateFmt.format((Date) row[4]));
}
if (row[5] != null) {
ob.setEndDate(DateFormats.dateFmt.format((Date) row[5]));
}
ob.setOfferBankTypeDesc(row[6].toString());
ob.setOfferBankTypeCd(row[7].toString());
ob.setPromotionalPeriodNm(row[8].toString());
ob.setTotalCount(((Integer) row[9]).intValue());
ob.setEditingCount(((Integer) row[10]).intValue());
ob.setFailedDeactiveCount(((Integer) row[11]).intValue());
ob.setFailedProductionCount(((Integer) row[12]).intValue());
ob.setFailedPreviewCount(((Integer) row[13]).intValue());
ob.setLoadedCount(((Integer) row[14]).intValue());
ob.setPendingCount(((Integer) row[15]).intValue());
ob.setParkedCount(((Integer) row[16]).intValue());
ob.setSuccessDeactivatedCount(((Integer) row[17]).intValue());
ob.setSuccessLoadedProdCount(((Integer) row[18]).intValue());
ob.setSuccessLoadedPreviewCount(((Integer) row[19]).intValue());
ob.setTotalPendingCount(((Integer) row[20]).intValue());
ob.setTotalFailedCount(((Integer) row[21]).intValue());
totalRowCount = ((Integer) row[22]).intValue();
if (row[24] != null)
ob.setMaxOfferEffectiveEndDt(DateFormats.dateFmt.format((Date) row[24]));
if (row[25] != null)
ob.setMinOfferEffectiveStartDt(DateFormats.dateFmt.format((Date) row[25]));
ob.setEndedCount(((Integer) row[26]).intValue());
ob.setCopientDelayCount(((Integer) row[27]).intValue());
ob.setRejectedCount(((Integer) row[28]).intValue());
ob.setProcessingCount(((Integer) row[29]).intValue());
if (row.length > 30) {
if (row[30] != null) {
ob.setRegionId(row[30].toString());
}
if (row[31] != null) {
ob.setRegionNm(row[31].toString());
}
}
offerBankTOs.add(ob);
}
return new Object[] { totalRowCount, offerBankTOs };
}
public Object[] getBankTypes() {
List<OfferBankTypeTO> offerBankTypes = new ArrayList<OfferBankTypeTO>();
try {
String sql = rMgr.get("sql.offer_bank_types");
SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);
List typeList = query.list();
Iterator iter = typeList.iterator();
while (iter.hasNext()) {
Object[] row = (Object[]) iter.next();
OfferBankTypeTO type = new OfferBankTypeTO();
type.setOfferBankTypeCd(row[0].toString());
type.setOfferBankTypeDesc(row[1].toString());
offerBankTypes.add(type);
}
} catch (RuntimeException e) {
log.error("Error List<OfferBankType> getBankTypes()");
throw e;
}
return new Object[] { offerBankTypes };
}
public void updateOfferBank(OfferBank offerBank, Context ctx) {
String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
.getUserName() : SharedMessages.getString("user.default");
offerBank.setLastUpdtTs(new Date(System.currentTimeMillis()));
offerBank.setLastUpdtUserId(user);
this.makePersistent(offerBank);
}
public OfferBank addOfferBank(OfferBank offerBank, Context ctx) {
String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
.getUserName() : SharedMessages.getString("user.default");
Date now = new Date(System.currentTimeMillis());
offerBank.setLastUpdtTs(now);
offerBank.setLastUpdtUserId(user);
offerBank.setCreationUserId(user);
offerBank.setCreationTs(now);
return this.insert(offerBank);
}
public int updateCurrentBankStatus(OfferBank offerBank, Context ctx) {
String sql = rMgr.get("sql.update_current_bank_status");
SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setParameter("offer_bank_id", offerBank.getOfferBankId());
return query.executeUpdate();
}
public void insertBankStatus(OfferBank offerBank, short newStatusId, Context ctx) {
String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
.getUserName() : SharedMessages.getString("user.default");
OfferBankStatus offerBankStatus = new OfferBankStatus();
OfferBankStatusId offerBankStatusId = new OfferBankStatusId();
Date now = new Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
offerBankStatusId.setOfferBankId(offerBank.getOfferBankId());
offerBankStatusId.setEffectiveStartDt(now);
offerBankStatus.setId(offerBankStatusId);
offerBankStatus.setCreationTs(now);
offerBankStatus.setCreationUserId(user);
offerBankStatus.setEffectiveEndDt(null);
offerBankStatus.setLastUpdtTs(now);
offerBankStatus.setLastUpdtUserId(user);
this.sessionFactory.getCurrentSession().save(offerBankStatus);
}
/*public void addOfferBankRegions(List<OfferBankCluster> obRegionList, Context ctx) {
String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
.getUserName() : SharedMessages.getString("user.default");
Date now = new Date(System.currentTimeMillis());
for (OfferBankCluster obc : obRegionList) {
obc.setCreationUserId(user);
obc.setCreationTs(now);
obc.setLastUpdtTs(now);
obc.setLastUpdtUserId(user);
this.sessionFactory.getCurrentSession().save(obc);
}
}*/
}
and the xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<sql>
<offer_bank_get_banks>
select * from (
select
ob.offer_bank_id
, ob.promotional_period_id
, ob.offer_bank_nm
, obst.offer_bank_status_type_dsc
, ob.effective_start_dt
, ob.effective_end_dt
, obt.offer_bank_type_dsc
, obt.offer_bank_type_cd
, pp.promotional_period_nm
, SUM(CASE WHEN a.offer_id IS NOT NULL THEN 1 ELSE 0 END) as total_count
, SUM(CASE WHEN a.offer_status_type_cd = 'ED' THEN 1 ELSE 0 END) as editing_count
, SUM(CASE WHEN a.offer_status_type_cd = 'FD' THEN 1 ELSE 0 END) as failed_deactive_count
, SUM(CASE WHEN a.offer_status_type_cd in ('FP', 'FI') THEN 1 ELSE 0 END) as failed_production_count
, SUM(CASE WHEN a.offer_status_type_cd = 'FV' THEN 1 ELSE 0 END) as failed_preview_count
, SUM(CASE WHEN a.offer_status_type_cd = 'LD' THEN 1 ELSE 0 END) as loaded_count
, SUM(CASE WHEN a.offer_status_type_cd in ('PE', 'PS') THEN 1 ELSE 0 END) as pending_count
, SUM(CASE WHEN a.offer_status_type_cd = 'PK' THEN 1 ELSE 0 END) as parked_count
, SUM(CASE WHEN a.offer_status_type_cd = 'SD' THEN 1 ELSE 0 END) as successfully_deactivated_count
, SUM(CASE WHEN a.offer_status_type_cd in ('SP','PI') THEN 1 ELSE 0 END) as successfully_loaded_to_prod_count
, SUM(CASE WHEN a.offer_status_type_cd = 'SV' THEN 1 ELSE 0 END) as successfully_loaded_to_preview_count
, SUM(CASE WHEN a.offer_status_type_cd in ('LD','PE','PS') THEN 1 ELSE 0 END) as total_pending_count
, SUM(CASE WHEN a.offer_status_type_cd in ('FD','FP','FV','FR','FI') THEN 1 ELSE 0 END) as failed_count
, COUNT(1) OVER(PARTITION BY 1) as total_rows
, ROW_NUMBER() OVER (ORDER BY ob.effective_end_dt desc) as row_nbr
, MAX(a.offer_effective_end_dt)as max_offer_effective_end_dt
, MIN(a.offer_effective_start_dt)as min_offer_effective_start_dt
, SUM(CASE WHEN a.offer_status_type_cd in('AR','SR','SD') THEN 1 ELSE 0 END) as ended_count
, SUM(CASE WHEN a.offer_status_type_cd in('CD') THEN 1 ELSE 0 END) as copient_delay_count
, SUM(CASE WHEN a.offer_status_type_cd in('SR') THEN 1 ELSE 0 END) as rejected_count
, SUM(CASE WHEN a.offer_status_type_cd in('LV', 'GV', 'CD', 'GA', 'GC', 'GD', 'GI', 'GP', 'GR', 'LA', 'LI', 'LP', 'LR', 'LV', 'LE')
THEN 1 ELSE 0 END) as processing_count
from
${sql.database}.offer_bank ob
INNER JOIN ${sql.database}.offer_bank_status obs
ON ob.offer_bank_id = obs.offer_bank_id
INNER JOIN ${sql.database}.offer_bank_status_type obst
ON obs.offer_bank_status_type_cd = obst.offer_bank_status_type_cd
INNER JOIN ${sql.database}.promotional_period pp
ON ob.promotional_period_id = pp.promotional_period_id
INNER JOIN ${sql.database}.offer_bank_type obt
ON ob.offer_bank_type_cd = obt.offer_bank_type_cd
LEFT OUTER JOIN
(Select
o.offer_id
, o.offer_bank_id
, ost.offer_status_type_cd
, o.offer_effective_end_dt
, o.offer_effective_start_dt
from
${sql.database}.offer o
INNER JOIN ${sql.database}.offer_status os
ON o.offer_id = os.offer_id
INNER JOIN ${sql.database}.offer_status_type ost
ON os.offer_status_type_cd = ost.offer_status_type_cd
AND os.effective_end_dt is null
) a
ON ob.offer_bank_id = a.offer_bank_id
where
obs.effective_end_dt is null
</offer_bank_get_banks>
and error stack being:
20:52:16,069 ERROR JDBCExceptionReporter:101 - ORA-00972: identifier is too long
20:52:16,070 ERROR OfferBankDaoHibernateImpl:77 - Error getOfferBanks(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)
Jul 19, 2013 8:52:16 PM org.restlet.resource.UniformResource doCatch
WARNING: Exception or error caught in resource
My code is breaking at OfferBankDaoHibernateImpl. To me it seems the method getOfferBanks(List offerBankTypes ,int startPos, int endPos, List statusIds) is breaking. If anyone has come across a similar situation, it will help?

ORA-00972: identifier is too long tells you what the issue is. The max length of an identifier is 30 characters in Oracle, and you have a couple aliases that are longer than 30 characters. For example, successfully_loaded_to_prod_count is 33 characters.

Related

What does "my_something" means in oracle sql query?

I have some Java code that runs an SQL query like this:
SELECT DISTINCT ven.enterprise_network_id, st.*
FROM studies st
inner join v_enterprise_network_members ven on st.ib_id = my_ib_id
WHERE ven.ib_id=:IB_ID
AND (st.myvrn_expiration_date IS NULL OR st.myvrn_expiration_Date >= sysdate)
ORDER BY st.study_date DESC
I understand everything except I don't understand what st.ib_id=my_ib_id. What does it mean? This is the whole method just in case if it helps:
public List<Study> searchRepository(StudySearchCriteria criteria, boolean isEnterpriseNetwork,
boolean isExactNameMatch) {
String selectForNone = null;
String studyStatus = null;
studyStatus = verifyStudyStatus(criteria, studyStatus, isEnterpriseNetwork);
if (criteria.contains(SearchField.STUDY_STATUS) && StringUtils.isBlank(studyStatus)) {
return new ArrayList<>();
}
if (StringUtils.isNotBlank(studyStatus) && studyStatus.contains(StudyPacsState.State.NONE.toString())) {
selectForNone = "DISTINCT {st.*}, st.study_date as stdate FROM studies st";
}
StringBuffer select = new StringBuffer(512);
StringBuffer where = new StringBuffer(512);
StringBuffer orderBy = new StringBuffer(selectForNone != null ? "" : " ORDER BY st.study_date DESC ");
select.append("SELECT ");
if (criteria.containsWildcard()) {
select.append(queryHint);
}
if (!isEnterpriseNetwork) {
select.append(selectForNone != null ? selectForNone : "DISTINCT {st.*} FROM studies st");
where.append(" WHERE st.ib_id=:IB_ID AND ").append(myVrnSql);
}
else {
///////////////////////////////////// HERE IS WHERE my_ib_id is
select.append("DISTINCT ven.enterprise_network_id, {st.*} FROM studies st")
.append(" inner join v_enterprise_network_members ven on st.ib_id=my_ib_id ");
/////////////////////////////////////
where.append(" WHERE ven.ib_id=:IB_ID AND ").append(myVrnSql);
}
StringBuilder queryForNone = selectForNone != null ? new StringBuilder(" UNION ") : new StringBuilder(" ");
createStudyStatusQuery(criteria, isExactNameMatch, studyStatus, where, queryForNone, false);
buildStudyQuery(criteria, select, where, orderBy, isEnterpriseNetwork, isExactNameMatch, true, false);
if (criteria.contains(SearchField.STUDY_STATUS)) {
select.append(" , smr_study_pacs_state sps ");
}
SQLQuery sq = null;
Query hq = null;
if (isEnterpriseNetwork) {
sq = getSession().createSQLQuery(select.toString() + where.toString());
sq.addEntity("st", Study.class).addScalar("enterprise_network_id", StandardBasicTypes.LONG)
.setCacheable(false).setCacheRegion("vrnstudysearch");
}
else {
sq = getSession().createSQLQuery(select.toString() + where.toString() + queryForNone.toString());
sq.addEntity("st", Study.class).setCacheable(false).setCacheRegion("vrnstudysearch");
if (selectForNone != null) {
sq.addScalar("stdate", StandardBasicTypes.TIMESTAMP);
}
}
hq = sq;
hq.setLong(SearchField.IB_ID.toString(), (Long) criteria.get(SearchField.IB_ID));
supplyParameters(criteria, hq, isExactNameMatch);
logger.info("Query searchRepository {}", hq.getQueryString());
List<Study> result = null;
if (!isEnterpriseNetwork) {
if (selectForNone != null) {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
result.add(st);
}
}
}
else {
result = hq.list();
}
}
else {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
st.setEnterpriseNetworkId((Long) tuple[1]);
result.add(st);
}
}
}
logger.debug(" returned " + (result == null ? 0 : result.size()));
return result;
}
st.ib_id=my_ib_id is the join condition - it defines the relationship between the two tables you are joining in the query. Presumably, my_ib_id is a column in one of those tables.

Why is my jpql .getResultList() returning 0 rows for a good query

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";

Send email on status change

I have a project which currently only does methods when I run the site. Now I need to implement a thread which checks the DB/the website for status-changes so I can send out a mail if something occurs. I have successfully added the functionality to mail someone, and also know the logic on how to do this. The problem occurs when I try to write the code, I don't know how to do it (Since I didn't know the back-end mostly, and now I have the responsibility for the project.
The logic would be to implement a java-thread (runnable) and then check the previous color with the new one and if it has changed send out an mail (The colors are statuses, for example, green & red). What is the most understandable and easy way to do this? I'll write the function names so you get an idea of what I have.
I have been stuck with this for a week and don't know what to do. Any help would be appreciated.
The method in the class for the object that changes color:
public void setColour(List<Status> statusar, List<Category> subcategories) {
for (int index = 0; index < subcategories.size(); index++) {
if (this.statusColor.compareToIgnoreCase("red") != 0) {
if ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("green") == 0)
&& (this.priority < ((Category)subcategories.get(index)).getPriority())) {
this.statusColor = "GREEN";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 2))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))) {
this.statusColor = "YELLOW";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))) {
this.statusColor = "RED";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
}
}
}
A color function I found in the DB part:
public List<Map<String, Object>> listColorsOverDays(String days, String categoryName) {
String SQL_getColors = "SELECT COUNT(*) count,color FROM ( ";
SQL_getColors += " SELECT CASE";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(greenFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(greenTo AS DECIMAL) THEN 'GREEN' ";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(yellowFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(yellowTo AS DECIMAL) THEN 'YELLOW' ";
SQL_getColors += " ELSE 'RED' END AS color ";
SQL_getColors += " FROM status INNER JOIN category ON status.idCategory = category.idCategory ";
SQL_getColors += " INNER JOIN threshold ON category.idCategory = threshold.idCategory ";
SQL_getColors += " WHERE status.timeStamp>DATE_SUB(NOW(), INTERVAL " + days + " DAY) ";
SQL_getColors += " AND category.name = '"+categoryName+"'";
SQL_getColors += " ) as p group by p.color";
List<Map<String, Object>> colorList = null;
try {
colorList = getJdbcTemplate().queryForList(SQL_getColors);
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
Here's the controller which uses this function:
public List<Map<String, Object>> getColorList(String days, String categoryName) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
List<Map<String, Object>> colorList = new ArrayList();
try {
colorList = statusDao_i.listColorsOverDays(days, categoryName);
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
A status list which contains the colors:
public List<Status> getStatusList(Status status) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
Timestamp fromTime = Timestamp.valueOf(status.getFromTime());
Timestamp toTime = Timestamp.valueOf(status.getToTime());
List<Status> statusList = new ArrayList();
try {
statusList = statusDao_i.getStatusesByTime(status, fromTime, toTime);
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return statusList;
}

How to prevent SQL injection attacks using parameterized queries - Play Framework

I inherited a Play 1.2.4 application which has just been security audited. It seems some methods are unsafe so I need to change them to use prepared statements.
One of the methods in question is this:
public static void surveys(int startIndex, int endIndex, boolean isAscending, String orderBy, String searchField,
String searchText, String filter) {
NdgUser currentUser = NdgUser.find("byUserName", session.get("ndgUser")).first();
NdgUser currentUserAdmin = NdgUser.find("byUserName", currentUser.userAdmin).first();
List<Survey> surveys = null;
String query;
if (filter != null && filter.length() > 0) {
query = getQuery2Filters( "available" , String.valueOf( SurveyStatusConsts.getStatusFlag( filter ) ),
"ndg_user_id", String.valueOf(currentUserAdmin.getId()), false,
searchField, searchText, null, isAscending );//sorting is not needed now
}
else {
query = getQuery( "ndg_user_id" , String.valueOf(currentUserAdmin.getId()), false,
searchField, searchText, null, isAscending );//sorting is not needed now
}
long totalItems = 0;
totalItems = Survey.count( query );
if ( orderBy != null && orderBy.equals( "resultCollection" ) ) {
surveys = Survey.find( query ).fetch();
Collections.sort( surveys, new SurveyNdgResultCollectionComapator() );
if ( !isAscending ) {
Collections.reverse( surveys );
}
int subListEndIndex = surveys.size() <= endIndex ? surveys.size() : endIndex;
surveys = surveys.subList( startIndex, subListEndIndex );
} else {
if (filter != null && filter.length() > 0) {
query = getQuery2Filters( "available", String.valueOf( SurveyStatusConsts.getStatusFlag( filter ) ),
"ndg_user_id", String.valueOf(currentUserAdmin.getId()), false,
searchField, searchText, orderBy, isAscending );
}
else {
query = getQuery( "ndg_user_id", String.valueOf(currentUserAdmin.getId()), false,
searchField, searchText, orderBy, isAscending );
}
surveys = Survey.find( query ).from( startIndex ).fetch( endIndex - startIndex );
}
serializeSurveys(surveys, startIndex, totalItems);
}
which makes use of another couple of methods to actually build the query
private static String getQuery(String filterName, String filterValue, boolean isFilterString, String searchField,
String searchText, String orderBy, boolean isAscending ) {
StringBuilder query = new StringBuilder();
String statusQuery = "";
String searchQuery = "";
String sortingQuery = "";
if ( filterName != null && filterName.length() > 0
&& filterValue != null && filterValue.length() > 0 ) {
statusQuery = filterName + "=" + ( isFilterString ? ("'" + filterValue + "'") : filterValue );
}
if ( searchField != null && searchText != null && searchText.length() > 0 ) {
if(searchField.equals("dateSent")) {
searchQuery = "DATE_FORMAT(" + searchField + ", '%d/%m/%Y')" + " like '%" + searchText + "%'";
}
else {
searchQuery = searchField + " like '%" + searchText + "%'";
}
}
if ( orderBy != null && orderBy.length()> 0 ) {
sortingQuery = "order by " + orderBy + ( isAscending ? " asc" : " desc" );
}
query.append( statusQuery )
.append( ( statusQuery.length() > 0 && searchQuery.length() > 0 ) ? " and " : ' ' )
.append( searchQuery )
.append( ' ' )
.append( sortingQuery );
return query.toString();
}
and
private static String getQuery2Filters(String filterName, String filterValue, String filterName2,
String filterValue2, boolean isFilterString, String searchField,
String searchText, String orderBy, boolean isAscending ) {
StringBuilder query = new StringBuilder();
String statusQuery = "";
String searchQuery = "";
String sortingQuery = "";
if ( filterName != null && filterName.length() > 0
&& filterValue != null && filterValue.length() > 0 ) {
statusQuery = filterName + "=" + ( isFilterString ? ("'" + filterValue + "'") : filterValue );
}
if ( filterName2 != null && filterName2.length() > 0
&& filterValue2 != null && filterValue2.length() > 0 ) {
statusQuery += " and " + filterName2 + "="
+ ( isFilterString ? ("'" + filterValue2 + "'") : filterValue2 );
}
if ( searchField != null && searchText != null && searchText.length() > 0 ) {
searchQuery = searchField + " like '%" + searchText + "%'";
}
if ( orderBy != null && orderBy.length()> 0 ) {
sortingQuery = "order by " + orderBy + ( isAscending ? " asc" : " desc" );
}
query.append( statusQuery )
.append( ( statusQuery.length() > 0 && searchQuery.length() > 0 ) ? " and " : ' ' )
.append( searchQuery )
.append( ' ' )
.append( sortingQuery );
return query.toString();
}
I believe it is these auxiliary methods I need to change for basic string concatenation to something using parameters but I am a bit lost as to how actually do that. I am not very familar with either Java or Hibernate/JPA so some pointers gratefully received

If + try - catch in method not working properly

I'm working on an SQLite based app. Everything is working fine, except my if-else statements in my method. The saving and stuff works, just the checking is giving me a pretty high blood pressure. I'm hoping one of you is much smarter than i am and finds the probably obvious mistake i made:
public void save() {
// get length of EditText
int dateLength, mileageLength, amountLength, lpriceLength, tpriceLength;
dateLength = date_widget.getText().length();
mileageLength = mileage_widget.getText().length();
amountLength = amount_widget.getText().length();
lpriceLength = price_widget.getText().length();
tpriceLength = totalPrice_widget.getText().length();
// Start save method if EditTexts are not empty.
if (dateLength > 0 || mileageLength > 0 || amountLength > 0
|| lpriceLength > 0 || tpriceLength > 0) {
// Get the value of each EditText and write it into the
// String/doubles
String date = date_widget.getText().toString();
double mileage = Double
.valueOf(mileage_widget.getText().toString());
double amount = Double.valueOf(amount_widget.getText().toString());
double lprice = Double.valueOf(price_widget.getText().toString());
double tprice = Double.valueOf(totalPrice_widget.getText()
.toString());
// Check if mileage is increasing, else cancel and show toast
int checkMileage = Integer.parseInt(db
.getSearchResult("mileage", 0));
if (checkMileage < mileage) {
try {
// if (id == null) {
db.insert(date, mileage, amount, lprice, tprice);
Toast.makeText(this, R.string.action_input_saved,
Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "ERROR " + e, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(
this,
"Your current mileage must be more than the last saved mileage",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "finish your input", Toast.LENGTH_LONG).show();
}
}
My Method in the DbAdapter class:
public String getSearchResult(String sql, int cmd) {
if (cmd == 0) {
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
cursor.moveToFirst();
String tmp = cursor.getString(0);
cursor.close();
// return count
return tmp;
} else if (cmd == 1) {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
for (int i = 0; i < maxId; i++) {
int tmp = Integer.parseInt(cursor.getString(0));
sum = sum + tmp;
cursor.moveToNext();
}
cursor.close();
id.close();
return String.valueOf(sum);
} else if (cmd == 2 && sql == "mileage") {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
if (maxId > 1) {
int array[] = new int[maxId];
// Array füllen
for (int i = 0; i < maxId; i++) {
array[i] = Integer.parseInt(cursor.getString(0));
// sum = sum + tmp;
cursor.moveToNext();
}
for (int k = 1; k < maxId; k++) {
int tmp;
tmp = array[k] - array[k - 1];
sum = sum + tmp;
}
cursor.close();
id.close();
return String.valueOf(sum);
} else {
return "--";
}
}
return "Wrong CMD";
}
I is pretty messy, i know
Turning comment into an answer:
Switch all || to && in your first if. Otherwise you will try to process everything even if only one field is filled in.

Categories

Resources