List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:com.quinsoft.epamms.ZGlobal1_Operation.java
public int InsertOI_DataIntoTemplateFile(View view, View workView, String toFile, String fromFile, String stringRootEntityName) throws IOException { BufferedWriter bw;/*from w w w .ja v a 2 s .com*/ StringBuilder sbInsertTemplate = new StringBuilder(); StringBuilder sbRawTemplate = new StringBuilder(); StringBuilder sbEntityBuffer; StringBuilder sbAttributeBuffer; String swapString = null; String stringStart = "{"; String stringEnd = "}"; String szTmp = null; int nRC = 0; int lSelectedCount = 0; int lTemplateLth = 0; nRC = SetCursorFirstEntity(workView, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { lSelectedCount++; nRC = SetCursorNextEntity(workView, stringRootEntityName, ""); } if (lSelectedCount <= 0) return 0; lTemplateLth = ReadFileDataIntoMemory(workView, fromFile, lTemplateLth, sbRawTemplate); if (lTemplateLth > Integer.MAX_VALUE) return 0; // File not found. if (lTemplateLth < 0) return -1; swapString = sbRawTemplate.substring(1, (lTemplateLth - 1)); lTemplateLth = swapString.length(); sbRawTemplate = new StringBuilder(); nRC = SetCursorFirstEntity(workView, stringRootEntityName, ""); while (nRC > zCURSOR_UNCHANGED) { sbRawTemplate.insert(0, swapString); for (int i = 0; i < sbRawTemplate.length(); i++) { sbEntityBuffer = new StringBuilder(); sbAttributeBuffer = new StringBuilder(); if (sbRawTemplate.charAt(i) == '[' && sbRawTemplate.charAt(i + 1) == 'Z') { int j = i; i += 2; while (sbRawTemplate.charAt(++i) != '.') sbEntityBuffer.append(sbRawTemplate.charAt(i)); while (sbRawTemplate.charAt(++i) != ']') sbAttributeBuffer.append(sbRawTemplate.charAt(i)); i++; szTmp = sbRawTemplate.substring(j, i + 10).toString(); sbRawTemplate.replace(j, i, GetStringFromAttribute(workView, sbEntityBuffer.toString(), sbAttributeBuffer.toString())); szTmp = sbRawTemplate.substring(j, j + 12).toString(); } } sbInsertTemplate.append(sbRawTemplate); //szTmp = sbInsertTemplate.substring(87284, 87296).toString(); sbRawTemplate = new StringBuilder(); nRC = SetCursorNextEntity(workView, stringRootEntityName, ""); } sbInsertTemplate.insert(0, stringStart); sbInsertTemplate.append(stringEnd); //szTmp = sbInsertTemplate.substring(87285, 87297).toString(); szTmp = sbInsertTemplate.substring(13917, 13929).toString(); bw = new BufferedWriter(new FileWriter(toFile)); //bw.write(sbInsertTemplate.toString()); szTmp = sbInsertTemplate.toString(); bw.write(szTmp); bw.flush(); bw.close(); return 0; }
From source file:forge.game.card.Card.java
private StringBuilder abilityTextInstantSorcery(CardState state) { final StringBuilder sb = new StringBuilder(); // Give spellText line breaks for easier reading sb.append(text.replaceAll("\\\\r\\\\n", "\r\n")); // NOTE:/* w ww .ja v a 2 s. co m*/ if (sb.toString().contains(" (NOTE: ")) { sb.insert(sb.indexOf("(NOTE: "), "\r\n"); } if (sb.toString().contains("(NOTE: ") && sb.toString().endsWith(".)") && !sb.toString().endsWith("\r\n")) { sb.append("\r\n"); } // I think SpellAbilities should be displayed after Keywords // Add SpellAbilities for (final SpellAbility element : state.getSpellAbilities()) { sb.append(formatSpellAbility(element)); } // Add Keywords final List<String> kw = getKeywords(state); // Triggered abilities for (final Trigger trig : state.getTriggers()) { if (!trig.isSecondary()) { sb.append(trig.toString()).append("\r\n"); } } // Replacement effects for (final ReplacementEffect replacementEffect : state.getReplacementEffects()) { sb.append(replacementEffect.toString()).append("\r\n"); } // static abilities for (final StaticAbility stAb : state.getStaticAbilities()) { final String stAbD = stAb.toString(); if (!stAbD.equals("")) { sb.append(stAbD).append("\r\n"); } } // TODO A lot of these keywords should really show up before the SAs // keyword descriptions for (final String keyword : kw) { if ((keyword.startsWith("Ripple") && !sb.toString().contains("Ripple")) || (keyword.startsWith("Dredge") && !sb.toString().contains("Dredge")) || (keyword.startsWith("CARDNAME is ") && !sb.toString().contains("CARDNAME is "))) { sb.append(keyword.replace(":", " ")).append("\r\n"); } else if ((keyword.startsWith("Madness") && !sb.toString().contains("Madness")) || (keyword.startsWith("Recover") && !sb.toString().contains("Recover")) || (keyword.startsWith("Miracle") && !sb.toString().contains("Miracle"))) { String[] parts = keyword.split(":"); sb.append(parts[0]).append(" ").append(ManaCostParser.parse(parts[1])).append("\r\n"); } else if (keyword.equals("CARDNAME can't be countered.") || keyword.startsWith("May be played") || keyword.startsWith("Conspire") || keyword.startsWith("Cascade") || keyword.startsWith("Wither") || (keyword.startsWith("Epic") && !sb.toString().contains("Epic")) || (keyword.startsWith("Split second") && !sb.toString().contains("Split second")) || (keyword.startsWith("Devoid"))) { sb.append(keyword).append("\r\n"); } else if (keyword .equals("You may cast CARDNAME as though it had flash if you pay 2 more to cast it.")) { sb.append(keyword).append("\r\n"); } else if (keyword.startsWith("Flashback")) { sb.append("Flashback"); if (keyword.contains(" ")) { final Cost fbCost = new Cost(keyword.substring(10), true); if (!fbCost.isOnlyManaCost()) { sb.append(" -"); } sb.append(" ").append(fbCost.toString()).delete(sb.length() - 2, sb.length()); if (!fbCost.isOnlyManaCost()) { sb.append("."); } } sb.append("\r\n"); } else if (keyword.startsWith("Splice")) { final Cost cost = new Cost(keyword.substring(19), false); sb.append("Splice onto Arcane ").append(cost.toSimpleString()).append("\r\n"); } else if (keyword.startsWith("Buyback")) { final Cost cost = new Cost(keyword.substring(8), false); sb.append("Buyback ").append(cost.toSimpleString()); sb.append( " (You may pay an additional cost as you cast CARDNAME. If you do, put CARDNAME back into your hand as it resolves.)"); sb.append("\r\n"); } else if (keyword.startsWith("Entwine")) { final Cost cost = new Cost(keyword.substring(8), false); sb.append("Entwine ").append(cost.toSimpleString()); sb.append(" (Choose both if you pay the entwine cost.)"); sb.append("\r\n"); } else if (keyword.startsWith("Multikicker")) { if (!keyword.endsWith("Generic")) { final Cost cost = new Cost(keyword.substring(7), false); sb.append("Multikicker ").append(cost.toSimpleString()).append("\r\n"); } } else if (keyword.startsWith("Kicker")) { if (!keyword.endsWith("Generic")) { final Cost cost = new Cost(keyword.substring(7), false); sb.append("Kicker ").append(cost.toSimpleString()).append("\r\n"); } } else if (keyword.startsWith("AlternateAdditionalCost")) { final String costString1 = keyword.split(":")[1]; final String costString2 = keyword.split(":")[2]; final Cost cost1 = new Cost(costString1, false); final Cost cost2 = new Cost(costString2, false); sb.append("As an additional cost to cast ").append(state.getName()).append(", ") .append(cost1.toSimpleString()).append(" or pay ").append(cost2.toSimpleString()) .append(".\r\n"); } else if (keyword.startsWith("Storm")) { if (sb.toString().contains("Target") || sb.toString().contains("target")) { sb.insert(sb.indexOf( "Storm (When you cast this spell, copy it for each spell cast before it this turn.") + 81, " You may choose new targets for the copies."); } } else if (keyword.startsWith("Replicate") && !sb.toString().contains("you paid its replicate cost.")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append(keyword); sb.append(" (When you cast this spell, copy it for each time you paid its replicate cost."); if (sb.toString().contains("Target") || sb.toString().contains("target")) { sb.append(" You may choose new targets for the copies."); } sb.append(")\r\n"); } else if (keyword.startsWith("Haunt")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append("Haunt ("); if (state.getType().isCreature()) { sb.append("When this creature dies, exile it haunting target creature."); } else { sb.append("When this spell card is put into a graveyard after resolving, "); sb.append("exile it haunting target creature."); } sb.append(")\r\n"); } else if (keyword.equals("Convoke")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append( "Convoke (Each creature you tap while casting this spell pays for {1} or one mana of that creature's color.)\r\n"); } else if (keyword.equals("Delve")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append( "Delve (Each card you exile from your graveyard while casting this spell pays for {1}.)\r\n"); } else if (keyword.endsWith(" offering")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } String offeringType = keyword.split(" ")[0]; sb.append(keyword); sb.append(" (You may cast this card any time you could cast an instant by sacrificing a "); sb.append(offeringType); sb.append("and paying the difference in mana costs between this and the sacrificed "); sb.append(offeringType); sb.append(". Mana cost includes color.)"); } else if (keyword .equals("Remove CARDNAME from your deck before playing if you're not playing for ante.")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append("Remove CARDNAME from your deck before playing if you're not playing for ante.\r\n"); } else if (keyword.equals("Rebound")) { sb.append(keyword).append( " (If you cast this spell from your hand, exile it as it resolves. At the beginning of your next upkeep, you may cast this card from exile without paying its mana cost.)\r\n"); } } return sb; }
From source file:br.gov.jfrj.siga.ex.bl.ExBL.java
public void marcarTudo(int primeiro, int ultimo, boolean efetivar, boolean apenasTemporalidade, PrintWriter out) {//w w w. ja v a 2 s. co m List<ExDocumento> list = new ArrayList<ExDocumento>(); final Criteria countCrit = dao().getSessao().createCriteria(ExDocumento.class) .add(Restrictions.ge("idDoc", new Long(primeiro))); if (ultimo != 0) countCrit.add(Restrictions.le("idDoc", new Long(ultimo))); countCrit.setProjection(Projections.rowCount()); final Criteria crit = dao().getSessao().createCriteria(ExDocumento.class) .add(Restrictions.ge("idDoc", new Long(primeiro))); if (ultimo != 0) crit.add(Restrictions.le("idDoc", new Long(ultimo))); crit.setMaxResults(5); crit.addOrder(Order.asc("idDoc")); out.println("-----------------------------------------------"); out.print(new SimpleDateFormat("HH:mm:ss").format(new Date())); out.print(" - Remarcando documentos."); out.print(" Primeiro: "); out.println(primeiro); if (ultimo != 0) { out.print(" Ultimo: "); out.println(ultimo); } if (efetivar) out.println("***EFETIVAR!!***"); out.println("-----------------------------------------------"); int index = 0; do { long inicio = System.currentTimeMillis(); if (efetivar) iniciarAlteracao(); crit.setFirstResult(index); list = crit.list(); for (ExDocumento doc : list) { index++; StringBuilder msg = new StringBuilder(); try { StringBuilder marcasAnteriores = new StringBuilder(); for (ExMobil mob : doc.getExMobilSet()) { marcasAnteriores.append(mob.isGeral() ? "0" : mob.getNumSequencia()); marcasAnteriores.append(" - "); marcasAnteriores.append(mob.getMarcadoresDescrCompleta(apenasTemporalidade)); } atualizarMarcasTemporalidade(doc); StringBuilder marcasPosteriores = new StringBuilder(); for (ExMobil mob : doc.getExMobilSet()) { marcasPosteriores.append(mob.isGeral() ? "0" : mob.getNumSequencia()); marcasPosteriores.append(" - "); marcasPosteriores.append(mob.getMarcadoresDescrCompleta(apenasTemporalidade)); } if (!marcasAnteriores.toString().equals(marcasPosteriores.toString())) { msg.append("Marcas:"); msg.append("\n\tAntes: "); msg.append(marcasAnteriores); msg.append("\n\tDepois: "); msg.append(marcasPosteriores); } } catch (Throwable e) { msg.append("ERRO: "); msg.append(e.getMessage()); e.printStackTrace(out); } if (msg.length() > 0) { msg.insert(0, "\n"); msg.insert(0, doc.getCodigo()); msg.insert(0, " - "); msg.insert(0, new SimpleDateFormat("HH:mm:ss").format(new Date())); msg.insert(0, "\n"); out.println(msg); } } if (efetivar) { ExDao.commitTransacao(); //System.gc(); } dao().getSessao().clear(); } while (list.size() > 0); out.println("\n-----------------------------------------------"); out.print(new SimpleDateFormat("HH:mm:ss").format(new Date())); out.println(" - Fim"); out.println("-----------------------------------------------"); //System.gc(); }
From source file:bfile.util.StringUtils.java
private static void convertRemainingAccentCharacters(final StringBuilder decomposed) { for (int i = 0; i < decomposed.length(); i++) { if (decomposed.charAt(i) == '\u0141') { decomposed.deleteCharAt(i);/*from w w w. ja v a2 s . c om*/ decomposed.insert(i, 'L'); } else if (decomposed.charAt(i) == '\u0142') { decomposed.deleteCharAt(i); decomposed.insert(i, 'l'); } } }
From source file:com.quinsoft.zeidon.vml.VmlOperation.java
/*** END fnValidateDay ***/ // Signed long to Asciiz right justified (with leading zeros) for length // INPUT: Long value to be converted to Ascii string // Ascii string address at which to set converted string // Return string length - not including null terminator ///* w w w . j a va2 s . c om*/ private int zltoal(int lValue, StringBuilder sb, int nOffset, int nLth) { String szTemp = null; int nPos; int k; szTemp = zltoa(lValue, szTemp); k = zstrlen(szTemp); if (k < nLth) { nPos = nLth - k; zmemset(sb, nOffset, '0', nPos); } else { nPos = 0; k = nLth; } zstrncpy(sb, nPos + nOffset, szTemp, k); sb.insert(nLth + nOffset, '\0'); return nLth + nOffset; }
From source file:com.quinsoft.zeidon.vml.VmlOperation.java
public int UfStringToDateTime(String cpcDateTimeString, DateTimeRecord lpDateTime) { int usStringLth; int usMonth;/*from w w w.j ava2 s .c o m*/ int usDay; int usDayOrg; int usSeconds; int usTSeconds; int ulYear; int ulHours; int usMinutes; int ulDateMinutes; int ulDays; int ulWorkYear; StringBuilder sbWorkString = new StringBuilder(20); DateTimeRecord lpDTInternal; boolean bDateSet; int nRC = 0; lpDTInternal = lpDateTime; // Null string will set the DateTime to 'NULL' if (StringUtils.isBlank(cpcDateTimeString)) { lpDTInternal.ulDateMinutes = lNullInteger; lpDTInternal.usTSeconds = 0; return (0); } usMonth = 0; usDay = 0; ulYear = 0; ulHours = 0; usMinutes = 0; usSeconds = 0; usTSeconds = 0; usStringLth = zstrlen(cpcDateTimeString); switch (usStringLth) { case 17: // YYYYMMDDHHmmSSTht case 16: // YYYYMMDDHHmmSSTh case 15: // YYYYMMDDHHmmSST // Get Thousandths of seconds Value zstrcpy(sbWorkString, cpcDateTimeString.substring(14)); usTSeconds = zatol(sbWorkString.toString()); if (usStringLth < 17) { usTSeconds *= (usStringLth == 16) ? 10 : 100; } case 14: // YYYYMMDDHHmmSS // Get Seconds Value sbWorkString.insert(0, cpcDateTimeString.charAt(12)); sbWorkString.insert(1, cpcDateTimeString.charAt(13)); sbWorkString.insert(2, '\0'); usSeconds = zatol(sbWorkString.toString()); if (usSeconds > 59) { usSeconds = 59; nRC = zCALL_ERROR; } case 12: // YYYYMMDDHHmm // Get Minutes Value sbWorkString.insert(0, cpcDateTimeString.charAt(10)); sbWorkString.insert(1, cpcDateTimeString.charAt(11)); sbWorkString.insert(2, '\0'); usMinutes = zatol(sbWorkString.toString()); if (usMinutes > 59) { usMinutes = 59; nRC = zCALL_ERROR; } // Get Hours Value sbWorkString.insert(0, cpcDateTimeString.charAt(8)); sbWorkString.insert(1, cpcDateTimeString.charAt(9)); sbWorkString.insert(2, '\0'); ulHours = zatol(sbWorkString.toString()); if (ulHours > 23) { ulHours = 23; nRC = zCALL_ERROR; } case 8: // YYYYMMDD // Get Day Value sbWorkString.insert(0, cpcDateTimeString.charAt(6)); sbWorkString.insert(1, cpcDateTimeString.charAt(7)); usDay = zatol(sbWorkString.toString()); // Get Month Value sbWorkString.setLength(0); sbWorkString.insert(0, cpcDateTimeString.charAt(4)); sbWorkString.insert(1, cpcDateTimeString.charAt(5)); usMonth = zatol(sbWorkString.toString()); // Get Year Value zstrncpy(sbWorkString, cpcDateTimeString, 4); ulYear = zatol(sbWorkString.toString()); // Check to see if we have date/datetime or only time without date. bDateSet = (ulYear != 0 || usMonth != 0 || usDay != 0); if (ulYear == 0) { ulYear = 1900; if (bDateSet) { nRC = zCALL_ERROR; } } // the year will be multiplied with minutes/year and then stored as // unsigned long. These means, max. can be not much more than 8000 if (ulYear > 8000) { ulYear = 8000; nRC = zCALL_ERROR; } // if month out of range, make it January if (usMonth < 1 || usMonth > 12) { usMonth = 1; if (bDateSet) { nRC = zCALL_ERROR; } } // Get valid day for the month usDayOrg = usDay; usDay = fnValidateDay(usMonth, usDayOrg, ulYear); if (usDay != usDayOrg) { if (bDateSet) { nRC = zCALL_ERROR; } } break; default: return (zCALL_ERROR); } /* Calculate Year in Minutes */ ulWorkYear = 0; ulDateMinutes = 0; // Fast path for dates starting Jan 1, 1900. // Start point set to beginning of century. if (ulYear >= 1900L) { ulWorkYear = 1900; ulDateMinutes = Year1900; if (ulYear >= 2000L) { ulWorkYear = 2000; ulDateMinutes += Century; } } // This will get us to Jan 1, of the desired year. // This will take a bit longer when the year is less than 1900. while (ulWorkYear < ulYear) { if ((ulWorkYear % 4) == 0 && ((ulWorkYear % 100) != 0 || (ulWorkYear % 400) == 0)) { ulDateMinutes += LeapYear; } else { ulDateMinutes += Year; } ulWorkYear++; } // This will get the number of days from the Jan 1, // to the beginning of the desired month. if ((ulWorkYear % 4) == 0 && ((ulWorkYear % 100) == 0 || (ulWorkYear % 400) == 0)) { ulDays = usLeapDayTable[usMonth - 1]; } else { ulDays = usDayTable[usMonth - 1]; } ulDays += usDay - 1; // add day of the month, for days // this year ulDateMinutes += ulDays * Day; // add days_minutes to total minutes ulDateMinutes += ulHours * Hour; // add hours_minutes to total minutes // add minutes to total minutes ulDateMinutes += (usMinutes * Minute); // Now save this, before we forget... lpDTInternal.ulDateMinutes = ulDateMinutes; // Convert seconds to thousandths, and save it too. lpDTInternal.usTSeconds = usTSeconds + (usSeconds * 1000); return (nRC); }
From source file:com.primovision.lutransport.service.ImportMainSheetServiceImpl.java
@Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<String> importMainSheet(InputStream is) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy"); // initializing the InputStream from a file using // POIFSFileSystem, before converting the result // into an HSSFWorkbook instance System.out.println("***** Here step 2"); HSSFWorkbook wb = null;//w w w. ja v a2 s . co m StringBuffer buffer = null; List<String> list = new ArrayList<String>(); List<Ticket> tickets = new ArrayList<Ticket>(); // List<String> emptydatalist=new ArrayList<String>(); int count = 1; int errorcount = 0; try { POIFSFileSystem fs = new POIFSFileSystem(is); ErrorData edata = new ErrorData(); // FileWriter writer = new FileWriter("e:/errordata.txt"); wb = new HSSFWorkbook(fs); // loop for every worksheet in the workbook int numOfSheets = wb.getNumberOfSheets(); Map criterias = new HashMap(); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = null; HSSFCell cell = null; Ticket ticket = null; Iterator rows = sheet.rowIterator(); StringBuffer lineError; while (rows.hasNext()) { boolean error = false; buffer = new StringBuffer(); int cellCount = 0; row = (HSSFRow) rows.next(); if (count == 1) { count++; continue; } lineError = new StringBuffer(""); try { ticket = new Ticket(); ticket.setTicketStatus(1); ticket.setPayRollStatus(1); Object loadDateObj = getCellValue(row.getCell(0), true); if (loadDateObj == null) { error = true; lineError.append("Load Date,"); } else if (loadDateObj instanceof Date) { ticket.setLoadDate((Date) loadDateObj); } else { String loadDateStr = loadDateObj.toString(); loadDateStr = StringUtils.trimToEmpty(loadDateStr); Date loadDate = sdf.parse(loadDateStr); ticket.setLoadDate(loadDate); } /*try { Date loadDate = sdf.parse((String) getCellValue(row.getCell(0), true)); ticket.setLoadDate(loadDate); } catch (ParseException p) { error = true; lineError.append("Load Date,"); }*/ /*if (validDate(getCellValue(row.getCell(0)))) ticket.setLoadDate((Date) getCellValue(row.getCell(0))); else { error = true; lineError.append("Load Date,"); }*/ if (validTime((String) getCellValue(row.getCell(1)))) { StringBuilder timeIn = new StringBuilder( StringUtils.leftPad((String) getCellValue(row.getCell(1)), 4, '0')); timeIn.insert(2, ':'); ticket.setTransferTimeIn(timeIn.toString()); } else { error = true; lineError.append("Transfer Time In,"); } if (validTime((String) getCellValue(row.getCell(2)))) { StringBuilder timeOut = new StringBuilder( StringUtils.leftPad((String) getCellValue(row.getCell(2)), 4, '0')); timeOut.insert(2, ':'); ticket.setTransferTimeOut(timeOut.toString()); } else { error = true; lineError.append("Transfer Time Out,"); } try { criterias.clear(); criterias.put("type", 1); criterias.put("unit", Integer.parseInt((String) getCellValue(row.getCell(3)))); Vehicle vehicle = genericDAO.getByCriteria(Vehicle.class, criterias); if (vehicle == null) throw new Exception("no such truck"); else ticket.setVehicle(vehicle); } catch (Exception ex) { error = true; lineError.append("Truck,"); log.warn(ex.getMessage()); } try { criterias.clear(); criterias.put("type", 2); criterias.put("unit", Integer.parseInt((String) getCellValue(row.getCell(4)))); Vehicle vehicle = genericDAO.getByCriteria(Vehicle.class, criterias); if (vehicle == null) throw new Exception("no such trailer"); else ticket.setTrailer(vehicle); } catch (Exception ex) { error = true; lineError.append("Trailer,"); log.warn(ex.getMessage()); } Object unloadDateObj = getCellValue(row.getCell(5), true); if (unloadDateObj == null) { error = true; lineError.append("Unload Date,"); } else if (unloadDateObj instanceof Date) { ticket.setUnloadDate((Date) unloadDateObj); } else { String unloadDateStr = unloadDateObj.toString(); unloadDateStr = StringUtils.trimToEmpty(unloadDateStr); Date unloadDate = sdf.parse(unloadDateStr); ticket.setUnloadDate(unloadDate); } /*try { Date unloadDate = sdf.parse((String) getCellValue(row.getCell(5))); ticket.setUnloadDate(unloadDate); } catch (ParseException p) { error = true; lineError.append("Unload Date,"); }*/ /*Object unloadDate = getCellValue(row.getCell(5)); if (validDate(unloadDate)) ticket.setUnloadDate((Date) unloadDate); else { error = true; lineError.append("" + " Date,"); }*/ if (validTime((String) getCellValue(row.getCell(6)))) { StringBuilder timeIn = new StringBuilder( StringUtils.leftPad((String) getCellValue(row.getCell(6)), 4, '0')); timeIn.insert(2, ':'); ticket.setLandfillTimeIn(timeIn.toString()); } else { error = true; lineError.append("Landfill Time In,"); } if (validTime((String) getCellValue(row.getCell(7)))) { StringBuilder timeOut = new StringBuilder( StringUtils.leftPad((String) getCellValue(row.getCell(7)), 4, '0')); timeOut.insert(2, ':'); ticket.setLandfillTimeOut(timeOut.toString()); } else { error = true; lineError.append("Landfill Time Out,"); } try { criterias.clear(); criterias.put("type", 1); criterias.put("name", (String) getCellValue(row.getCell(8))); Location location = genericDAO.getByCriteria(Location.class, criterias); if (location == null) throw new Exception("no such origin"); else ticket.setOrigin(location); } catch (Exception ex) { error = true; lineError.append("Origin,"); // log.warn(ex.getMessage()); } try { ticket.setOriginTicket(Long.parseLong((String) getCellValue(row.getCell(9)))); } catch (Exception ex) { error = true; lineError.append("Origin Ticket,"); } try { criterias.clear(); criterias.put("type", 2); criterias.put("name", (String) getCellValue(row.getCell(10))); Location location = genericDAO.getByCriteria(Location.class, criterias); if (location == null) throw new Exception("no such destination"); else ticket.setDestination(location); } catch (Exception ex) { error = true; lineError.append("Destination,"); // log.warn(ex.getMessage()); } // FOR CUSTOMER AND COMPANY_LACATION BillingRate billingRate = null; try { criterias.clear(); criterias.put("type", 1); criterias.put("name", (String) getCellValue(row.getCell(8))); Location originid = genericDAO.getByCriteria(Location.class, criterias); criterias.clear(); criterias.put("type", 2); criterias.put("name", (String) getCellValue(row.getCell(10))); Location destinationid = genericDAO.getByCriteria(Location.class, criterias); if (originid != null && destinationid != null) { // BillingRate billingRate = null; String query = "select obj from BillingRate obj where transferStation=" + originid.getId() + " and landfill=" + destinationid.getId(); List<BillingRate> rates = genericDAO.executeSimpleQuery(query); for (BillingRate rate : rates) { if (rate.getRateUsing() == null) { billingRate = rate; break; } else if (rate.getRateUsing() == 1) { // calculation for a load date if ((ticket.getLoadDate().getTime() >= rate.getValidFrom().getTime()) && (ticket.getLoadDate().getTime() <= rate.getValidTo().getTime())) { billingRate = rate; break; } } else if (rate.getRateUsing() == 2) { // calculation for a unload date if ((ticket.getUnloadDate().getTime() >= rate.getValidFrom().getTime()) && (ticket.getUnloadDate().getTime() <= rate.getValidTo().getTime())) { billingRate = rate; break; } } } if (billingRate != null) { ticket.setCompanyLocation((billingRate.getCompanyLocation() != null) ? billingRate.getCompanyLocation() : null); ticket.setCustomer( (billingRate.getCustomername() != null) ? billingRate.getCustomername() : null); } else { System.out.println("Customer and Company Location"); } /* * { error = true; lineError.append( * "Rate is expired for this origin and destination,please contact to administrator," * ); } */ } } catch (Exception ex) { System.out.println("Customer and Company Location"); log.warn(ex.getMessage()); } try { ticket.setDestinationTicket(Long.parseLong((String) getCellValue(row.getCell(11)))); } catch (Exception ex) { error = true; lineError.append("Destination Ticket,"); } if (ticket.getOrigin() != null) { if (reportService.checkDuplicate(ticket, "O")) { lineError.append("Duplicate Origin Ticket,"); error = true; } } if (ticket.getDestination() != null) { if (reportService.checkDuplicate(ticket, "D")) { lineError.append("Duplicates Dest. Ticket,"); error = true; } } if (ticket.getUnloadDate() != null && ticket.getLoadDate() != null) { if (ticket.getUnloadDate().before(ticket.getLoadDate())) { lineError.append("Unload Date is before Load Date,"); error = true; } } Double tgross = getValidAmount((String) getCellValue(row.getCell(12))); if (tgross != null) ticket.setTransferGross(tgross); else { error = true; lineError.append("Transfer Gross,"); } Double ttare = getValidAmount((String) getCellValue(row.getCell(13))); if (ttare != null) ticket.setTransferTare(ttare); else { lineError.append("Transfer Tare,"); error = true; } if (tgross != null && ttare != null) { ticket.setTransferNet(tgross - ttare); ticket.setTransferTons((tgross - ttare) / 2000); /* if(billingRate.getBilledby().equals("bygallon")){ */ // Change to 8.35 - 28th Dec 2016 ticket.setGallons(ticket.getTransferNet() / 8.35); // } } Double lgross = getValidAmount((String) getCellValue(row.getCell(16))); if (lgross != null) ticket.setLandfillGross(lgross); else { error = true; lineError.append("Landfill Gross,"); } Double ltare = getValidAmount((String) getCellValue(row.getCell(17))); if (ltare != null) ticket.setLandfillTare(ltare); else { lineError.append("Landfill Tare,"); error = true; } if (lgross != null && ltare != null) { ticket.setLandfillNet(lgross - ltare); ticket.setLandfillTons((lgross - ltare) / 2000); } String driverName = ((String) getCellValue(row.getCell(21))); Driver driver = null; try { if (StringUtils.isEmpty(driverName)) throw new Exception("Invalid driver"); else { // String[] names = driverName.split(" "); criterias.clear(); /* * criterias.put("firstName", names[1]); * criterias.put("lastName", names[0]); */ criterias.put("status", 1); criterias.put("fullName", driverName); driver = genericDAO.getByCriteria(Driver.class, criterias); if (driver == null) throw new Exception("Invalid driver"); ticket.setDriver(driver); // ticket.setDriverCompany(driver.getCompany()); } } catch (Exception ex) { error = true; lineError.append("Driver,"); } try { String employeeCompanyName = ((String) getCellValue(row.getCell(23))); if (StringUtils.isEmpty(employeeCompanyName)) throw new Exception("Invalid company"); else { criterias.clear(); criterias.put("status", 1); criterias.put("name", employeeCompanyName); Location employeeCompany = genericDAO.getByCriteria(Location.class, criterias); if (employeeCompany == null) throw new Exception("Invalid company"); ticket.setDriverCompany(employeeCompany); } } catch (Exception ex) { error = true; lineError.append("employee company,"); } String subcontractor = ((String) getCellValue(row.getCell(20))); try { if (!StringUtils.isEmpty(subcontractor)) { /* * if (driver != null && !"Subcontractor" * .equalsIgnoreCase(driver .getLastName().trim())) * { throw new Exception("Invalid subcontractor"); } * * * else { */ //String subcontractorMod = subcontractor.replace("&", "\"&\""); criterias.clear(); criterias.put("name", subcontractor); SubContractor contractor = genericDAO.getByCriteria(SubContractor.class, criterias); if (contractor == null) { throw new Exception("Invalid subcontractor"); } else { ticket.setSubcontractor(contractor); } criterias.clear(); } // } } catch (Exception ex) { error = true; lineError.append("Sub Contractor,"); } Object billbatchDateObj = getCellValue(row.getCell(22), true); if (billbatchDateObj == null) { error = true; lineError.append("Bill Batch Date,"); } else if (billbatchDateObj instanceof Date) { ticket.setBillBatch((Date) billbatchDateObj); } else { String billbatchDateStr = billbatchDateObj.toString(); billbatchDateStr = StringUtils.trimToEmpty(billbatchDateStr); Date billbatchDate = sdf.parse(billbatchDateStr); ticket.setBillBatch(billbatchDate); } /*try { Date billBatch = sdf.parse((String) getCellValue(row.getCell(22))); ticket.setBillBatch(billBatch); } catch (ParseException p) { error = true; lineError.append("Batch Date,"); }*/ /*Object billBatch = getCellValue(row.getCell(22)); if (validDate(billBatch)) ticket.setBillBatch((Date) billBatch); else { error = true; lineError.append("Batch Date,"); }*/ try { criterias.clear(); String locCode = (String) getCellValue(row.getCell(24)); if (StringUtils.isEmpty(locCode)) throw new Exception("Invalid terminal"); else { criterias.put("code", locCode); criterias.put("type", 4); } Location location = genericDAO.getByCriteria(Location.class, criterias); if (location == null) { throw new Exception("no such terminal"); } else { criterias.clear(); criterias.put("status", 1); criterias.put("fullName", driverName); criterias.put("terminal", location); Driver driverobj = genericDAO.getByCriteria(Driver.class, criterias); if (driverobj == null) { throw new Exception("Terminal does not match with driver"); } else { ticket.setTerminal(location); } } } catch (Exception ex) { error = true; lineError.append("Terminal does not match with driver,"); log.warn(ex.getMessage()); } try { User user = genericDAO.getByUniqueAttribute(User.class, "username", (String) getCellValue(row.getCell(25))); if (user == null) { throw new Exception("Invalid user"); } else { ticket.setCreatedBy(user.getId()); ticket.setEnteredBy(user.getName()); } } catch (Exception ex) { error = true; lineError.append("User,"); } if (!error) { if (tickets.contains(ticket)) { lineError.append("Duplicate Ticket,"); error = true; errorcount++; } else { tickets.add(ticket); //genericDAO.saveOrUpdate(ticket); } } else { errorcount++; } } catch (Exception ex) { error = true; log.warn(ex); } if (lineError.length() > 0) { System.out.println("Error :" + lineError.toString()); list.add("Line " + count + ":" + lineError.toString() + "<br/>"); } System.out.println("Record No :" + count); count++; } } catch (Exception e) { log.warn("Error in import customer :" + e); } if (errorcount == 0) { for (Ticket ticket : tickets) { genericDAO.saveOrUpdate(ticket); } } return list; }
From source file:com.quinsoft.zeidon.zeidonoperations.KZOEP1AA.java
public static int SysAppendcDirSep(StringBuilder sbDirectoryName) { String s = sbDirectoryName.toString(); s = s.replace('\\', '/'); int nLth = s.length(); sbDirectoryName.setLength(0); // Use sb.setLength( 0 ); to clear a string buffer. sbDirectoryName.append(s);//from ww w.ja v a 2 s. c om if (nLth > 1 && sbDirectoryName.charAt(nLth - 1) != '/') { sbDirectoryName.insert(nLth++, '/'); } return nLth; }
From source file:org.ohmage.query.impl.SurveyResponseQueries.java
/** * Builds the SQL for the survey response SELECT and generates a parameter * list that corresponds to that SQL. The parameter list is returned and * the SQL is set as the final parameter. * /* ww w. j a v a 2s. co m*/ * @param campaign The campaign to which the survey responses must belong. * * @param username The username of the user that is making this request. * This is used by the ACLs to limit who sees what. * * @param usernames Limits the results to only those submitted by any one * of the users in the list. * * @param startDate Limits the results to only those survey responses that * occurred on or after this date. * * @param endDate Limits the results to only those survey responses that * occurred on or before this date. * * @param privacyState Limits the results to only those survey responses * with this privacy state. * * @param surveyIds Limits the results to only those survey responses that * were derived from a survey in this collection. * * @param promptIds Limits the results to only those survey responses that * were derived from a prompt in this collection. * * @param promptType Limits the results to only those survey responses that * are of the given prompt type. * * @param columns Aggregates the data based on the column keys. If this is * null, no aggregation is performed. If the list is empty, * an empty list is returned. * * @param parameters This is a list created by the caller to be populated * with the parameters aggregated while generating this * SQL. * * @return The list of parameters that corresponds with the generated SQL. */ private String buildSqlAndParameters(final Campaign campaign, final String username, final Set<UUID> surveyResponseIds, final Collection<String> usernames, final DateTime startDate, final DateTime endDate, final SurveyResponse.PrivacyState privacyState, final Collection<String> surveyIds, final Collection<String> promptIds, final String promptType, final Set<String> promptResponseSearchTokens, final Collection<ColumnKey> columns, final List<SortParameter> sortOrder, final Collection<Object> parameters) throws DataAccessException { // Begin with the SQL string which gets all results or the one that // aggregates results. StringBuilder sqlBuilder = new StringBuilder(SQL_BASE_WHERE); parameters.add(campaign.getId()); // Catch any query exceptions. try { // If the requesting user is an admin, don't bother applying the // ACLs. if (!getJdbcTemplate().queryForObject("SELECT admin FROM user WHERE username = ?", new Object[] { username }, Boolean.class)) { // Get the roles for the user in the campaign. List<Campaign.Role> roles = getJdbcTemplate().query( "SELECT ur.role " + "FROM user u, campaign c, user_role ur, user_role_campaign urc " + "WHERE u.username = ? " + "AND u.id = urc.user_id " + "AND c.urn = ? " + "AND c.id = urc.campaign_id " + "AND urc.user_role_id = ur.id", new Object[] { username, campaign.getId() }, new RowMapper<Campaign.Role>() { @Override public Campaign.Role mapRow(final ResultSet rs, final int rowNum) throws SQLException { return Campaign.Role.getValue(rs.getString("role")); } }); // If the user is not a supervisor in the campaign, then we // will add additional ACLs based on their role. if (!roles.contains(Campaign.Role.SUPERVISOR)) { // Users are always allowed to query about themselves. sqlBuilder.append(" AND ((u.username = ?)"); parameters.add(username); // If the user is an author or analyst, they may see shared // responses as well. if (roles.contains(Campaign.Role.AUTHOR) || roles.contains(Campaign.Role.ANALYST)) { // Add the shared survey responses. sqlBuilder.append(" OR ((srps.privacy_state = 'shared')"); // However, if the user is only an analyst, the // campaign must also be shared. if (!roles.contains(Campaign.Role.AUTHOR)) { sqlBuilder.append(" AND (cps.privacy_state = 'shared')"); } // Finally, close the OR. sqlBuilder.append(')'); } // Finally, close the AND. sqlBuilder.append(')'); } } } catch (org.springframework.dao.DataAccessException e) { throw new DataAccessException("Error querying about the user.", e); } // Check all of the criteria and if any are non-null add their SQL and // append the parameters. if (surveyResponseIds != null) { sqlBuilder.append(SQL_WHERE_SURVEY_RESPONSE_IDS); sqlBuilder.append(StringUtils.generateStatementPList(surveyResponseIds.size())); for (UUID surveyResponseId : surveyResponseIds) { parameters.add(surveyResponseId.toString()); } } if ((usernames != null) && (usernames.size() > 0)) { sqlBuilder.append(SQL_WHERE_USERNAMES); sqlBuilder.append(StringUtils.generateStatementPList(usernames.size())); parameters.addAll(usernames); } if (startDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_AFTER); parameters.add(startDate.getMillis()); } if (endDate != null) { sqlBuilder.append(SQL_WHERE_ON_OR_BEFORE); parameters.add(endDate.getMillis()); } if (privacyState != null) { sqlBuilder.append(SQL_WHERE_PRIVACY_STATE); parameters.add(privacyState.toString()); } if (surveyIds != null) { sqlBuilder.append(SQL_WHERE_SURVEY_IDS); sqlBuilder.append(StringUtils.generateStatementPList(surveyIds.size())); parameters.addAll(surveyIds); } if (promptIds != null) { sqlBuilder.append(SQL_WHERE_PROMPT_IDS); sqlBuilder.append(StringUtils.generateStatementPList(promptIds.size())); parameters.addAll(promptIds); } if (promptType != null) { sqlBuilder.append(SQL_WHERE_PROMPT_TYPE); parameters.add(promptType); } if (promptResponseSearchTokens != null) { for (String promptResponseSearchToken : promptResponseSearchTokens) { sqlBuilder.append(SQL_WHERE_PROMPT_RESPONSE_SEARCH_TOKEN); parameters.add('%' + promptResponseSearchToken + '%'); } } // Now, collapse the columns if columns is non-null. boolean onSurveyResponse = true; if (columns != null) { sqlBuilder.append(" GROUP BY "); boolean firstPass = true; for (ColumnKey columnKey : columns) { if (firstPass) { firstPass = false; } else { sqlBuilder.append(", "); } switch (columnKey) { case CONTEXT_CLIENT: sqlBuilder.append("sr.client"); break; case CONTEXT_DATE: sqlBuilder .append("DATE(CONVERT_TZ(FROM_UNIXTIME(epoch_millis / 1000), 'UTC', phone_timezone))"); break; case CONTEXT_TIMESTAMP: case CONTEXT_UTC_TIMESTAMP: sqlBuilder.append("(sr.epoch_millis / 1000)"); break; case CONTEXT_EPOCH_MILLIS: sqlBuilder.append("sr.epoch_millis"); break; case CONTEXT_TIMEZONE: sqlBuilder.append("sr.phone_timezone"); break; case CONTEXT_LAUNCH_CONTEXT_LONG: case CONTEXT_LAUNCH_CONTEXT_SHORT: sqlBuilder.append("sr.launch_context"); break; case CONTEXT_LOCATION_STATUS: sqlBuilder.append("sr.location_status"); break; case USER_ID: sqlBuilder.append("u.username"); break; case SURVEY_ID: sqlBuilder.append("sr.survey_id"); break; case SURVEY_RESPONSE_ID: sqlBuilder.append("sr.uuid"); break; case SURVEY_PRIVACY_STATE: sqlBuilder.append("srps.privacy_state"); break; case REPEATABLE_SET_ID: onSurveyResponse = false; sqlBuilder.append("pr.repeatable_set_id"); break; case REPEATABLE_SET_ITERATION: onSurveyResponse = false; sqlBuilder.append("pr.repeatable_set_iteration"); break; case PROMPT_RESPONSE: onSurveyResponse = false; sqlBuilder.append("pr.response"); break; // This is inaccurate and will only work if the entire // JSONObject is the same. We cannot do this without JSONObject // dissection in SQL. case CONTEXT_LOCATION_LATITUDE: case CONTEXT_LOCATION_LONGITUDE: case CONTEXT_LOCATION_TIMESTAMP: case CONTEXT_LOCATION_TIMEZONE: case CONTEXT_LOCATION_ACCURACY: case CONTEXT_LOCATION_PROVIDER: sqlBuilder.append("sr.location"); break; // This cannot be done without XML manipulation in the SQL. // Instead, we shouldn't dump the XML in the database and // should explode it into its own series of columns and, if // necessary, additional tables. case SURVEY_TITLE: case SURVEY_DESCRIPTION: default: int length = sqlBuilder.length(); sqlBuilder.delete(length - 2, length); } } } // Now, go back and insert the correct SELECT clause based on if we are // grouping or not and, if so, if we are doing it at the survey level // or the prompt level. if (columns == null) { sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_INDIVIDUAL); } else if (onSurveyResponse) { sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_AGGREGATED_SURVEY); } else { sqlBuilder.insert(0, SQL_GET_SURVEY_RESPONSES_AGGREGATED_PROMPT); } // Finally, add some ordering to facilitate consistent results in the // paging system. if (sortOrder == null) { sqlBuilder.append(" ORDER BY epoch_millis DESC, uuid"); } else { sqlBuilder.append(" ORDER BY "); boolean firstPass = true; for (SortParameter sortParameter : sortOrder) { if (firstPass) { firstPass = false; } else { sqlBuilder.append(", "); } sqlBuilder.append(sortParameter.getSqlColumn()); } // We must always include the UUID in the order to guarantee that // all survey responses are grouped together. if (firstPass) { sqlBuilder.append("uuid"); } else { sqlBuilder.append(", uuid"); } } return sqlBuilder.toString(); }
From source file:com.intuit.tank.project.JobDetailFormatter.java
protected static String buildDetails(JobValidator validator, Workload workload, JobInstance proposedJobInstance, String scriptName) {/*ww w . j a v a 2 s. c o m*/ StringBuilder sb = new StringBuilder(); StringBuilder errorSB = new StringBuilder(); TankConfig config = new TankConfig(); if (proposedJobInstance != null) { if (StringUtils.isBlank(proposedJobInstance.getName())) { addError(errorSB, "Name cannot be null"); } JobRegionDao jrd = new JobRegionDao(); List<JobRegion> regions = new ArrayList<JobRegion>(); for (EntityVersion ver : proposedJobInstance.getJobRegionVersions()) { JobRegion region = jrd.findById(ver.getObjectId()); if (region != null) { long users = TestParamUtil.evaluateExpression(region.getUsers(), proposedJobInstance.getExecutionTime(), proposedJobInstance.getSimulationTime(), proposedJobInstance.getRampTime()); if (users > 0) { regions.add(new JobRegion(region.getRegion(), Long.toString(users))); } } } Collections.sort(regions); long simulationTime = getSimulationTime(proposedJobInstance, workload, validator); addProperty(sb, "General Information", "", "emphasis"); addProperty(sb, "Name", StringUtils.isBlank(proposedJobInstance.getName()) ? "Name cannot be null" : proposedJobInstance.getName(), StringUtils.isBlank(proposedJobInstance.getName()) ? "error" : null); addProperty(sb, "Workload Type", proposedJobInstance.getIncrementStrategy().name()); addProperty(sb, "Tank Http Client", config.getAgentConfig().getTankClientName(proposedJobInstance.getTankClientClass())); addProperty(sb, "Agent VM Type", getVmDetails(config, proposedJobInstance.getVmInstanceType())); addProperty(sb, "Assign Elastic Ips", Boolean.toString(proposedJobInstance.isUseEips())); addProperty(sb, "Max Users per Agent", Integer.toString(proposedJobInstance.getNumUsersPerAgent())); addProperty(sb, "Estimated Cost", calculateCost(config, proposedJobInstance, regions, simulationTime)); addProperty(sb, "Location", proposedJobInstance.getLocation()); addProperty(sb, "Logging Profile", LoggingProfile.fromString(proposedJobInstance.getLoggingProfile()).getDisplayName()); addProperty(sb, "Stop Behavior", StopBehavior.fromString(proposedJobInstance.getStopBehavior()).getDisplay()); addProperty(sb, "Run Scripts Until", proposedJobInstance.getTerminationPolicy().getDisplay(), proposedJobInstance.getTerminationPolicy() == TerminationPolicy.time && proposedJobInstance.getSimulationTime() == 0 ? "error" : null); sb.append(BREAK); addProperty(sb, "Simulation Time", TimeUtil.toTimeString(simulationTime)); if (proposedJobInstance.getTerminationPolicy() == TerminationPolicy.time && proposedJobInstance.getSimulationTime() == 0) { addError(errorSB, "Simulation time not set."); } addProperty(sb, "Ramp Time", TimeUtil.toTimeString(proposedJobInstance.getRampTime())); addProperty(sb, "Initial Users", Integer.toString(proposedJobInstance.getBaselineVirtualUsers())); addProperty(sb, "User Increment", Integer.toString(proposedJobInstance.getUserIntervalIncrement())); // users and regions sb.append(BREAK); addProperty(sb, "Total Users", Integer.toString(proposedJobInstance.getTotalVirtualUsers()), proposedJobInstance.getTotalVirtualUsers() == 0 ? "error" : "emphasis"); if (proposedJobInstance.getTotalVirtualUsers() == 0) { addError(errorSB, "No users defined."); } for (JobRegion r : regions) { if (config.getStandalone()) { addProperty(sb, " Users", r.getUsers()); } else { addProperty(sb, " " + r.getRegion().getDescription(), r.getUsers()); } } sb.append(BREAK); sb.append(BREAK); int userPercentage = 0; for (TestPlan plan : workload.getTestPlans()) { userPercentage += plan.getUserPercentage(); } if (userPercentage != 100) { addError(errorSB, "User Percentage of Test Plans does not add up to 100%"); } // datafiles addProperty(sb, "Data Files", proposedJobInstance.getDataFileVersions().size() == 0 ? "None" : null, "emphasis"); DataFileDao dfd = new DataFileDao(); Set<String> datafiles = new HashSet<String>(); for (EntityVersion ver : proposedJobInstance.getDataFileVersions()) { DataFile df = dfd.findById(ver.getObjectId()); if (df != null) { addProperty(sb, " " + df.getPath(), null); datafiles.add(df.getPath()); } else { addProperty(sb, " " + ver.getObjectId(), "data file not found.", "error"); } } sb.append(BREAK); // variables addProperty(sb, "Global Variables", proposedJobInstance.getVariables().size() == 0 ? "None" : " (Allow Overide: " + proposedJobInstance.isAllowOverride() + ")", "emphasis"); for (Entry<String, String> entry : proposedJobInstance.getVariables().entrySet()) { addProperty(sb, " " + entry.getKey(), entry.getValue()); if (entry.getValue().toLowerCase().endsWith(".csv") && !datafiles.contains(entry.getValue())) { addProperty(sb, " WARNING", "This variable, " + entry.getKey() + " appears to be a reference to a datafile, " + entry.getValue() + " that is not declared.", "error"); } } sb.append(BREAK); // notifications addProperty(sb, "Notifications", proposedJobInstance.getNotificationVersions().size() == 0 ? "None" : null, "emphasis"); JobNotificationDao jnd = new JobNotificationDao(); for (EntityVersion ver : proposedJobInstance.getNotificationVersions()) { JobNotification not = jnd.findById(ver.getObjectId()); if (not != null) { if (not.getLifecycleEvents().size() > 0) { addProperty(sb, " " + not.getRecipientList(), StringUtils.join(not.getLifecycleEvents(), ", ")); } else { addProperty(sb, " " + not.getRecipientList(), "no events selected", "error"); } } } sb.append(BREAK); addProperty(sb, "Scripts", "", "emphasis"); // scripts List<ScriptGroupStep> stepsList = new ArrayList<ScriptGroupStep>(); for (TestPlan plan : workload.getTestPlans()) { int numUsers = plan.getUserPercentage() > 0 ? proposedJobInstance.getTotalVirtualUsers() : 0; if (plan.getUserPercentage() < 100 && plan.getUserPercentage() > 0) { numUsers = (int) Math.floor(numUsers * ((double) plan.getUserPercentage() / 100D)); } addProperty(sb, " " + plan.getName(), plan.getUserPercentage() + "% : (" + numUsers + " users) : estimated Time " + TimeUtil.toTimeString(validator.getExpectedTime(plan.getName())), userPercentage != 100 ? "error" : null); if (plan.getScriptGroups().size() == 0) { addProperty(sb, " " + plan.getName(), "contains no script groups", "error"); } for (ScriptGroup group : plan.getScriptGroups()) { addProperty(sb, " " + group.getName(), "loop " + group.getLoop() + " time(s)"); if (group.getScriptGroupSteps().size() == 0) { addProperty(sb, " " + group.getName(), "contains no scripts", "error"); } for (ScriptGroupStep s : group.getScriptGroupSteps()) { stepsList.add(s); addProperty(sb, " " + s.getScript().getName(), "loop " + s.getLoop() + " time(s)"); } } } sb.append(BREAK); if (stepsList.size() == 0) { addError(errorSB, "No scripts defined."); } } else { addProperty(sb, scriptName, "Estimated Time " + validator.getDuration(scriptName), "emphasis"); sb.append(BREAK); sb.append(BREAK); } addProperty(sb, "Variable Validation", "", "emphasis"); addProperty(sb, " Declared Variables", "", "emphasis"); for (Entry<String, Set<String>> entry : validator.getDeclaredVariables().entrySet()) { for (String value : entry.getValue()) { addProperty(sb, " " + entry.getKey(), value, validator.isSuperfluous(entry.getKey()) ? "error" : null); } } sb.append(BREAK); addProperty(sb, " Used Variables", "", "emphasis"); for (String s : validator.getUsedVariables()) { addProperty(sb, " ", s, validator.isOrphaned(s) ? "error" : null); } sb.append(BREAK); if (validator.isProcessAssignements()) { addProperty(sb, " Assignements", "", "emphasis"); for (Entry<String, Set<String>> entry : validator.getAssignments().entrySet()) { for (String value : entry.getValue()) { addProperty(sb, " " + entry.getKey(), value, validator.isSuperfluous(entry.getKey()) ? "error" : null); } } sb.append(BREAK); } sb.append(BREAK); if (!validator.getBestPracticeViolations().isEmpty()) { StringBuilder tsb = new StringBuilder(); addProperty(tsb, "Best Practice Violations", "", "emphasis"); for (String s : validator.getBestPracticeViolations()) { addError(tsb, s); } tsb.append(BREAK); tsb.append(BREAK); sb.insert(0, tsb.toString()); } if (errorSB.length() > 0) { sb = new StringBuilder().append("ERRORS").append(BREAK).append(errorSB.append(BREAK).toString()) .append(sb.toString()); } return sb.toString(); }