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

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

Related

How to traverse a B-Tree using Stack without recursion?

How to traverse a B-Tree using Stack without recursion?
This is function to traverse Btree using Stack but it does not work
void StackTraverse( BTreeNode node01 ) {
Stack< BTreeNode > stack01 = new Stack< BTreeNode >();
stack01.push( node01 ); // first node "to check"
String string01 = "";
int i = 0;
while ( stack01.size() > 0 ) {
BTreeNode current = stack01.pop();
if ( current.leaf == false ) {// if node is valid
for ( i = 0; i < current.n; i++ ) {
string01 = string01 + "Node : " + current.keys[ i ] + " ";
// string01 = string01 + current.traverse();
stack01.push( current.nodeChild[ i ] );
}
arrayString.add( string01 );
string01 = "";
}
}
}
void StackTraverse() {
String s01 = "";
if ( root != null ) {
StackTraverse( root );
System.out
.println( "\n arrayString.size() = " + arrayString.size() );
for ( int i = 0; i < arrayString.size(); i++ ) {
s01 = arrayString.get( i );
System.out.println( s01 );
}
}
}

Issue in masking XML tag value in java

I have an XML file shown below:
<Envelope>
<Body>
<user1>
<userId>userName</userId>
<password>password</password>
<creditCard>
<creditCardNumber>12345678901234</creditCardNumber>
<cvv>123</cvv>
</creditCard>
</user1>
<user2>
<userId>userName</userId>
<password>password</password>
<creditCard>
<creditCardNumber>12345678901234</creditCardNumber>
<cvv>123</cvv>
</creditCard>
</user2>
</Body>
</Envelope>
I have a java code used to log the xml transactions on to some server for future reference. This java code has methods to mask some characters or whole value of tag before logging as the credit card details are not to be disclosed.
Here are the methods:
public static String mask( String input, String[] tags, String maskPattern, String namespacePattern)
throws Throwable
{
StringBuffer sb = new StringBuffer( input );
encodedXML = false;
if (sb.indexOf( ">" ) > 0) {
// XML is encoded
gt = ">";
lt = "<";
encodedXML = true;
// modify patterns for encoded xml
maskPattern = "(>)" + alphaNumericStuff + "+(<)/";
if (sb.indexOf( """ ) >= 0) {
// There is a mix of double quotes and " in this xml
namespacePattern = mixedEncodingAlphaNumericStuff + "*";
}
}
for (int i = 0; i < tags.length; i++) {
// do a quick check to see if the tag is in the string to reduce excessive string creation
if (sb.indexOf( tags[i] ) < 0) {
continue;
} else {
sb = maskElementValue( sb, tags[i],maskPattern, namespacePattern );
}
}
return sb.toString();
}
private static StringBuffer maskElementValue( StringBuffer sb, String tag, String maskPattern,String namespacePattern)
{
// Pattern p = Pattern.compile( tag + maskPattern ); doesn't take namespace into account
Pattern p = Pattern.compile( tag + namespacePattern + maskPattern );
Matcher m = p.matcher( sb.toString() );
StringBuffer tempSB = new StringBuffer();
String namespaceStr = "";
while (m.find()) {
namespaceStr = m.group().substring( tag.length(), m.group().indexOf( gt ) );
// Added full masking for username and password including last 4 characters
if (tag.equalsIgnoreCase( "username" ) || tag.equalsIgnoreCase( "password" )) {
m.appendReplacement( tempSB, tag + namespaceStr + gt + xOut( new StringBuffer( m.group().substring( tag.length() + namespaceStr.length() + gt.length() ) ), true ) );
} else {
m.appendReplacement( tempSB, tag + namespaceStr + gt + xOut( new StringBuffer( m.group().substring( tag.length() + namespaceStr.length() + gt.length() ) ), false ) );
}
}
m.appendTail( tempSB );
return tempSB;
}
private static String xOut( StringBuffer sb, boolean maskAll )
{
int dataSize = sb.toString().trim().length() - 1 - lt.length();
if (!maskAll && dataSize > 4) {
if (sb.indexOf( "<" ) > 0 || sb.indexOf( "<" ) > 0) {
StringBuffer tempmaskSB = new StringBuffer( sb.substring( 0, sb.indexOf( "<" ) ) );
dataSize = tempmaskSB.length();
}
// Don't mask last 4 digit
for (int i = 0; i < dataSize - 4; i++) {
sb.setCharAt( i, 'X' );
}
} else {
if (sb.indexOf( "<" ) > 0 || sb.indexOf( "<" ) > 0) {
StringBuffer tempmaskSB = new StringBuffer( sb.substring( 0, sb.indexOf( "<" ) ) );
dataSize = tempmaskSB.length();
}
// Mask all
for (int i = 0; i < dataSize; i++) {
sb.setCharAt( i, 'X' );
}
}
return sb.toString();
}
I am passing the xml as string to the method and an array of tags that are to be masked. If it is username and password they should be masked completely and other tags in the array should be masked except the last 4 characters.
Now the problem is that masking is not happening for some of the transactions. when we have done a load testing, 12 out of 18000 transactions are not masked the protected data.
In some cases, user1 details are getting masked but user2 details are not masked in the same transaction.
Could any one help me in understanding why this is happening? Has anybody faced such issue before?
Thanks in advance.
Not sure if this is helpful. But i would do the masking part with jsoup
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
public class Mask {
static String xml = "<Envelope>\n" +
"<Body>\n" +
" <user1>\n" +
" <userId>userName</userId>\n" +
" <password>password</password>\n" +
" <creditCard>\n" +
" <creditCardNumber>12345678901234</creditCardNumber>\n" +
" <cvv>123</cvv>\n" +
" </creditCard>\n" +
" </user1>\n" +
" <user2>\n" +
" <userId>userName</userId>\n" +
" <password>password</password>\n" +
" <creditCard>\n" +
" <creditCardNumber>12345678901234</creditCardNumber>\n" +
" <cvv>123</cvv>\n" +
" </creditCard>\n" +
" </user2>\n" +
"</Body>\n" +
"</Envelope>";
public static void main (String[]args){
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements toMaskCompletely = doc.select("userId,password");
Elements toMaskPartially = doc.select("creditCardNumber");
for(Element ele : toMaskCompletely){
ele.text("XXXXX");
}
for(Element ele : toMaskPartially){
ele.text("XXXXXXXX"+ele.text().substring(ele.text().length()-4));
}
System.out.println(doc.toString());
}
}

How to break long strings into paragraphs

I have a String of length 1000-1500 chars. I want to divide the same into paragraphs. What I am doing now is:
String tempDisplayText =
"this is the long...... string of length 1000-2000 chars";
String displayText = null;
if (tempDisplayText != null && tempDisplayText.length() > 400) {
int firstFullStopIndex = tempDisplayText.indexOf(". ", 350);
if (firstFullStopIndex > 0) {
displayText = "<p>"
+ tempDisplayText.substring(0, firstFullStopIndex)
+ ".</p><p>"
+ tempDisplayText.substring(firstFullStopIndex + 1)
+ "</p>";
feed.setDisplayText(displayText);
}
}
This code is working fine, but divides the whole string into 2 paragraphs only. But some time the next paragraph is too lengthy thus looses its readability. Is there any standard way to divide strings into paragraphs in Java?
I see no reason why you shouldn't repeat this for the remainder, i.e., the second paragraph. You can't split a sentence.
StringBuilder sb = new StringBuilder();
if (tempDisplayText != null) {
int firstFullStopIndex;
while( tempDisplayText.length() > 400
&&
(firstFullStopIndex = tempDisplayText.indexOf(". ", 350)) >= 0 ){
sb.append( "<p>" );
sb.append( tempDisplayText.substring(0, firstFullStopIndex) );
sb.append( ".</p>" );
tempDisplayText = tempDisplayText.substring(firstFullStopIndex + 1);
}
if( tempDisplayText.length() > 0 ){
sb.append( "<p>" ).append( tempDisplayText ).append( "</p>" );
}
tempDisplayText = sb.toString();
}

Java/J2EE Internal Server Error

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.

when running my java code i am facing this error ->

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
my code:
public static void loanenquiry(String ApplicationID,String LoanNumber,String RIMNumber,String custname,String fromdate,String todate) {
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
try {
if(ApplicationID != null) {
wherestring = wherestring + "ApplicationID ="+BillAction.StringtoInt(ApplicationID)+"";
}
if(LoanNumber != null ) {
if(ApplicationID != null) {
wherestring = wherestring + "AND LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
} else {
wherestring = wherestring + "LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
}
}
if(RIMNumber != null ) {
if(ApplicationID != null && LoanNumber != null) {
wherestring = wherestring + "AND AdvparyRIM = "+RIMNumber+" ";
} else {
wherestring = wherestring + "AdvparyRIM = "+RIMNumber+"";
}
}
if(custname != null ){
if(ApplicationID != null && LoanNumber != null && RIMNumber != null ) {
wherestring = wherestring + "AND custName = "+custname+"";
} else {
wherestring = wherestring + "custName = "+custname+"";
}
}
if(fromdate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null ) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" ";
} else {
wherestring = wherestring + "ApplicationDt = "+BillAction.StringtoDate(fromdate)+"";
}
}
if(todate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null && fromdate != null) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" AND ApplicationDt <= "+BillAction.StringtoDate(todate)+"";
} else {
wherestring = wherestring + "ApplicationDt >= "+BillAction.StringtoDate(todate)+"";
}
}
Connection conn = BillFinanceDB.getDBConnection();
PreparedStatement psloanenquiry= conn.prepareStatement(wherestring + ";");
ResultSet rs = psloanenquiry.executeQuery();
while(rs.next()) {
System.out.println("loan number"+rs.getInt("LoanNumber"));
}
} catch(SQLException e) {
e.printStackTrace();
}
}
Any ideas?
thanks for the help.
My guess: you're missing a space after WHERE in your constructed string. Try this:
String wherestring = "SELECT * FROM bf_loanmaster WHERE ";
The best way to debug these kinds of errors is to print out the SQL query you have constructed before it is executed so that you can manually inspect it for problems.
The WHERE is most likely a problem. The second problem that you could have is not putting your strings in quotation marks. For example it probably should be wherestring = wherestring + "custName = '"+custname+"' ";
Also things to note:
All this appending is terribly inefficient, use a StringBuilder or StringBuffer instead. You could also use PreparedStatements which would make your code perform better and possibly even make it easier to read.
Add a space after where.. You have to seperate keywords like where..
give a space in your query
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
there is no space between WHERE statement and condition.

Categories

Resources