List of usage examples for java.util LinkedHashMap size
int size();
From source file:lucee.runtime.config.XMLConfigWebFactory.java
/** * @param configServer/* ww w . ja v a2 s .com*/ * @param config * @param doc * @throws IOException */ private static void loadComponent(ConfigServer configServer, ConfigImpl config, Document doc, int mode) { Element component = getChildByName(doc.getDocumentElement(), "component"); boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_SETTING); boolean hasSet = false; boolean hasCS = configServer != null; // String virtual="/component/"; if (component != null && hasAccess) { // component-default-import String strCDI = component.getAttribute("component-default-import"); if (StringUtil.isEmpty(strCDI, true) && configServer != null) { strCDI = ((ConfigServerImpl) configServer).getComponentDefaultImport().toString(); } if (!StringUtil.isEmpty(strCDI, true)) config.setComponentDefaultImport(strCDI); // Base CFML String strBase = component.getAttribute("base-cfml"); if (StringUtil.isEmpty(strBase, true)) strBase = component.getAttribute("base"); if (StringUtil.isEmpty(strBase, true) && configServer != null) { strBase = configServer.getBaseComponentTemplate(CFMLEngine.DIALECT_CFML); } config.setBaseComponentTemplate(CFMLEngine.DIALECT_CFML, strBase); // Base Lucee strBase = component.getAttribute("base-lucee"); if (StringUtil.isEmpty(strBase, true)) { if (configServer != null) strBase = configServer.getBaseComponentTemplate(CFMLEngine.DIALECT_LUCEE); else strBase = "/lucee/Component.lucee"; } config.setBaseComponentTemplate(CFMLEngine.DIALECT_LUCEE, strBase); // deep search if (mode == ConfigImpl.MODE_STRICT) { config.setDoComponentDeepSearch(false); } else { String strDeepSearch = component.getAttribute("deep-search"); if (!StringUtil.isEmpty(strDeepSearch)) { config.setDoComponentDeepSearch(Caster.toBooleanValue(strDeepSearch.trim(), false)); } else if (hasCS) { config.setDoComponentDeepSearch(((ConfigServerImpl) configServer).doComponentDeepSearch()); } } // Dump-Template String strDumpRemplate = component.getAttribute("dump-template"); if ((strDumpRemplate == null || strDumpRemplate.trim().length() == 0) && configServer != null) { strDumpRemplate = configServer.getComponentDumpTemplate(); } config.setComponentDumpTemplate(strDumpRemplate); // data-member-default-access if (mode == ConfigImpl.MODE_STRICT) { config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); } else { String strDmda = component.getAttribute("data-member-default-access"); if (strDmda != null && strDmda.trim().length() > 0) { strDmda = strDmda.toLowerCase().trim(); if (strDmda.equals("remote")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_REMOTE); else if (strDmda.equals("public")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PUBLIC); else if (strDmda.equals("package")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PACKAGE); else if (strDmda.equals("private")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); } else if (configServer != null) { config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess()); } } // trigger-properties if (mode == ConfigImpl.MODE_STRICT) { config.setTriggerComponentDataMember(true); } else { Boolean tp = Caster.toBoolean(component.getAttribute("trigger-data-member"), null); if (tp != null) config.setTriggerComponentDataMember(tp.booleanValue()); else if (configServer != null) { config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember()); } } // local search if (mode == ConfigImpl.MODE_STRICT) { config.setComponentLocalSearch(false); } else { Boolean ls = Caster.toBoolean(component.getAttribute("local-search"), null); if (ls != null) config.setComponentLocalSearch(ls.booleanValue()); else if (configServer != null) { config.setComponentLocalSearch(((ConfigServerImpl) configServer).getComponentLocalSearch()); } } // use cache path Boolean ucp = Caster.toBoolean(component.getAttribute("use-cache-path"), null); if (ucp != null) config.setUseComponentPathCache(ucp.booleanValue()); else if (configServer != null) { config.setUseComponentPathCache(((ConfigServerImpl) configServer).useComponentPathCache()); } // use component shadow if (mode == ConfigImpl.MODE_STRICT) { config.setUseComponentShadow(false); } else { Boolean ucs = Caster.toBoolean(component.getAttribute("use-shadow"), null); if (ucs != null) config.setUseComponentShadow(ucs.booleanValue()); else if (configServer != null) { config.setUseComponentShadow(configServer.useComponentShadow()); } } } else if (configServer != null) { config.setBaseComponentTemplate(CFMLEngine.DIALECT_CFML, configServer.getBaseComponentTemplate(CFMLEngine.DIALECT_CFML)); config.setBaseComponentTemplate(CFMLEngine.DIALECT_LUCEE, configServer.getBaseComponentTemplate(CFMLEngine.DIALECT_LUCEE)); config.setComponentDumpTemplate(configServer.getComponentDumpTemplate()); if (mode == ConfigImpl.MODE_STRICT) { config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); config.setTriggerComponentDataMember(true); } else { config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess()); config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember()); } } if (mode == ConfigImpl.MODE_STRICT) { config.setDoComponentDeepSearch(false); config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); config.setTriggerComponentDataMember(true); config.setComponentLocalSearch(false); config.setUseComponentShadow(false); } // Web Mapping Element[] cMappings = getChildren(component, "mapping"); hasSet = false; Mapping[] mappings = null; if (hasAccess && cMappings.length > 0) { mappings = new Mapping[cMappings.length]; for (int i = 0; i < cMappings.length; i++) { Element cMapping = cMappings[i]; String physical = cMapping.getAttribute("physical"); String archive = cMapping.getAttribute("archive"); boolean readonly = toBoolean(cMapping.getAttribute("readonly"), false); boolean hidden = toBoolean(cMapping.getAttribute("hidden"), false); //boolean trusted = toBoolean(cMapping.getAttribute("trusted"), false); int listMode = ConfigWebUtil.toListenerMode(cMapping.getAttribute("listener-mode"), -1); int listType = ConfigWebUtil.toListenerType(cMapping.getAttribute("listener-type"), -1); short inspTemp = inspectTemplate(cMapping); String virtual = XMLConfigAdmin.createVirtual(cMapping); //int clMaxEl = toInt(cMapping.getAttribute("classloader-max-elements"), 100); String primary = cMapping.getAttribute("primary"); boolean physicalFirst = archive == null || !primary.equalsIgnoreCase("archive"); hasSet = true; mappings[i] = new MappingImpl(config, virtual, physical, archive, inspTemp, physicalFirst, hidden, readonly, true, false, true, null, listMode, listType); } config.setComponentMappings(mappings); } // Server Mapping if (hasCS) { Mapping[] originals = ((ConfigServerImpl) configServer).getComponentMappings(); Mapping[] clones = new Mapping[originals.length]; LinkedHashMap map = new LinkedHashMap(); Mapping m; for (int i = 0; i < clones.length; i++) { m = ((MappingImpl) originals[i]).cloneReadOnly(config); map.put(toKey(m), m); // clones[i]=((MappingImpl)m[i]).cloneReadOnly(config); } if (mappings != null) { for (int i = 0; i < mappings.length; i++) { m = mappings[i]; map.put(toKey(m), m); } } if (originals.length > 0) { clones = new Mapping[map.size()]; Iterator it = map.entrySet().iterator(); Map.Entry entry; int index = 0; while (it.hasNext()) { entry = (Entry) it.next(); clones[index++] = (Mapping) entry.getValue(); // print.out("c:"+clones[index-1]); } hasSet = true; // print.err("set:"+clones.length); config.setComponentMappings(clones); } } if (!hasSet) { MappingImpl m = new MappingImpl(config, "/default", "{lucee-web}/components/", null, ConfigImpl.INSPECT_UNDEFINED, true, false, false, true, false, true, null, -1, -1); config.setComponentMappings(new Mapping[] { m.cloneReadOnly(config) }); } }
From source file:com.github.cmisbox.core.Queue.java
private void synchAllWatches() throws Exception { Storage storage = Storage.getInstance(); CMISRepository cmisRepository = CMISRepository.getInstance(); UI ui = UI.getInstance();//from w w w. j av a2 s . c o m Config config = Config.getInstance(); if (ui.isAvailable()) { ui.setStatus(Status.SYNCH); } List<String[]> updates = new ArrayList<String[]>(); Changes changes = cmisRepository.getContentChanges(storage.getRootIds()); LinkedHashMap<String, File> downloadList = new LinkedHashMap<String, File>(); boolean errors = false; for (ChangeItem item : changes.getEvents()) { try { if (item == null) { continue; } String id = "workspace://SpacesStore/" + item.getId(); String type = item.getT(); StoredItem storedItem = storage.findById(id); if (type.equals("D")) { if (storedItem != null) { File f = new File(config.getWatchParent() + storedItem.getPath()); f.delete(); storage.delete(storedItem, true); } } else if (type.equals("C") || type.equals("U")) { CmisObject remoteObject = cmisRepository.findObject(id); remoteObject.refresh(); if (remoteObject.getType().getBaseTypeId().equals(BaseTypeId.CMIS_FOLDER)) { Folder folder = (Folder) remoteObject; File newFile = new File(this.resolvePath(folder.getFolderParent()), folder.getName()); if (storedItem == null) { storage.add(newFile, folder, false); } else { if ((folder.getLastModificationDate().getTimeInMillis() > storedItem .getRemoteModified()) && !storedItem.getName().equals(folder.getName())) { if (new File(storedItem.getAbsolutePath()).renameTo(newFile)) { storage.localUpdate(storedItem, newFile, folder); } else { if (ui.isAvailable()) { ui.notify(Messages.renameError + " " + storedItem.getAbsolutePath() + " -> " + newFile.getAbsolutePath()); } this.log.error("Unable to rename " + storedItem.getAbsolutePath() + " to " + newFile.getAbsolutePath()); } } } } else { Document document = (Document) remoteObject; this.log.debug("preparing to update or create " + document.getName()); File newFile = new File(this.resolvePath(document.getParents().get(0)), document.getName()); if (storedItem == null) { downloadList.put(id, newFile); } else { File current = new File(storedItem.getAbsolutePath()); if (storedItem.getLocalModified() < document.getLastModificationDate() .getTimeInMillis()) { if (!current.getAbsolutePath().equals(newFile.getAbsolutePath())) { if (!current.renameTo(newFile)) { if (ui.isAvailable()) { ui.notify(Messages.renameError + " " + storedItem.getAbsolutePath() + " -> " + newFile.getAbsolutePath()); } this.log.error("Unable to rename " + storedItem.getAbsolutePath() + " to " + newFile.getAbsolutePath()); } } downloadList.put(id, newFile); } } } } } catch (Exception e1) { errors = true; this.log.error("Error getting remote chahges for " + item, e1); } } if (ui.isAvailable() && (downloadList.size() > 0)) { ui.notify(Messages.downloading + " " + downloadList.size() + " " + Messages.files); } for (Entry<String, File> e : downloadList.entrySet()) { try { storage.deleteById(e.getKey()); e.getValue().delete(); cmisRepository.download(cmisRepository.getDocument(e.getKey()), e.getValue()); storage.add(e.getValue(), cmisRepository.getDocument(e.getKey())); } catch (Exception e1) { errors = true; this.log.error("Error downloading " + e, e1); if (ui.isAvailable()) { ui.notify(Messages.errorDownloading + " " + e); } } } if (!errors) { config.setChangeLogToken(changes.getToken()); } if (ui.isAvailable()) { ui.setStatus(Status.OK); if (updates.size() == 1) { ui.notify(updates.get(0)[0] + " " + Messages.updatedBy + " " + updates.get(0)[1]); } else if (updates.size() > 1) { ui.notify(Messages.updated + " " + updates.size() + Messages.files); } } }
From source file:com.egt.core.db.ddl.MapaClases.java
private Map addClases(String filtro) throws SQLException { LinkedHashMap clases = new LinkedHashMap(); LinkedHashMap tablas = new LinkedHashMap(); String sql = "SELECT * FROM vista_script_tablas "; if (filtro != null && !filtro.equals("")) { sql += "WHERE (" + filtro + ")"; }// w w w . ja va 2 s . c o m // sql += "ORDER BY codigo_clase_objeto, tabname, numero_seccion_clase, numero_propiedad_clase, colid"; sql += "ORDER BY codigo_clase_objeto, tabname, id_propiedad_clase, colid"; this.resultSet = TLC.getAgenteSql().executeQuery(sql); if (this.resultSet.next()) { String tabname = null; String tabdescription = null; Integer colid = null; String colname = null; String coldescription = null; Integer coltype = null; Integer length = null; Integer prec = null; Integer scale = null; Integer isnullable = null; Integer autonumber = null; Long clase = null; String codigoClase = null; Integer esClaseSincronizada = null; Long seccion = null; String codigoSeccion = null; Integer esSeccionMultiple = null; String sufijoSeccion = null; Integer esSeccionSincronizada = null; Long propiedad = null; String codigoPropiedad = null; Integer esPropiedadMultiple = null; String sufijoPropiedad = null; Integer esPropiedadSincronizada = null; Long tipoValor = null; String claseAnterior = null; String tablaAnterior = null; Clase s = null; Tabla t = null; Columna c = null; do { tabname = this.resultSet.getString("tabname"); tabdescription = this.resultSet.getString("tabdescription"); colid = (Integer) this.resultSet.getObject("colid"); colname = this.resultSet.getString("colname"); coldescription = this.resultSet.getString("coldescription"); coltype = (Integer) this.resultSet.getObject("coltype"); length = (Integer) this.resultSet.getObject("length"); prec = (Integer) this.resultSet.getObject("prec"); scale = (Integer) this.resultSet.getObject("scale"); isnullable = (Integer) this.resultSet.getObject("isnullable"); autonumber = (Integer) this.resultSet.getObject("autonumber"); clase = (Long) this.resultSet.getObject("id_clase_objeto"); codigoClase = this.resultSet.getString("codigo_clase_objeto"); esClaseSincronizada = (Integer) this.resultSet.getObject("es_clase_sincronizada"); seccion = (Long) this.resultSet.getObject("id_seccion_clase"); codigoSeccion = this.resultSet.getString("codigo_seccion_clase"); esSeccionMultiple = (Integer) this.resultSet.getObject("es_seccion_multiple"); sufijoSeccion = this.resultSet.getString("sufijo_tabla_seccion_clase"); esSeccionSincronizada = (Integer) this.resultSet.getObject("es_seccion_sincronizada"); propiedad = (Long) this.resultSet.getObject("id_propiedad_clase"); codigoPropiedad = this.resultSet.getString("codigo_propiedad"); esPropiedadMultiple = (Integer) this.resultSet.getObject("es_propiedad_multiple"); sufijoPropiedad = this.resultSet.getString("sufijo_tabla_propiedad_clase"); esPropiedadSincronizada = (Integer) this.resultSet.getObject("es_propiedad_sincronizada"); tipoValor = (Long) this.resultSet.getObject("id_tipo_valor"); if (!codigoClase.equals(claseAnterior)) { claseAnterior = codigoClase; tablaAnterior = null; s = new Clase(clase, codigoClase); clases.put(codigoClase, s); } if (!tabname.equals(tablaAnterior)) { tablaAnterior = tabname; t = s.addTabla(tabname, this.getNombreTabla(tabname, seccion, esSeccionMultiple, codigoSeccion, sufijoSeccion, codigoPropiedad, sufijoPropiedad)); t.setDescripcion(tabdescription); t.setSincronizada(this.getTablaSincronizada(seccion, esSeccionMultiple, esClaseSincronizada, esSeccionSincronizada, esPropiedadSincronizada)); tablas.put(tabname, t); } if (BitUtils.valueOf(esSeccionMultiple)) { t.setSeccion(seccion); } else if (BitUtils.valueOf(esPropiedadMultiple)) { t.setPropiedad(propiedad); } c = t.addColumna(colname, propiedad); c.setDescripcion(coldescription); c.setTipo(coltype); c.setLongitud(length); c.setPrecision(prec); c.setEscala(scale); c.setAnulable(isnullable); c.setAutonumerica(autonumber); c.setDominio(tipoValor); c.setPropiedad(propiedad); c.setSincronizada(this.getColumnaSincronizada(colid, t.getSincronizada(), esPropiedadSincronizada)); } while (this.resultSet.next()); } this.resultSet.close(); if (tablas.size() > 0) { this.addClavesPrimarias(tablas); this.addClavesForaneas(tablas); this.addClavesUnicas(tablas); this.addClavesDuplicadas(tablas); } return clases; }
From source file:com.nest5.businessClient.Initialactivity.java
private void makeDailyTable(int TABLE_TYPE) { dailyTable.removeAllViews();//from w ww . j a v a 2s .com Double total = 0.0; DecimalFormat dec = new DecimalFormat("$###,###,###"); TextView tv = new TextView(mContext); tv.setBackgroundColor(Color.parseColor("#80808080")); tv.setHeight(2); TableRow tr1 = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate1 = (TextView) tr1.findViewById(R.id.cell_date); TextView tItem1 = (TextView) tr1.findViewById(R.id.cell_item); TextView tAccount1 = (TextView) tr1.findViewById(R.id.cell_account); TextView tVal1 = (TextView) tr1.findViewById(R.id.cell_value); TextView tTot1 = (TextView) tr1.findViewById(R.id.cell_total); tDate1.setText("FECHA"); tAccount1.setText("CUENTA"); tItem1.setText("ITEM"); tVal1.setText("VALOR"); tTot1.setText("TOTAL"); tr1.setBackgroundColor(Color.CYAN); dailyTable.addView(tr1); dailyTable.addView(tv); //actualizar sales de hoy Calendar today = Calendar.getInstance(); Calendar tomorrow = Calendar.getInstance(); today.set(Calendar.HOUR, 0); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); tomorrow.roll(Calendar.DATE, 1); tomorrow.set(Calendar.HOUR, 0); tomorrow.set(Calendar.HOUR_OF_DAY, 0); tomorrow.set(Calendar.MINUTE, 0); tomorrow.set(Calendar.SECOND, 0); tomorrow.set(Calendar.MILLISECOND, 0); init = today.getTimeInMillis(); end = tomorrow.getTimeInMillis(); Log.d("GUARDANDOVENTA", today.toString()); Log.d("GUARDANDOVENTA", tomorrow.toString()); Calendar now = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); Log.d(TAG, now.toString()); Log.d(TAG, "Diferencia entre tiempos: " + String.valueOf(end - init)); salesFromToday = saleDataSource.getAllSalesWithin(init, end); List<Sale> usingSales = salesFromToday; switch (TABLE_TYPE) { case TABLE_TYPE_TODAY: usingSales = salesFromToday; break; case TABLE_TYPE_ALL: usingSales = saleList; break; } for (Sale currentSale : usingSales) { double totalLocal = 0.0; LinkedHashMap<Combo, Double> combos = currentSale.getCombos(); LinkedHashMap<Product, Double> products = currentSale.getProducts(); LinkedHashMap<Ingredient, Double> ingredients = currentSale.getIngredients(); Log.w("DAYILETABLES", " " + combos.size() + " " + products.size() + " " + ingredients.size()); Iterator<Entry<Combo, Double>> it = combos.entrySet().iterator(); Calendar date = Calendar.getInstance(); date.setTimeInMillis(currentSale.getDate()); String fecha = date.get(Calendar.MONTH) + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + date.get(Calendar.YEAR) + "\n" + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND); String account = currentSale.getPaymentMethod(); while (it.hasNext()) { TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Map.Entry<Combo, Double> pair = (Map.Entry<Combo, Double>) it.next(); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName() + " en Combo"); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } Iterator<Entry<Product, Double>> it2 = products.entrySet().iterator(); while (it2.hasNext()) { Map.Entry<Product, Double> pair = (Map.Entry<Product, Double>) it2.next(); TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName()); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } Iterator<Entry<Ingredient, Double>> it3 = ingredients.entrySet().iterator(); while (it3.hasNext()) { Map.Entry<Ingredient, Double> pair = (Map.Entry<Ingredient, Double>) it3.next(); TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); Double value = pair.getValue() * pair.getKey().getPrice(); tDate.setText(fecha); tAccount.setText(account); tItem.setText(pair.getKey().getName()); tVal.setText(dec.format(value)); tTot.setText("----"); total += value; totalLocal += value; dailyTable.addView(tr); // Log.d("INGREDIENTES","INGREDIENTE: "+ingrediente.getKey().getName()+" "+ingrediente.getValue()); } TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate = (TextView) tr.findViewById(R.id.cell_date); TextView tItem = (TextView) tr.findViewById(R.id.cell_item); TextView tAccount = (TextView) tr.findViewById(R.id.cell_account); TextView tVal = (TextView) tr.findViewById(R.id.cell_value); TextView tTot = (TextView) tr.findViewById(R.id.cell_total); tDate.setText(fecha); tAccount.setText("-------"); tItem.setText("Ingreso por Ventas"); tVal.setText("----"); tTot.setText(dec.format(totalLocal)); tr.setBackgroundColor(Color.LTGRAY); dailyTable.addView(tr); TableRow tr2 = (TableRow) getLayoutInflater().inflate(R.layout.daily_table_row, null); TextView tDate2 = (TextView) tr2.findViewById(R.id.cell_date); TextView tItem2 = (TextView) tr2.findViewById(R.id.cell_item); TextView tAccount2 = (TextView) tr2.findViewById(R.id.cell_account); TextView tVal2 = (TextView) tr2.findViewById(R.id.cell_value); TextView tTot2 = (TextView) tr2.findViewById(R.id.cell_total); tDate2.setText(fecha); tAccount2.setText("-------"); tItem2.setText("Acumulado por Ventas"); tVal2.setText("----"); tTot2.setText(dec.format(total)); tr2.setBackgroundColor(Color.GRAY); dailyTable.addView(tr2); } }
From source file:com.gp.cong.logisoft.lcl.report.LclAllBLPdfCreator.java
public PdfPTable appendChargesAndCommodity() throws Exception { LclBlAcDAO lclBlAcDAO = new LclBlAcDAO(); List<LclBlPiece> lclBlPiecesList = lclbl.getLclFileNumber().getLclBlPieceList(); List<LclBlAc> chargeList = lclBlAcDAO.getLclCostByFileNumberAsc(lclbl.getFileNumberId()); PdfPTable chargeTable = new PdfPTable(6); PdfPCell chargeCell = null;/*from w w w . ja va 2 s. co m*/ chargeTable.setWidths(new float[] { 3.8f, 1.5f, .8f, 3.8f, 1.5f, .8f }); chargeTable.setWidthPercentage(100f); Paragraph p = null; this.total_ar_amount = 0.00; this.total_ar_col_amount = 0.00; this.total_ar_ppd_amount = 0.00; List<LinkedHashMap<String, PdfPCell>> listChargeMap = null; LinkedHashMap<String, PdfPCell> chargeMap = null; if ("BOTH".equalsIgnoreCase(billType)) { listChargeMap = this.getTotalChargesList(chargeList, lclBlPiecesList); } else { chargeMap = this.getTotalCharges(chargeList, lclBlPiecesList); } LclBlAc blAC = lclBlAcDAO.manualChargeValidate(lclbl.getFileNumberId(), "OCNFRT", false); if (lclBlPiecesList != null && lclBlPiecesList.size() > 0 && blAC != null) { BigDecimal CFT = BigDecimal.ZERO, LBS = BigDecimal.ZERO; LclBlPiece lclBlPiece = (LclBlPiece) lclBlPiecesList.get(0); if (blAC.getRatePerUnitUom() != null) { CFT = blAC.getRatePerUnitUom().equalsIgnoreCase("FRV") ? blAC.getRatePerVolumeUnit() : BigDecimal.ZERO; LBS = blAC.getRatePerUnitUom().equalsIgnoreCase("FRW") ? blAC.getRatePerWeightUnit() : BigDecimal.ZERO; } if (CFT != BigDecimal.ZERO || LBS != BigDecimal.ZERO) { StringBuilder cbmValues = new StringBuilder(); if (CFT != BigDecimal.ZERO && lclBlPiece.getActualVolumeImperial() != null) { cbmValues.append(NumberUtils .convertToThreeDecimalhash(lclBlPiece.getActualVolumeImperial().doubleValue())); } if (LBS != BigDecimal.ZERO && lclBlPiece.getActualWeightImperial() != null) { cbmValues.append(NumberUtils .convertToThreeDecimalhash(lclBlPiece.getActualWeightImperial().doubleValue())); } if (null != blAC.getArAmount() && blAC.getArAmount().toString().equalsIgnoreCase(OCNFRT_Total)) { if (CFT == BigDecimal.ZERO) { cbmValues.append(" LBS @ ").append(LBS).append(" PER 100 LBS @ ") .append(blAC.getArAmount()); } else { cbmValues.append(" CFT @ ").append(CFT).append(" PER CFT @").append(blAC.getArAmount()); } chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(6); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(6); p = new Paragraph(2f, "" + cbmValues.toString().toUpperCase(), totalFontQuote); p.add(new Paragraph(2f, null != lclBlPiece && null != lclBlPiece.getCommodityType() ? " Commodity# " + lclBlPiece.getCommodityType().getCode() : " Commodity#", totalFontQuote)); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } } } this.OCNFRT_Total = ""; LinkedHashMap<String, PdfPCell> left_chargeMap = new LinkedHashMap<String, PdfPCell>(); LinkedHashMap<String, PdfPCell> right_chargeMap = new LinkedHashMap<String, PdfPCell>(); if ("BOTH".equalsIgnoreCase(billType) && listChargeMap != null && !listChargeMap.isEmpty()) { if (listChargeMap.size() > 1) { if (listChargeMap.get(0).size() > 6 || listChargeMap.get(1).size() > 6) { chargeMap = new LinkedHashMap<String, PdfPCell>(); chargeMap.putAll(listChargeMap.get(0)); chargeMap.putAll(listChargeMap.get(1)); int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2; for (String key : chargeMap.keySet()) { if (count++ < size) { left_chargeMap.put(key, chargeMap.get(key)); } else { right_chargeMap.put(key, chargeMap.get(key)); } } } else { left_chargeMap.putAll(listChargeMap.get(0)); right_chargeMap.putAll(listChargeMap.get(1)); } } else { int count = 0, size = listChargeMap.get(0).size() / 2 <= 6 ? 6 : listChargeMap.get(0).size() / 2; for (String key : listChargeMap.get(0).keySet()) { if (count++ < size) { left_chargeMap.put(key, listChargeMap.get(0).get(key)); } else { right_chargeMap.put(key, listChargeMap.get(0).get(key)); } } } } else if (chargeMap != null && !chargeMap.isEmpty()) { int count = 0, size = chargeMap.size() / 2 <= 6 ? 6 : chargeMap.size() / 2; for (String key : chargeMap.keySet()) { if (count++ < size) { left_chargeMap.put(key, chargeMap.get(key)); } else { right_chargeMap.put(key, chargeMap.get(key)); } } } if (!left_chargeMap.isEmpty()) { String chargeDesc = null; PdfPTable innner_chargeTable = new PdfPTable(2); innner_chargeTable.setWidthPercentage(100f); PdfPCell inner_chargeCell = null; chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(3); chargeCell.setBorderWidthRight(0.6f); chargeCell.setPadding(0); innner_chargeTable = new PdfPTable(2); innner_chargeTable.setWidths(new float[] { 5f, 3f }); if (!left_chargeMap.isEmpty()) { for (String key : left_chargeMap.keySet()) { inner_chargeCell = new PdfPCell(); inner_chargeCell.setBorder(0); inner_chargeCell.setPaddingLeft(-15); chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$")); inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote)); innner_chargeTable.addCell(inner_chargeCell); inner_chargeCell = new PdfPCell(); inner_chargeCell.setBorder(0); inner_chargeCell = left_chargeMap.get(key); innner_chargeTable.addCell(inner_chargeCell); } } chargeCell.addElement(innner_chargeTable); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(3); chargeCell.setPadding(0); innner_chargeTable = new PdfPTable(2); innner_chargeTable.setWidths(new float[] { 5f, 3f }); if (!left_chargeMap.isEmpty()) { for (String key : right_chargeMap.keySet()) { inner_chargeCell = new PdfPCell(); inner_chargeCell.setBorder(0); inner_chargeCell.setPaddingLeft(-15); chargeDesc = key.substring(key.indexOf("#") + 1, key.indexOf("$")); inner_chargeCell.addElement(new Paragraph(7f, "" + chargeDesc, totalFontQuote)); innner_chargeTable.addCell(inner_chargeCell); inner_chargeCell = new PdfPCell(); inner_chargeCell.setBorder(0); inner_chargeCell = right_chargeMap.get(key); innner_chargeTable.addCell(inner_chargeCell); } } chargeCell.addElement(innner_chargeTable); chargeTable.addCell(chargeCell); } else { this.total_ar_amount = 0.00; this.total_ar_ppd_amount = 0.00; this.total_ar_col_amount = 0.00; } String acctNo = ""; String billToParty = ""; if (CommonFunctions.isNotNull(lclbl.getBillToParty()) && CommonUtils.isNotEmpty(lclbl.getBillToParty())) { if (lclbl.getBillToParty().equalsIgnoreCase("T") && CommonFunctions.isNotNull(lclbl.getThirdPartyAcct())) { billToParty = "THIRD PARTY"; acctNo = lclbl.getThirdPartyAcct().getAccountno(); } else if (lclbl.getBillToParty().equalsIgnoreCase("S") && CommonFunctions.isNotNull(lclbl.getShipAcct())) { billToParty = "SHIPPER"; acctNo = lclbl.getShipAcct().getAccountno(); } else if (lclbl.getBillToParty().equalsIgnoreCase("F") && CommonFunctions.isNotNull(lclbl.getFwdAcct())) { billToParty = "FORWARDER"; acctNo = lclbl.getFwdAcct().getAccountno(); } else if (lclbl.getBillToParty().equalsIgnoreCase("A") && CommonFunctions.isNotNull(lclbl.getAgentAcct())) { billToParty = "AGENT"; if (lclBooking.getBookingType().equals("T") && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) { acctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo().getAccountno(); } else if (lclBooking.getAgentAcct() != null) { acctNo = lclBooking.getAgentAcct().getAccountno(); } else { acctNo = lclbl.getAgentAcct().getAccountno(); } } } if ("BOTH".equalsIgnoreCase(billType)) { if (this.total_ar_ppd_amount != 0.00 || this.total_ar_col_amount != 0.00) { if (this.total_ar_ppd_amount != 0.00) { if (CommonFunctions.isNotNullOrNotEmpty(ppdBillToSet) && ppdBillToSet.size() == 1) { for (String billTo : ppdBillToSet) { arBillToParty = billTo; break; } if (arBillToParty.equalsIgnoreCase("T")) { billToParty = "THIRD PARTY"; acctNo = null != lclbl.getThirdPartyAcct() ? lclbl.getThirdPartyAcct().getAccountno() : acctNo; } else if (arBillToParty.equalsIgnoreCase("S")) { acctNo = null != lclbl.getShipAcct() ? lclbl.getShipAcct().getAccountno() : acctNo; billToParty = "SHIPPER"; } else if (arBillToParty.equalsIgnoreCase("F")) { billToParty = "FORWARDER"; acctNo = null != lclbl.getFwdAcct() ? lclbl.getFwdAcct().getAccountno() : acctNo; } } else { acctNo = null; } chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(2); p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setColspan(4); chargeCell.setBorder(0); if (null != acctNo) { p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount) + " PPD " + billToParty + "-" + acctNo, totalFontQuote); } else { p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_ppd_amount) + " PPD ", totalFontQuote); } p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } if (this.total_ar_col_amount != 0.00) { String colAcctNo = ""; if (lclBooking.getBookingType().equals("T") && lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() != null) { colAcctNo = lclbl.getLclFileNumber().getLclBookingImport().getExportAgentAcctNo() .getAccountno(); } else if (lclBooking.getAgentAcct() != null) { colAcctNo = lclBooking.getAgentAcct().getAccountno(); } else if (lclbl.getAgentAcct() != null) { colAcctNo = lclbl.getAgentAcct().getAccountno(); } chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(2); if (this.total_ar_ppd_amount == 0.00) { p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote); } else { p = new Paragraph(7f, "", totalFontQuote); } p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setColspan(4); chargeCell.setBorder(0); p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_col_amount) + " COL AGENT-" + colAcctNo, totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } NumberFormat numberFormat = new DecimalFormat("###,###,##0.000"); if (this.total_ar_ppd_amount != 0.00) { String totalString1 = numberFormat.format(this.total_ar_ppd_amount).replaceAll(",", ""); int indexdot = totalString1.indexOf("."); String beforeDecimal = totalString1.substring(0, indexdot); String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length()); chargeCell = new PdfPCell(); chargeCell.setColspan(6); chargeCell.setBorder(0); p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal)) + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS", totalFontQuote); chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } if (this.total_ar_col_amount != 0.00) { String totalString1 = numberFormat.format(this.total_ar_col_amount).replaceAll(",", ""); int indexdot = totalString1.indexOf("."); String beforeDecimal = totalString1.substring(0, indexdot); String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length()); chargeCell = new PdfPCell(); chargeCell.setColspan(6); chargeCell.setBorder(0); p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal)) + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS", totalFontQuote); chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } } } else if (this.total_ar_amount != 0.00) { chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(2); chargeCell.setPaddingTop(8f); p = new Paragraph(7f, "T O T A L (USA)", totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setColspan(4); chargeCell.setBorder(0); chargeCell.setPaddingTop(8f); p = new Paragraph(7f, "$" + NumberUtils.convertToTwoDecimal(this.total_ar_amount) + " " + billType + " " + billToParty + "-" + acctNo, totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); NumberFormat numberFormat = new DecimalFormat("###,###,##0.000"); String totalString1 = numberFormat.format(this.total_ar_amount).replaceAll(",", ""); int indexdot = totalString1.indexOf("."); String beforeDecimal = totalString1.substring(0, indexdot); String afterDecimal = totalString1.substring(indexdot + 1, totalString1.length()); chargeCell = new PdfPCell(); chargeCell.setColspan(6); chargeCell.setBorder(0); p = new Paragraph(7f, "" + ConvertNumberToWords.convert(Integer.parseInt(beforeDecimal)) + " DOLLARS AND " + StringUtils.removeEnd(afterDecimal, "0") + " CENTS", totalFontQuote); chargeCell.setHorizontalAlignment(Element.ALIGN_CENTER); chargeCell.addElement(p); chargeTable.addCell(chargeCell); } chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(4); p = new Paragraph(5f, "" + sailDateFormat, totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setColspan(5); chargeCell.setBorder(0); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setColspan(3); chargeCell.setBorder(0); chargeCell.setRowspan(3); String fdPodValue = null; if (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[2])) { fdPodValue = agencyInfo[2]; } else if (CommonFunctions.isNotNull(lclbl.getFinalDestination()) && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId()) && CommonFunctions.isNotNull(lclbl.getFinalDestination().getCountryId().getCodedesc())) { fdPodValue = lclbl.getFinalDestination().getUnLocationName() + "," + lclbl.getFinalDestination().getCountryId().getCodedesc(); } p = new Paragraph(7f, fdPodValue != null ? fdPodValue.toUpperCase() : podValues.toUpperCase(), totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(3); p = new Paragraph(5f, "UNIT# " + unitNumber, headingblackBoldFont); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(3); chargeCell.setPaddingTop(2f); p = new Paragraph(5f, "SEAL# " + sealOut, headingblackBoldFont); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); chargeCell = new PdfPCell(); chargeCell.setBorder(0); chargeCell.setColspan(3); chargeCell.setPaddingTop(2f); p = new Paragraph(5f, "CONTROL-VOY# " + voyageNumber, totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); chargeCell.addElement(p); chargeTable.addCell(chargeCell); String emailId = ""; StringBuilder agentDetails = new StringBuilder(); //Agent Details String agentAcctNo = ""; if ("Y".equalsIgnoreCase(altAgentKey)) { agentAcctNo = CommonUtils.isNotEmpty(altAgentValue) ? altAgentValue : ""; } else if (lclbl.getAgentAcct() != null) { agentAcctNo = (agencyInfo != null && CommonUtils.isNotEmpty(agencyInfo[0])) ? agencyInfo[0] : lclbl.getAgentAcct().getAccountno(); } if (CommonUtils.isNotEmpty(agentAcctNo)) { CustAddress custAddress = new CustAddressDAO().findPrimeContact(agentAcctNo); if (CommonFunctions.isNotNull(custAddress)) { if (CommonFunctions.isNotNull(custAddress.getAcctName())) { agentDetails.append(custAddress.getAcctName()).append(" "); } if (CommonFunctions.isNotNull(custAddress.getPhone())) { agentDetails.append("Phone: ").append(custAddress.getPhone()).append("\n"); } else { agentDetails.append("\n"); } if (CommonFunctions.isNotNull(custAddress.getCoName())) { agentDetails.append(custAddress.getCoName()).append("\n"); } if (CommonFunctions.isNotNull(custAddress.getAddress1())) { agentDetails.append(custAddress.getAddress1().replace(", ", "\n")).append("\n"); } if (CommonFunctions.isNotNull(custAddress.getCity1())) { agentDetails.append(custAddress.getCity1()); } if (CommonFunctions.isNotNull(custAddress.getState())) { agentDetails.append(" ").append(custAddress.getState()); } if (CommonFunctions.isNotNull(custAddress.getEmail1())) { emailId = custAddress.getEmail1(); } } } BigDecimal PrintInvoiceValue = null; if (lclbl.getPortOfDestination() != null) { boolean schnum = new LCLPortConfigurationDAO().getSchnumValue(lclbl.getPortOfDestination().getId()); if (schnum) { BigDecimal printInvoice = lclbl.getInvoiceValue(); Long fileId = lclbl.getFileNumberId(); if (!CommonUtils.isEmpty(printInvoice) && !CommonUtils.isEmpty(fileId)) { PrintInvoiceValue = printInvoice; } } } chargeCell = new PdfPCell(); chargeCell.setBorder(2); chargeCell.setColspan(6); chargeCell.setPadding(0f); PdfPTable agent_Contact_Table = new PdfPTable(3); agent_Contact_Table.setWidthPercentage(100f); agent_Contact_Table.setWidths(new float[] { 2.3f, 1.7f, 1.8f }); PdfPCell agent_Contact_cell = new PdfPCell(); agent_Contact_cell.setBorder(0); agent_Contact_cell.setBorderWidthTop(1f); agent_Contact_cell.setBorderWidthLeft(1f); agent_Contact_cell.setBorderWidthBottom(0.06f); agent_Contact_cell.setBorderWidthRight(1f); p = new Paragraph(7f, "To Pick Up Freight Please Contact: ", blackContentNormalFont); p.setAlignment(Element.ALIGN_LEFT); agent_Contact_cell.addElement(p); agent_Contact_Table.addCell(agent_Contact_cell); agent_Contact_cell = new PdfPCell(); agent_Contact_cell.setBorder(0); agent_Contact_cell.setColspan(2); agent_Contact_cell.setBorderWidthTop(1f); agent_Contact_cell.setPaddingBottom(2f); p = new Paragraph(7f, "Email: " + emailId.toLowerCase(), totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); agent_Contact_cell.addElement(p); agent_Contact_Table.addCell(agent_Contact_cell); agent_Contact_cell = new PdfPCell(); agent_Contact_cell.setColspan(2); agent_Contact_cell.setBorder(0); agent_Contact_cell.setBorderWidthLeft(1f); p = new Paragraph(7f, "" + agentDetails.toString(), totalFontQuote); p.setAlignment(Element.ALIGN_LEFT); agent_Contact_cell.addElement(p); agent_Contact_Table.addCell(agent_Contact_cell); agent_Contact_cell = new PdfPCell(); agent_Contact_cell.setBorder(0); agent_Contact_cell.setPaddingTop(27f); p = new Paragraph(7f, "" + agentAcctNo, totalFontQuote); p.setAlignment(Element.ALIGN_RIGHT); agent_Contact_cell.addElement(p); agent_Contact_Table.addCell(agent_Contact_cell); agent_Contact_cell = new PdfPCell(); agent_Contact_cell.setBorder(0); agent_Contact_cell.setColspan(3); agent_Contact_cell.setBorderWidthLeft(1f); StringBuilder builder = new StringBuilder(); builder.append(PrintInvoiceValue != null ? "Value of Goods:USD $" + PrintInvoiceValue : ""); p = new Paragraph(3f, "" + builder.toString(), totalFontQuote); p.setAlignment(Element.ALIGN_RIGHT); agent_Contact_cell.addElement(p); agent_Contact_Table.addCell(agent_Contact_cell); chargeCell.addElement(agent_Contact_Table); chargeTable.addCell(chargeCell); return chargeTable; }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
/** * Configures all the needed components, but does not actually start the server. * @param config Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy. * @throws Exception Yeah, a lot can go wrong here, but at least it will be caught immediately :-) *///from w ww.jav a 2 s. co m public void config(HierarchicalConfiguration config) throws Exception { List<HierarchicalConfiguration> lconf; HttpAsyncRequester executor = null; BasicNIOConnPool connPool = null; ObjectPool<ByteBuffer> byteBufferPool = null; LinkedHashMap<String, TargetDescriptor> mappings = null; ConcurrentMap<String, HttpHost> hosts = null; handlerRegistry = new UriHttpAsyncRequestHandlerMapper(); // Initialize the keystore (if one was specified) KeyStore keystore = null; char[] keypass = null; String keystoreUri = config.getString("keystore"); if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) { Path keystorePath = Utils.MakePath(keystoreUri); if (!Files.exists(keystorePath)) throw new ConfigurationException("Keystore does not exist."); if (Files.isDirectory(keystorePath)) throw new ConfigurationException("Keystore is not a file"); String storepass = config.getString("storepass"); if ((storepass != null) && "null".equals(storepass)) storepass = null; keystore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) { keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray()); } catch (IOException ex) { Logger.error("Unable to load https server keystore from " + keystoreUri); return; } keypass = config.getString("keypass").trim().toCharArray(); } // Wire up the listening reactor lconf = config.configurationsAt("server"); if ((lconf == null) || (lconf.size() != 1)) throw new ConfigurationException("One (and only one) server configuration element is allowed."); else { Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667))); builder.setSoTimeout(config.getInt("server[@soTimeout]", 0)); builder.setSoLinger(config.getInt("server[@soLinger]", -1)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); builder.setSelectInterval(100); IOReactorConfig rconfig = builder.build(); Logger.info("Configuring server with options: " + rconfig.toString()); listeningReactor = new DefaultListeningIOReactor(rconfig); lconf = config.configurationsAt("server.listen"); InetSocketAddress addr; boolean hasNonWildcardSecure = false; LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>(); if ((lconf == null) || (lconf.size() == 0)) { addr = new InetSocketAddress("127.0.0.1", 8080); ListenerEndpoint ep = listeningReactor.listen(addr); Logger.warn("Configured " + ep.getAddress()); } else { TrustManager[] trustManagers = null; KeyManagerFactory kmf = null; // Create all the specified listeners. for (HierarchicalConfiguration hc : lconf) { String addrStr = hc.getString("[@address]"); if ((addrStr == null) || (addrStr.length() == 0)) addrStr = "0.0.0.0"; String alias = hc.getString("[@alias]"); int port = hc.getInt("[@port]", alias != null ? 443 : 80); addr = new InetSocketAddress(addrStr, port); ListenerEndpoint ep = listeningReactor.listen(addr); String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null; Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null; if ((alias != null) && (secure == null)) secure = true; if ((protocol != null) && (secure == null)) secure = true; if ((secure != null) && secure) { if (protocol == null) protocol = "TLS"; if (keystore == null) throw new ConfigurationException( "An https listening socket was requested, but no keystore was specified."); if (kmf == null) { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); } // Are we going to trust all clients or just specific ones? if (hc.getBoolean("[@trustAny]", true)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } KeyManager[] keyManagers = kmf.getKeyManagers(); if (alias != null) for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) keyManagers[i] = new PokerFaceKeyManager(alias, (X509ExtendedKeyManager) keyManagers[i]); } SSLContext sslCtx = SSLContext.getInstance(protocol); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); if (addr.getAddress().isAnyLocalAddress()) { // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { addr = new InetSocketAddress(enumIpAddr.nextElement(), port); addrSSLContext.put(addr, sslCtx); } } } else { addrSSLContext.put(addr, sslCtx); hasNonWildcardSecure = true; } } Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress()); } } // We will need an HTTP protocol processor for the incoming connections String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version); HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent), new ResponseContent(), new ResponseConnControl() }); HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(), null, handlerRegistry, null) { public void exception(final NHttpServerConnection conn, final Exception cause) { Logger.warn(cause.getMessage()); super.exception(conn, cause); } }; if (addrSSLContext.size() > 0) { final SSLContext defaultCtx = addrSSLContext.values().iterator().next(); final Map<SocketAddress, SSLContext> sslMap; if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1)) sslMap = null; else sslMap = addrSSLContext; listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) { protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext, SSLSetupHandler sslHandler) { SSLIOSession retVal; SSLContext sktCtx = sslcontext; if (sslMap != null) { SocketAddress la = iosession.getLocalAddress(); if (la != null) { sktCtx = sslMap.get(la); if (sktCtx == null) sktCtx = sslcontext; } retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler); } else retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler); if (sktCtx != null) retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true); return retVal; } }); } else listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT); } // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets. lconf = config.configurationsAt("targets"); if ((lconf != null) && (lconf.size() > 0)) { HierarchicalConfiguration conf = lconf.get(0); Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667))); builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0)); builder.setSoLinger(config.getInt("targets[@soLinger]", -1)); builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); connectingReactor = new DefaultConnectingIOReactor(builder.build()); final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024; byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() { @Override public ByteBuffer create() throws Exception { return ByteBuffer.allocateDirect(bufferSize); } @Override public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) { return new DefaultPooledObject<ByteBuffer>(buffer); } }); KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; if (keystore != null) { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); keyManagers = kmf.getKeyManagers(); } // Will the httpclient's trust any remote target, or only specific ones. if (conf.getBoolean("targets[@trustAny]", false)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else if (keystore != null) { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS")); clientSSLContext.init(keyManagers, trustManagers, new SecureRandom()); // Setup an SSL capable connection pool for the httpclients. connPool = new BasicNIOConnPool(connectingReactor, new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT), conf.getInt("targets[@connectTimeout]", 0)); connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023)); connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023)); // Set up HTTP protocol processor for outgoing connections String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version); HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue(true) }); executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy()); // Now set up all the configured targets. mappings = new LinkedHashMap<String, TargetDescriptor>(); hosts = new ConcurrentHashMap<String, HttpHost>(); String[] scheme = { null }; String[] host = { null }; int[] port = { 0 }; String[] path = { null }; int[] stripPrefixCount = { 0 }; for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) { String match = targetConfig.getString("[@pattern]"); if ((match == null) || (match.trim().length() < 1)) { Logger.error("Unable to configure target; Invalid url match pattern"); continue; } String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host, port, path, stripPrefixCount); if (key == null) { Logger.error("Unable to configure target"); continue; } HttpHost targetHost = hosts.get(key); if (targetHost == null) { targetHost = new HttpHost(host[0], port[0], scheme[0]); hosts.put(key, targetHost); } TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]); mappings.put(match, desc); } connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(), ConnectionConfig.DEFAULT); } // Allocate the script map which will be populated by it's own executor thread. if (config.containsKey("scripts.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>(); boolean watch = config.getBoolean("scripts.dynamicWatch", false); List<Path> jsLibs; Object prop = config.getProperty("scripts.library"); if (prop != null) { jsLibs = new ArrayList<Path>(); if (prop instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> oprop = (Collection<Object>) prop; for (Object obj : oprop) jsLibs.add(Utils.MakePath(obj)); } else { jsLibs.add(Utils.MakePath(prop)); } } else jsLibs = null; lconf = config.configurationsAt("scripts.scriptConfig"); if (lconf != null) { if (lconf.size() > 1) throw new ConfigurationException("Only one scriptConfig element is allowed."); if (lconf.size() == 0) lconf = null; } HierarchicalConfiguration scriptConfig; if (lconf == null) scriptConfig = new HierarchicalConfiguration(); else scriptConfig = lconf.get(0); scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString()); configureScripts(jsLibs, scriptConfig, tmp, watch); if (watch) ScriptDirectoryWatcher = new DirectoryWatchService(); } // Configure the static file directory (if any) Path staticFilesPath = null; if (config.containsKey("files.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); staticFilesPath = tmp; List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry"); if (mimeEntries != null) { for (HierarchicalConfiguration entry : mimeEntries) { entry.setDelimiterParsingDisabled(true); String type = entry.getString("[@type]", "").trim(); if (type.length() == 0) throw new ConfigurationException("Invalid mime type entry"); String extensions = entry.getString("[@extensions]", "").trim(); if (extensions.length() == 0) throw new ConfigurationException("Invalid mime extensions for: " + type); ScriptHelperImpl.AddMimeEntry(type, extensions); } } } handlerRegistry.register("/*", new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings, scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null, config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null)); }
From source file:com.ikanow.aleph2.analytics.services.DeduplicationService.java
@Override public void onObjectBatch(final Stream<Tuple2<Long, IBatchRecord>> batch, final Optional<Integer> batch_size, final Optional<JsonNode> grouping_key) { if (_deduplication_is_disabled.get()) { // no deduplication, generally shouldn't be here... //.. but if we are, make do the best we can batch.forEach(t2 -> _context.get().emitImmutableObject(t2._1(), t2._2().getJson(), Optional.empty(), Optional.empty(), Optional.empty())); return;//from w w w.j a v a 2 s. c o m } // Create big query final Tuple3<QueryComponent<JsonNode>, List<Tuple2<JsonNode, Tuple2<Long, IBatchRecord>>>, Either<String, List<String>>> fieldinfo_dedupquery_keyfields = getDedupQuery( batch, _dedup_fields.get(), _db_mapper.get()); // Get duplicate results final Tuple2<List<String>, Boolean> fields_include = getIncludeFields(_policy.get(), _dedup_fields.get(), _timestamp_field.get()); final CompletableFuture<Iterator<JsonNode>> dedup_res = fieldinfo_dedupquery_keyfields._2().isEmpty() ? CompletableFuture.completedFuture(Collections.<JsonNode>emptyList().iterator()) : _dedup_context.get().getObjectsBySpec(fieldinfo_dedupquery_keyfields._1(), fields_include._1(), fields_include._2()).thenApply(cursor -> cursor.iterator()); // Wait for it to finsh //(create handy results structure if so) final LinkedHashMap<JsonNode, LinkedList<Tuple3<Long, IBatchRecord, ObjectNode>>> mutable_obj_map = fieldinfo_dedupquery_keyfields ._2().stream() .collect(Collector.of( () -> new LinkedHashMap<JsonNode, LinkedList<Tuple3<Long, IBatchRecord, ObjectNode>>>(), (acc, t2) -> { // (ie only the first element is added, duplicate elements are removed) final Tuple3<Long, IBatchRecord, ObjectNode> t3 = Tuples._3T(t2._2()._1(), t2._2()._2(), _mapper.createObjectNode()); acc.compute(t2._1(), (k, v) -> { final LinkedList<Tuple3<Long, IBatchRecord, ObjectNode>> new_list = (null == v) ? new LinkedList<>() : v; new_list.add(t3); return new_list; }); }, (map1, map2) -> { map1.putAll(map2); return map1; })); //TODO (ALEPH-20): add timestamps to annotation //TODO (ALEPH-20): support different timestamp fields for the different buckets //TODO (ALEPH-20): really need to support >1 current enrichment job // ^^(Really really longer term you should be able to decide what objects you want and what you don't <- NOTE: don't remember what i meant here) final Iterator<JsonNode> cursor = dedup_res.join(); // Handle the results final Stream<JsonNode> records_to_delete = Lambdas.get(() -> { if (isCustom(_doc_schema.get().deduplication_policy()) || _doc_schema.get().delete_unhandled_duplicates()) { return Optionals.streamOf(cursor, true) .collect(Collectors.groupingBy( ret_obj -> getKeyFieldsAgain(ret_obj, fieldinfo_dedupquery_keyfields._3()))) .entrySet().stream().<JsonNode>flatMap(kv -> { final Optional<JsonNode> maybe_key = kv.getKey(); final Optional<LinkedList<Tuple3<Long, IBatchRecord, ObjectNode>>> matching_records = maybe_key .map(key -> mutable_obj_map.get(key)); // Stats: _mutable_stats.duplicate_keys++; _mutable_stats.duplicates_existing += kv.getValue().size(); _mutable_stats.duplicates_incoming += matching_records.map(l -> l.size()).orElse(0); //DEBUG //System.out.println("?? " + kv.getValue().size() + " vs " + maybe_key + " vs " + matching_records.map(x -> Integer.toString(x.size())).orElse("(no match)")); return matching_records .<Stream<JsonNode>>map(records -> handleDuplicateRecord(_doc_schema.get(), _custom_handler.optional().map( handler -> Tuples._2T(handler, this._custom_context.get())), _timestamp_field.get(), records, kv.getValue(), maybe_key.get(), mutable_obj_map)) .orElse(Stream.empty()); }); } else { Optionals.streamOf(cursor, true).forEach(ret_obj -> { final Optional<JsonNode> maybe_key = getKeyFieldsAgain(ret_obj, fieldinfo_dedupquery_keyfields._3()); final Optional<LinkedList<Tuple3<Long, IBatchRecord, ObjectNode>>> matching_records = maybe_key .map(key -> mutable_obj_map.get(key)); //DEBUG //System.out.println("?? " + ret_obj + " vs " + maybe_key + " vs " + matching_record.map(x -> x._2().getJson().toString()).orElse("(no match)")); // Stats: _mutable_stats.duplicate_keys++; _mutable_stats.duplicates_existing++; _mutable_stats.duplicates_incoming += matching_records.map(l -> l.size()).orElse(0); matching_records.ifPresent(records -> handleDuplicateRecord(_doc_schema.get(), _custom_handler.optional() .map(handler -> Tuples._2T(handler, this._custom_context.get())), _timestamp_field.get(), records, Arrays.asList(ret_obj), maybe_key.get(), mutable_obj_map)); }); return Stream.<JsonNode>empty(); } }); final List<Object> ids = records_to_delete.map(j -> jsonToObject(j)).filter(j -> null != j) .collect(Collectors.toList()); if (!ids.isEmpty()) { // fire a bulk deletion request mutable_uncompleted_deletes.add( _dedup_context.get().deleteObjectsBySpec(CrudUtils.allOf().withAny(AnnotationBean._ID, ids))); _mutable_stats.deleted += ids.size(); //(quickly see if we can reduce the number of outstanding requests) final Iterator<CompletableFuture<Long>> it = mutable_uncompleted_deletes.iterator(); while (it.hasNext()) { final CompletableFuture<Long> cf = it.next(); if (cf.isDone()) { it.remove(); } else break; // ie stop as soon as we hit one that isn't complete) } } _mutable_stats.nonduplicate_keys += mutable_obj_map.size(); if (Optional.ofNullable(_doc_schema.get().custom_finalize_all_objects()).orElse(false)) { mutable_obj_map.entrySet().stream() .forEach(kv -> handleCustomDeduplication( _custom_handler.optional() .map(handler -> Tuples._2T(handler, this._custom_context.get())), kv.getValue(), Collections.emptyList(), kv.getKey())); } else { // Just emit the last element of each grouped object set mutable_obj_map.values().stream().map(t -> t.peekLast()) .forEach(t -> _context.get().emitImmutableObject(t._1(), t._2().getJson(), Optional.of(t._3()), Optional.empty(), Optional.empty())); } }
From source file:org.cerberus.servlet.crud.testexecution.ReadTestCaseExecution.java
private AnswerItem findExecutionListByTag(ApplicationContext appContext, HttpServletRequest request, String Tag) throws CerberusException, ParseException, JSONException { AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK)); testCaseLabelService = appContext.getBean(ITestCaseLabelService.class); int startPosition = Integer .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0")); int length = Integer .valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0")); String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), ""); String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "test,testCase,application,priority,status,description,bugId,function"); String columnToSort[] = sColumns.split(","); //Get Sorting information int numberOfColumnToSort = Integer .parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortingCols"), "1")); int columnToSortParameter = 0; String sort = "asc"; StringBuilder sortInformation = new StringBuilder(); for (int c = 0; c < numberOfColumnToSort; c++) { columnToSortParameter = Integer .parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_" + c), "0")); sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_" + c), "asc"); String columnName = columnToSort[columnToSortParameter]; sortInformation.append(columnName).append(" ").append(sort); if (c != numberOfColumnToSort - 1) { sortInformation.append(" , "); }//from www . j av a 2 s . com } Map<String, List<String>> individualSearch = new HashMap<String, List<String>>(); for (int a = 0; a < columnToSort.length; a++) { if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) { List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(","))); individualSearch.put(columnToSort[a], search); } } List<TestCaseExecution> testCaseExecutions = readExecutionByTagList(appContext, Tag, startPosition, length, sortInformation.toString(), searchParameter, individualSearch); JSONArray executionList = new JSONArray(); JSONObject statusFilter = getStatusList(request); JSONObject countryFilter = getCountryList(request, appContext); LinkedHashMap<String, JSONObject> ttc = new LinkedHashMap<String, JSONObject>(); String globalStart = ""; String globalEnd = ""; String globalStatus = "Finished"; /** * Find the list of labels */ AnswerList testCaseLabelList = testCaseLabelService.readByTestTestCase(null, null); for (TestCaseExecution testCaseExecution : testCaseExecutions) { try { if (testCaseExecution.getStart() != 0) { if ((globalStart.isEmpty()) || (globalStart.compareTo(String.valueOf(testCaseExecution.getStart())) > 0)) { globalStart = String.valueOf(testCaseExecution.getStart()); } } if (testCaseExecution.getEnd() != 0) { if ((globalEnd.isEmpty()) || (globalEnd.compareTo(String.valueOf(testCaseExecution.getEnd())) < 0)) { globalEnd = String.valueOf(testCaseExecution.getEnd()); } } if (testCaseExecution.getControlStatus().equalsIgnoreCase("PE")) { globalStatus = "Pending..."; } String controlStatus = testCaseExecution.getControlStatus(); if (statusFilter.get(controlStatus).equals("on") && countryFilter.get(testCaseExecution.getCountry()).equals("on")) { JSONObject execution = testCaseExecutionToJSONObject(testCaseExecution); String execKey = testCaseExecution.getEnvironment() + " " + testCaseExecution.getCountry() + " " + testCaseExecution.getBrowser(); String testCaseKey = testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase(); JSONObject execTab = new JSONObject(); executionList.put(testCaseExecutionToJSONObject(testCaseExecution)); JSONObject ttcObject = new JSONObject(); if (ttc.containsKey(testCaseKey)) { ttcObject = ttc.get(testCaseKey); execTab = ttcObject.getJSONObject("execTab"); execTab.put(execKey, execution); ttcObject.put("execTab", execTab); } else { ttcObject.put("test", testCaseExecution.getTest()); ttcObject.put("testCase", testCaseExecution.getTestCase()); ttcObject.put("function", testCaseExecution.getTestCaseObj().getFunction()); ttcObject.put("shortDesc", testCaseExecution.getTestCaseObj().getDescription()); ttcObject.put("status", testCaseExecution.getStatus()); ttcObject.put("application", testCaseExecution.getApplication()); ttcObject.put("priority", testCaseExecution.getTestCaseObj().getPriority()); ttcObject.put("bugId", new JSONObject( "{\"bugId\":\"" + testCaseExecution.getTestCaseObj().getBugID() + "\",\"bugTrackerUrl\":\"" + testCaseExecution.getApplicationObj().getBugTrackerUrl().replace( "%BUGID%", testCaseExecution.getTestCaseObj().getBugID()) + "\"}")); ttcObject.put("comment", testCaseExecution.getTestCaseObj().getComment()); execTab.put(execKey, execution); ttcObject.put("execTab", execTab); /** * Iterate on the label retrieved and generate HashMap * based on the key Test_TestCase */ LinkedHashMap<String, JSONArray> testCaseWithLabel = new LinkedHashMap(); for (TestCaseLabel label : (List<TestCaseLabel>) testCaseLabelList.getDataList()) { String key = label.getTest() + "_" + label.getTestcase(); if (testCaseWithLabel.containsKey(key)) { JSONObject jo = new JSONObject().put("name", label.getLabel().getLabel()) .put("color", label.getLabel().getColor()) .put("description", label.getLabel().getDescription()); testCaseWithLabel.get(key).put(jo); } else { JSONObject jo = new JSONObject().put("name", label.getLabel().getLabel()) .put("color", label.getLabel().getColor()) .put("description", label.getLabel().getDescription()); testCaseWithLabel.put(key, new JSONArray().put(jo)); } } ttcObject.put("labels", testCaseWithLabel .get(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase())); } ttc.put(testCaseExecution.getTest() + "_" + testCaseExecution.getTestCase(), ttcObject); } } catch (JSONException ex) { Logger.getLogger(ReadTestCaseExecution.class.getName()).log(Level.SEVERE, null, ex); } } JSONObject jsonResponse = new JSONObject(); jsonResponse.put("globalEnd", globalEnd.toString()); jsonResponse.put("globalStart", globalStart.toString()); jsonResponse.put("globalStatus", globalStatus); jsonResponse.put("testList", ttc.values()); jsonResponse.put("iTotalRecords", ttc.size()); jsonResponse.put("iTotalDisplayRecords", ttc.size()); answer.setItem(jsonResponse); answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK)); return answer; }
From source file:lu.fisch.unimozer.Diagram.java
public void run() { try {/*from w w w .jav a 2s . com*/ // compile all //doCompilationOnly(null); //frame.setCompilationErrors(new Vector<CompilationError>()); if (compile()) { Vector<String> mains = getMains(); String runnable = null; if (mains.size() == 0) { JOptionPane.showMessageDialog(frame, "Sorry, but your project does not contain any runnable public class ...", "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } else { if (mains.size() == 1) { runnable = mains.get(0); } else { String[] classNames = new String[mains.size()]; for (int c = 0; c < mains.size(); c++) classNames[c] = mains.get(c); runnable = (String) JOptionPane.showInputDialog(frame, "Unimozer detected more than one runnable class.\n" + "Please select which one you want to run.", "Run", JOptionPane.QUESTION_MESSAGE, Unimozer.IMG_QUESTION, classNames, ""); } // we know now what to run MyClass runnClass = classes.get(runnable); // set full signature String fullSign = "void main(String[] args)"; if (runnClass.hasMain2()) fullSign = "void main(String args[])"; // get signature String sign = runnClass.getSignatureByFullSignature(fullSign); String complete = runnClass.getCompleteSignatureBySignature(sign); if ((runnClass.hasMain2()) && (sign.equals("void main(String)"))) { sign = "void main(String[])"; } //System.out.println("Calling method (full): "+fullSign); //System.out.println("Calling method : "+sign); // find method Class c = Runtime5.getInstance().load(runnClass.getFullName()); Method m[] = c.getMethods(); for (int i = 0; i < m.length; i++) { String full = ""; full += m[i].getReturnType().getSimpleName(); full += " "; full += m[i].getName(); full += "("; Class<?>[] tvm = m[i].getParameterTypes(); LinkedHashMap<String, String> genericInputs = new LinkedHashMap<String, String>(); for (int t = 0; t < tvm.length; t++) { String sn = tvm[t].toString(); genericInputs.put("param" + t, sn); sn = sn.substring(sn.lastIndexOf('.') + 1, sn.length()); if (sn.startsWith("class")) sn = sn.substring(5).trim(); // array is shown as ";" ??? if (sn.endsWith(";")) { sn = sn.substring(0, sn.length() - 1) + "[]"; } full += sn + ", "; } if (tvm.length > 0) full = full.substring(0, full.length() - 2); full += ")"; //if((full.equals(sign) || full.equals(fullSign))) // System.out.println("Found: "+full); if ((full.equals(sign) || full.equals(fullSign))) { LinkedHashMap<String, String> inputs = runnClass.getInputsBySignature(sign); //System.out.println(inputs); //System.out.println(genericInputs); if (inputs.size() != genericInputs.size()) { inputs = genericInputs; } MethodInputs mi = null; boolean go = true; if (inputs.size() > 0) { mi = new MethodInputs(frame, inputs, full, runnClass.getJavaDocBySignature(sign)); go = mi.OK; } if (go == true) { try { String method = runnClass.getFullName() + "." + m[i].getName() + "("; if (inputs.size() > 0) { Object[] keys = inputs.keySet().toArray(); //int cc = 0; for (int in = 0; in < keys.length; in++) { String name = (String) keys[in]; String val = mi.getValueFor(name); if (val.equals("")) val = "null"; else if (!val.startsWith("new String[]")) { String[] pieces = val.split("\\s+"); String inp = ""; for (int iin = 0; iin < pieces.length; iin++) { if (inp.equals("")) inp = pieces[iin]; else inp += "\",\"" + pieces[iin].replace("\"", "\\\""); } val = "new String[] {\"" + inp + "\"}"; } method += val + ","; } method = method.substring(0, method.length() - 1); } method += ")"; // Invoke method in a new thread final String myMeth = method; Console.disconnectAll(); System.out.println("Running now: " + myMeth); Console.connectAll(); Runnable r = new Runnable() { public void run() { Console.cls(); try { //Console.disconnectAll(); //System.out.println(myMeth); Object retobj = Runtime5.getInstance().executeMethod(myMeth); if (retobj != null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE, Unimozer.IMG_INFO); } catch (EvalError ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } }; Thread t = new Thread(r); t.start(); //System.out.println(method); //Object retobj = Runtime5.getInstance().executeMethod(method); //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO); } catch (Throwable ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } } } } } } catch (ClassNotFoundException ex) { JOptionPane.showMessageDialog(frame, "There was an error while running your project ...", "Error :: ClassNotFoundException", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } }
From source file:lu.fisch.unimozer.Diagram.java
@Override public void actionPerformed(ActionEvent e) { if (isEnabled()) { if (e.getSource() instanceof JMenuItem) { JMenuItem item = (JMenuItem) e.getSource(); if (item.getText().equals("Compile")) { compile();//from w w w.j a va2 s .com } else if (item.getText().equals("Remove class") && mouseClass != null) { int answ = JOptionPane.showConfirmDialog(frame, "Are you sure to remove the class " + mouseClass.getFullName() + "", "Remove a class", JOptionPane.YES_NO_OPTION); if (answ == JOptionPane.YES_OPTION) { cleanAll();// clean(mouseClass); removedClasses.add(mouseClass.getFullName()); classes.remove(mouseClass.getFullName()); mouseClass = null; updateEditor(); repaint(); objectizer.repaint(); } } else if (mouseClass.getName().contains("abstract")) { JOptionPane.showMessageDialog(frame, "Can't create an object of an abstract class ...", "Instatiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } else if (item.getText().startsWith("new")) // we have constructor { Logger.getInstance().log("Click on <new> registered"); // get full signature String fSign = item.getText(); if (fSign.startsWith("new")) fSign = fSign.substring(3).trim(); // get signature final String fullSign = fSign; Logger.getInstance().log("fullSign = " + fSign); final String sign = mouseClass.getSignatureByFullSignature(fullSign); Logger.getInstance().log("sign = " + sign); Logger.getInstance().log("Creating runnable ..."); Runnable r = new Runnable() { @Override public void run() { //System.out.println("Calling method (full): "+fullSign); //System.out.println("Calling method : "+sign); try { Logger.getInstance().log("Loading the class <" + mouseClass.getName() + ">"); Class<?> cla = Runtime5.getInstance().load(mouseClass.getFullName()); //mouseClass.load(); Logger.getInstance().log("Loaded!"); // check if we need to specify a generic class boolean cont = true; String generics = ""; TypeVariable[] tv = cla.getTypeParameters(); Logger.getInstance().log("Got TypeVariables with length = " + tv.length); if (tv.length > 0) { LinkedHashMap<String, String> gms = new LinkedHashMap<String, String>(); for (int i = 0; i < tv.length; i++) { gms.put(tv[i].getName(), ""); } MethodInputs gi = new MethodInputs(frame, gms, "Generic type declaration", "Please specify the generic types"); cont = gi.OK; // build the string generics = "<"; Object[] keys = gms.keySet().toArray(); mouseClass.generics.clear(); for (int in = 0; in < keys.length; in++) { String kname = (String) keys[in]; // save generic type to myClass mouseClass.generics.put(kname, gi.getValueFor(kname)); generics += gi.getValueFor(kname) + ","; } generics = generics.substring(0, generics.length() - 1); generics += ">"; } if (cont == true) { Logger.getInstance().log("Getting the constructors."); Constructor[] constr = cla.getConstructors(); for (int c = 0; c < constr.length; c++) { // get signature String full = objectizer.constToFullString(constr[c]); Logger.getInstance().log("full = " + full); /* String full = constr[c].getName(); full+="("; Class<?>[] tvm = constr[c].getParameterTypes(); for(int t=0;t<tvm.length;t++) { String sn = tvm[t].toString(); sn=sn.substring(sn.lastIndexOf('.')+1,sn.length()); if(sn.startsWith("class")) sn=sn.substring(5).trim(); // array is shown as ";" ??? if(sn.endsWith(";")) { sn=sn.substring(0,sn.length()-1)+"[]"; } full+= sn+", "; } if(tvm.length>0) full=full.substring(0,full.length()-2); full+= ")"; */ /*System.out.println("Loking for S : "+sign); System.out.println("Loking for FS: "+fullSign); System.out.println("Found: "+full);*/ if (full.equals(sign) || full.equals(fullSign)) { Logger.getInstance().log("We are in!"); //editor.setEnabled(false); //Logger.getInstance().log("Editor disabled"); String name; Logger.getInstance().log("Ask user for a name."); do { String propose = mouseClass.getShortName().substring(0, 1) .toLowerCase() + mouseClass.getShortName().substring(1); int count = 0; String prop = propose + count; while (objectizer.hasObject(prop) == true) { count++; prop = propose + count; } name = (String) JOptionPane.showInputDialog(frame, "Please enter the name for you new instance of " + mouseClass.getShortName() + "", "Create object", JOptionPane.QUESTION_MESSAGE, null, null, prop); if (Java.isIdentifierOrNull(name) == false) { JOptionPane.showMessageDialog(frame, "" + name + " is not a correct identifier.", "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } else if (objectizer.hasObject(name) == true) { JOptionPane.showMessageDialog(frame, "An object with the name " + name + " already exists.\nPlease choose another name ...", "Error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } } while (Java.isIdentifierOrNull(name) == false || objectizer.hasObject(name) == true); Logger.getInstance().log("name = " + name); if (name != null) { Logger.getInstance().log("Need to get inputs ..."); LinkedHashMap<String, String> inputs = mouseClass .getInputsBySignature(sign); if (inputs.size() == 0) inputs = mouseClass.getInputsBySignature(fullSign); //System.out.println("1) "+sign); //System.out.println("2) "+fullSign); MethodInputs mi = null; boolean go = true; if (inputs.size() > 0) { mi = new MethodInputs(frame, inputs, full, mouseClass.getJavaDocBySignature(sign)); go = mi.OK; } Logger.getInstance().log("go = " + go); if (go == true) { Logger.getInstance().log("Building string ..."); //Object arglist[] = new Object[inputs.size()]; String constructor = "new " + mouseClass.getFullName() + generics + "("; if (inputs.size() > 0) { Object[] keys = inputs.keySet().toArray(); for (int in = 0; in < keys.length; in++) { String kname = (String) keys[in]; //String type = inputs.get(kname); //if(type.equals("int")) { arglist[in] = Integer.valueOf(mi.getValueFor(kname)); } //else if(type.equals("short")) { arglist[in] = Short.valueOf(mi.getValueFor(kname)); } //else if(type.equals("byte")) { arglist[in] = Byte.valueOf(mi.getValueFor(kname)); } //else if(type.equals("long")) { arglist[in] = Long.valueOf(mi.getValueFor(kname)); } //else if(type.equals("float")) { arglist[in] = Float.valueOf(mi.getValueFor(kname)); } //else if(type.equals("double")) { arglist[in] = Double.valueOf(mi.getValueFor(kname)); } //else if(type.equals("boolean")) { arglist[in] = Boolean.valueOf(mi.getValueFor(kname)); } //else arglist[in] = mi.getValueFor(kname); String val = mi.getValueFor(kname); if (val.equals("")) val = "null"; else { String type = mi.getTypeFor(kname); if (type.toLowerCase().equals("byte")) constructor += "Byte.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("short")) constructor += "Short.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("float")) constructor += "Float.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("long")) constructor += "Long.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("double")) constructor += "Double.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("char")) constructor += "'" + val + "',"; else constructor += val + ","; } //constructor+=mi.getValueFor(kname)+","; } constructor = constructor.substring(0, constructor.length() - 1); } //System.out.println(arglist); constructor += ")"; //System.out.println(constructor); Logger.getInstance().log("constructor = " + constructor); //LOAD: //addLibs(); Object obj = Runtime5.getInstance().getInstance(name, constructor); //mouseClass.getInstance(name, constructor); Logger.getInstance().log("Objet is now instantiated!"); //Runtime.getInstance().interpreter.getNameSpace().i //System.out.println(obj.getClass().getSimpleName()); //Object obj = constr[c].newInstance(arglist); MyObject myo = objectizer.addObject(name, obj); myo.setMyClass(mouseClass); obj = null; cla = null; } objectizer.repaint(); Logger.getInstance().log("Objectizer repainted ..."); repaint(); Logger.getInstance().log("Diagram repainted ..."); } //editor.setEnabled(true); //Logger.getInstance().log("Editor enabled again ..."); } } } } catch (Exception ex) { //ex.printStackTrace(); MyError.display(ex); JOptionPane.showMessageDialog(frame, ex.toString(), "Instantiation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); } } }; Thread t = new Thread(r); t.start(); } else // we have a static method { try { // get full signature String fullSign = ((JMenuItem) e.getSource()).getText(); // get signature String sign = mouseClass.getSignatureByFullSignature(fullSign).replace(", ", ","); String complete = mouseClass.getCompleteSignatureBySignature(sign).replace(", ", ","); /*System.out.println("Calling method (full): "+fullSign); System.out.println("Calling method : "+sign); System.out.println("Calling method (comp): "+complete);/**/ // find method Class c = Runtime5.getInstance().load(mouseClass.getFullName()); Method m[] = c.getMethods(); for (int i = 0; i < m.length; i++) { /*String full = ""; full+= m[i].getReturnType().getSimpleName(); full+=" "; full+= m[i].getName(); full+= "("; Class<?>[] tvm = m[i].getParameterTypes(); LinkedHashMap<String,String> genericInputs = new LinkedHashMap<String,String>(); for(int t=0;t<tvm.length;t++) { String sn = tvm[t].toString(); //System.out.println(sn); if(sn.startsWith("class")) sn=sn.substring(5).trim(); sn=sn.substring(sn.lastIndexOf('.')+1,sn.length()); // array is shown as ";" ??? if(sn.endsWith(";")) { sn=sn.substring(0,sn.length()-1)+"[]"; } full+= sn+", "; genericInputs.put("param"+t,sn); } if(tvm.length>0) full=full.substring(0,full.length()-2); full+= ")";*/ String full = objectizer.toFullString(m[i]); LinkedHashMap<String, String> genericInputs = objectizer.getInputsReplaced(m[i], null); /*System.out.println("Looking for S : "+sign); System.out.println("Looking for FS: "+fullSign); System.out.println("Found : "+full);*/ if (full.equals(sign) || full.equals(fullSign)) { LinkedHashMap<String, String> inputs = mouseClass.getInputsBySignature(sign); //Objectizer.printLinkedHashMap("inputs", inputs); if (inputs.size() != genericInputs.size()) { inputs = genericInputs; } //Objectizer.printLinkedHashMap("inputs", inputs); MethodInputs mi = null; boolean go = true; if (inputs.size() > 0) { mi = new MethodInputs(frame, inputs, full, mouseClass.getJavaDocBySignature(sign)); go = mi.OK; } if (go == true) { try { String method = mouseClass.getFullName() + "." + m[i].getName() + "("; if (inputs.size() > 0) { Object[] keys = inputs.keySet().toArray(); //int cc = 0; for (int in = 0; in < keys.length; in++) { String name = (String) keys[in]; String val = mi.getValueFor(name); if (val.equals("")) method += val + "null,"; else { String type = mi.getTypeFor(name); if (type.toLowerCase().equals("byte")) method += "Byte.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("short")) method += "Short.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("float")) method += "Float.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("long")) method += "Long.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("double")) method += "Double.valueOf(\"" + val + "\"),"; else if (type.toLowerCase().equals("char")) method += "'" + val + "',"; else method += val + ","; } //if (val.equals("")) val="null"; //method+=val+","; } if (!method.endsWith("(")) method = method.substring(0, method.length() - 1); } method += ")"; //System.out.println(method); // Invoke method in a new thread final String myMeth = method; Runnable r = new Runnable() { public void run() { try { Object retobj = Runtime5.getInstance().executeMethod(myMeth); if (retobj != null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE, Unimozer.IMG_INFO); } catch (EvalError ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Invokation error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } }; Thread t = new Thread(r); t.start(); //System.out.println(method); //Object retobj = Runtime5.getInstance().executeMethod(method); //if(retobj!=null) JOptionPane.showMessageDialog(frame, retobj.toString(), "Result", JOptionPane.INFORMATION_MESSAGE,Unimozer.IMG_INFO); } catch (Throwable ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } } } } catch (Exception ex) { JOptionPane.showMessageDialog(frame, ex.toString(), "Execution error", JOptionPane.ERROR_MESSAGE, Unimozer.IMG_ERROR); MyError.display(ex); } } } } }