List of usage examples for org.xml.sax Attributes getQName
public abstract String getQName(int index);
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
private String getRefObjectNameFromAttr(Attributes attrs) { String refObjName = null;//from ww w . j av a2s. com for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { refObjName = attValue; } } return refObjName; }
From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java
private void startActivity(Attributes attributes) throws SAXException { // if (!SIM_XML_ROOT.equals(curElement)) // throw new SAXParseException("<" + SIM_XML_ACTIVITY + ">: must have <" + SIM_XML_ROOT + "> as parent element", saxLocator); if (simCurrTime == null) simCurrTime = new UsecTimestamp(); TNT4JSimulator.trace(simCurrTime, "Started activity ..."); TrackingActivity parentActivity = curActivity; activeActivities.push(curActivity);//from www. j a v a2 s. c om curActivity = null; curActivityStart = new UsecTimestamp(simCurrTime); String name = null; int srcId = 0; ActivityStatus status = null; OpLevel sev = null; OpCompCode cc = null; int rc = 0; long pid = 0L; long tid = 0L; String exc = null; String loc = null; String res = null; String user = null; String[] corrs = null; try { for (int i = 0; i < attributes.getLength(); i++) { String attName = attributes.getQName(i); String attValue = expandEnvVars(attributes.getValue(i)); if (attName.equals(SIM_XML_ATTR_NAME)) { name = attValue; } else if (attName.equals(SIM_XML_ATTR_SOURCE)) { srcId = Integer.parseInt(attValue); if (srcId <= 0) throw new SAXParseException( "Invalid <" + SIM_XML_ACTIVITY + "> attribute '" + attName + "', must be > 0", saxLocator); } else if (attName.equals(SIM_XML_ATTR_STATUS)) { status = ActivityStatus.valueOf(attValue); } else if (attName.equals(SIM_XML_ATTR_SEVERITY)) { sev = getLevel(attValue); } else if (attName.equals(SIM_XML_ATTR_CC)) { cc = OpCompCode.valueOf(attValue); } else if (attName.equals(SIM_XML_ATTR_RC)) { rc = Integer.parseInt(attValue); } else if (attName.equals(SIM_XML_ATTR_PID)) { pid = Long.parseLong(attValue); if (pid <= 0L) throw new SAXParseException( "Invalid <" + SIM_XML_ACTIVITY + "> attribute '" + attName + "', must be > 0", saxLocator); } else if (attName.equals(SIM_XML_ATTR_TID)) { tid = Long.parseLong(attValue); if (tid <= 0L) throw new SAXParseException( "Invalid <" + SIM_XML_ACTIVITY + "> attribute '" + attName + "', must be > 0", saxLocator); } else if (attName.equals(SIM_XML_ATTR_EXC)) { exc = attValue; } else if (attName.equals(SIM_XML_ATTR_LOC)) { loc = attValue; } else if (attName.equals(SIM_XML_ATTR_RES)) { res = attValue; } else if (attName.equals(SIM_XML_ATTR_USER)) { user = attValue; } else if (attName.equals(SIM_XML_ATTR_CORRS)) { corrs = attValue.split(","); for (int c = 0; c < corrs.length; c++) { if (TNT4JSimulator.isGenerateValues()) corrs[c] = generateValues(corrs[c]); if (!Utils.isEmpty(corSuffix)) { corrs[c] += corSuffix; } } } else { throw new SAXParseException("Unknown <" + SIM_XML_ACTIVITY + "> attribute '" + attName + "'", saxLocator); } } if (srcId <= 0) throw new SAXParseException( "<" + SIM_XML_ACTIVITY + "> attribute '" + SIM_XML_ATTR_SOURCE + "' is missing", saxLocator); Source source = sourceIds.get(srcId); if (source == null) throw new SAXParseException( "<" + SIM_XML_ACTIVITY + ">: " + SIM_XML_ATTR_SOURCE + " '" + srcId + "' is not defined", saxLocator); curTracker = trackers.get(source.getFQName()); if (curTracker == null) throw new SAXParseException( "<" + SIM_XML_ACTIVITY + ">: " + SIM_XML_ATTR_SOURCE + " '" + srcId + "' is not defined", saxLocator); curActivity = curTracker.newActivity(); curActivity.setTTL(TNT4JSimulator.getTTL()); curActivity.setSource(source); curActivity.setUser(user == null ? source.getUser() : user); curActivity.setStatus(status == null ? ActivityStatus.BEGIN : status); curActivity.setSeverity(sev == null ? OpLevel.INFO : sev); curActivity.setCompCode(cc == null ? OpCompCode.SUCCESS : cc); if (pid > 0L) curActivity.setPID(pid); if (tid > 0L) curActivity.setTID(tid); if (!StringUtils.isEmpty(name)) curActivity.setName(name); if (!StringUtils.isEmpty(loc)) curActivity.setLocation(loc); if (!StringUtils.isEmpty(res)) curActivity.setResource(res); if (status != null) curActivity.setStatus(status); if (rc != 0) curActivity.setReasonCode(rc); if (!StringUtils.isEmpty(exc)) curActivity.setException(exc); if (!ArrayUtils.isEmpty(corrs)) curActivity.setCorrelator(corrs); TNT4JSimulator.debug(simCurrTime, "Started activity: " + name); curActivity.start(curActivityStart); if (parentActivity != null) parentActivity.add(curActivity); } catch (Exception e) { if (e instanceof SAXException) throw (SAXException) e; throw new SAXException("Failed processing event '" + name + "': " + e, e); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <resource-ref>} element. * * @param attrs/*from w w w . ja v a 2 s. c o m*/ * List of element attributes * * @throws SAXException * if error occurs parsing element */ private void processResourceReference(Attributes attrs) throws SAXException { String id = null; String type = null; String uri = null; String delim = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (ID_ATTR.equals(attName)) { id = attValue; } else if (TYPE_ATTR.equals(attName)) { type = attValue; } else if (URI_ATTR.equals(attName)) { uri = attValue; } else if (SEPARATOR_ATTR.equals(attName)) { delim = attValue; } } notEmpty(id, RESOURCE_REF_ELMT, ID_ATTR); notEmpty(type, RESOURCE_REF_ELMT, TYPE_ATTR); notEmpty(uri, RESOURCE_REF_ELMT, URI_ATTR); if (type.equals(ResourceReferenceType.VALUES_MAP.value())) { try { if (resourcesMap == null) { resourcesMap = new HashMap<>(5); } InputStream is; try { URL url = new URL(uri); is = url.openStream(); } catch (MalformedURLException exc) { is = new FileInputStream(uri); } if (uri.toLowerCase().endsWith(".json")) { // NON-NLS resourcesMap.put(id, Utils.fromJsonToMap(is, false)); } else if (uri.toLowerCase().endsWith(".csv")) { // NON-NLS resourcesMap.put(id, fromPropsToMap(is, StringUtils.isEmpty(delim) ? "," : delim)); // NON-NLS } else if (uri.toLowerCase().endsWith(".properties")) { // NON-NLS resourcesMap.put(id, fromPropsToMap(is, StringUtils.isEmpty(delim) ? "=" : delim)); // NON-NLS } else { throw new SAXParseException( StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.invalidResource", id, uri), currParseLocation); } Utils.close(is); } catch (Exception e) { throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.jsonParseException", id, uri), e); } } else { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.invalidRefType", id, type), currParseLocation); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <java-object>} element. * * @param attrs//from ww w .j av a2 s . co m * List of element attributes * * @throws SAXException * if error occurs parsing element */ private void processJavaObject(Attributes attrs) throws SAXException { if (javaObjectData == null) { javaObjectData = new JavaObjectData(); } String name = null; String className = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { name = attValue; } else if (CLASS_ATTR.equals(attName)) { className = attValue; } } notEmpty(name, JAVA_OBJ_ELMT, NAME_ATTR); notEmpty(className, JAVA_OBJ_ELMT, CLASS_ATTR); javaObjectData.name = name; javaObjectData.className = className; }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import flat storages to the hierarchical storage * * @param con an open and valid connection to store imported data * @param zip zip file containing the data * @throws Exception on errors//from w w w .j a va 2 s .c o m */ protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception { //mapping: storage->level->columnname->assignment id final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>( 5); //mapping: assignment id->position index final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100); //mapping: flatstorage->column sizes [string,bigint,double,select,text] final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5); ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(zip.getInputStream(zeMeta)); XPath xPath = XPathFactory.newInstance().newXPath(); //calculate column sizes NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document, XPathConstants.NODESET); Node currNode; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue()); int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue()); int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue()); int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue()); int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue()); String tableName = null; if (currNode.hasChildNodes()) { for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { tableName = currNode.getChildNodes().item(j).getTextContent(); } } if (tableName != null) { flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext }); } } //parse mappings nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue()); int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue()); String storage = null; String columnname = null; final NodeList childNodes = currNode.getChildNodes(); for (int c = 0; c < childNodes.getLength(); c++) { Node child = childNodes.item(c); if ("tblname".equals(child.getNodeName())) storage = child.getTextContent(); else if ("colname".equals(child.getNodeName())) columnname = child.getTextContent(); } if (storage == null || columnname == null) throw new Exception("Invalid flatstorage export: could not read storage or column name!"); if (!flatAssignmentMapping.containsKey(storage)) flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20)); Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage); if (!levelMap.containsKey(level)) levelMap.put(level, new HashMap<String, Long>(30)); Map<String, Long> columnMap = levelMap.get(level); if (!columnMap.containsKey(columnname)) columnMap.put(columnname, assignment); //calculate position assignmentPositions.put(assignment, getAssignmentPosition(flatstoragesColumns.get(storage), columnname)); } if (flatAssignmentMapping.size() == 0) { LOG.warn("No flatstorage assignments found to process!"); return; } ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT); final String xpathStorage = "flatstorages/storage"; final String xpathData = "flatstorages/storage/data"; final PreparedStatement psGetAssInfo = con.prepareStatement( "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY"); final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size()); final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA + //1 2 3 4 5 6 =1 =1 =1 =1 7 8 9 "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,"; final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,"; final PreparedStatement psString = con .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)"); final PreparedStatement psText = con .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)"); final PreparedStatement psDouble = con .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psNumber = con .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psLargeNumber = con .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psFloat = con .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psBoolean = con .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psReference = con .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)"); final PreparedStatement psSelectOne = con .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)"); try { final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final DefaultHandler handler = new DefaultHandler() { private String currentElement = null; private String currentStorage = null; private Map<String, String> data = new HashMap<String, String>(10); private StringBuilder sbData = new StringBuilder(10000); boolean inTag = false; boolean inElement = false; List<String> path = new ArrayList<String>(10); StringBuilder currPath = new StringBuilder(100); int insertCount = 0; /** * {@inheritDoc} */ @Override public void startDocument() throws SAXException { inTag = false; inElement = false; path.clear(); currPath.setLength(0); sbData.setLength(0); data.clear(); currentElement = null; currentStorage = null; insertCount = 0; } /** * {@inheritDoc} */ @Override public void endDocument() throws SAXException { LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage"); } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { pushPath(qName, attributes); if (currPath.toString().equals(xpathData)) { inTag = true; data.clear(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if (StringUtils.isEmpty(name)) name = attributes.getQName(i); data.put(name, attributes.getValue(i)); } } else if (currPath.toString().equals(xpathStorage)) { currentStorage = attributes.getValue("name"); LOG.info("Processing storage: " + currentStorage); } else { currentElement = qName; } inElement = true; sbData.setLength(0); } /** * Push a path element from the stack * * @param qName element name to push * @param att attributes */ @SuppressWarnings({ "UnusedDeclaration" }) private void pushPath(String qName, Attributes att) { path.add(qName); buildPath(); } /** * Pop the top path element from the stack */ private void popPath() { path.remove(path.size() - 1); buildPath(); } /** * Rebuild the current path */ private synchronized void buildPath() { currPath.setLength(0); for (String s : path) currPath.append(s).append('/'); if (currPath.length() > 1) currPath.delete(currPath.length() - 1, currPath.length()); // System.out.println("currPath: " + currPath); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (currPath.toString().equals(xpathData)) { // LOG.info("Insert [" + xpathData + "]: [" + data + "]"); inTag = false; processData(); /*try { if (insertMode) { if (executeInsertPhase) { processColumnSet(insertColumns, psInsert); counter += psInsert.executeUpdate(); } } else { if (executeUpdatePhase) { if (processColumnSet(updateSetColumns, psUpdate)) { processColumnSet(updateClauseColumns, psUpdate); counter += psUpdate.executeUpdate(); } } } } catch (SQLException e) { throw new SAXException(e); } catch (ParseException e) { throw new SAXException(e); }*/ } else { if (inTag) { data.put(currentElement, sbData.toString()); } currentElement = null; } popPath(); inElement = false; sbData.setLength(0); } void processData() { // System.out.println("processing " + currentStorage + " -> " + data); final String[] cols = { "string", "bigint", "double", "select", "text" }; for (String column : data.keySet()) { if (column.endsWith("_mld")) continue; for (String check : cols) { if (column.startsWith(check)) { if ("select".equals(check) && "0".equals(data.get(column))) continue; //dont insert 0-referencing selects try { insertData(column); } catch (SQLException e) { //noinspection ThrowableInstanceNeverThrown throw new FxDbException(e, "ex.db.sqlError", e.getMessage()) .asRuntimeException(); } } } } } private void insertData(String column) throws SQLException { final int level = Integer.parseInt(data.get("lvl")); long assignment = flatAssignmentMapping.get(currentStorage).get(level) .get(column.toUpperCase()); int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',', assignmentPositions.get(assignment)); String _valueData = data.get("valuedata"); Integer valueData = _valueData == null ? null : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',', assignmentPositions.get(assignment)); Object[] propXP = getPropertyXPathDataType(assignment); long prop = (Long) propXP[0]; String xpath = (String) propXP[1]; FxDataType dataType; try { dataType = FxDataType.getById((Long) propXP[2]); } catch (FxNotFoundException e) { throw e.asRuntimeException(); } long id = Long.parseLong(data.get("id")); int ver = Integer.parseInt(data.get("ver")); long lang = Integer.parseInt(data.get("lang")); boolean isMaxVer = "1".equals(data.get("ismax_ver")); boolean isLiveVer = "1".equals(data.get("islive_ver")); boolean mlDef = "1".equals(data.get(column + "_mld")); PreparedStatement ps; int vdPos; switch (dataType) { case String1024: ps = psString; ps.setString(10, data.get(column)); ps.setString(11, data.get(column).toUpperCase()); vdPos = 12; break; case Text: case HTML: ps = psText; ps.setString(10, data.get(column)); ps.setString(11, data.get(column).toUpperCase()); vdPos = 12; break; case Number: ps = psNumber; ps.setLong(10, Long.valueOf(data.get(column))); vdPos = 11; break; case LargeNumber: ps = psLargeNumber; ps.setLong(10, Long.valueOf(data.get(column))); vdPos = 11; break; case Reference: ps = psReference; ps.setLong(10, Long.valueOf(data.get(column))); vdPos = 11; break; case Float: ps = psFloat; ps.setFloat(10, Float.valueOf(data.get(column))); vdPos = 11; break; case Double: ps = psDouble; ps.setDouble(10, Double.valueOf(data.get(column))); vdPos = 11; break; case Boolean: ps = psBoolean; ps.setBoolean(10, "1".equals(data.get(column))); vdPos = 11; break; case SelectOne: ps = psSelectOne; ps.setLong(10, Long.valueOf(data.get(column))); vdPos = 11; break; default: //noinspection ThrowableInstanceNeverThrown throw new FxInvalidParameterException("assignment", "ex.structure.flatstorage.datatype.unsupported", dataType.name()) .asRuntimeException(); } ps.setLong(1, id); ps.setInt(2, ver); ps.setInt(3, pos); ps.setLong(4, lang); ps.setLong(5, prop); ps.setLong(6, assignment); ps.setBoolean(7, isMaxVer); ps.setBoolean(8, isLiveVer); ps.setBoolean(9, mlDef); if (valueData == null) ps.setNull(vdPos, java.sql.Types.NUMERIC); else ps.setInt(vdPos, valueData); ps.executeUpdate(); insertCount++; } /** * Get property id, xpath and data type for an assignment * * @param assignment assignment id * @return Object[] {propertyId, xpath, datatype} */ private Object[] getPropertyXPathDataType(long assignment) { if (assignmentPropAlias.get(assignment) != null) return assignmentPropAlias.get(assignment); try { psGetAssInfo.setLong(1, assignment); ResultSet rs = psGetAssInfo.executeQuery(); if (rs != null && rs.next()) { Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) }; assignmentPropAlias.put(assignment, data); return data; } } catch (SQLException e) { throw new IllegalArgumentException( "Could not load data for assignment " + assignment + ": " + e.getMessage()); } throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!"); } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (inElement) sbData.append(ch, start, length); } }; parser.parse(zip.getInputStream(zeData), handler); } finally { Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble, psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText); } }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import data from a zip archive to a database table * * @param stmt statement to use * @param zip zip archive containing the zip entry * @param ze zip entry within the archive * @param xpath xpath containing the entries to import * @param table name of the table * @param executeInsertPhase execute the insert phase? * @param executeUpdatePhase execute the update phase? * @param updateColumns columns that should be set to <code>null</code> in a first pass (insert) * and updated to the provided values in a second pass (update), * columns that should be used in the where clause have to be prefixed * with "KEY:", to assign a default value use the expression "columnname:default value", * if the default value is "@", it will be a negative counter starting at 0, decreasing. * If the default value starts with "%", it will be set to the column following the "%" * character in the first pass * @throws Exception on errors/* w w w.j a v a2s . c om*/ */ protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath, final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase, final String... updateColumns) throws Exception { //analyze the table final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2"); StringBuilder sbInsert = new StringBuilder(500); StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null; if (rs == null) throw new IllegalArgumentException("Can not analyze table [" + table + "]!"); sbInsert.append("INSERT INTO ").append(table).append(" ("); final ResultSetMetaData md = rs.getMetaData(); final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0 ? new HashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0 ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; //preset to a referenced column (%column syntax) final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null; final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>( md.getColumnCount() + (counters != null ? counters.size() : 0)); int insertIndex = 1; int updateSetIndex = 1; int updateClauseIndex = 1; boolean first = true; for (int i = 0; i < md.getColumnCount(); i++) { final String currCol = md.getColumnName(i + 1).toLowerCase(); if (updateColumns.length > 0) { boolean abort = false; for (String col : updateColumns) { if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) { String value = col.substring(col.indexOf(':') + 1); col = col.substring(0, col.indexOf(':')); if ("@".equals(value)) { if (currCol.equalsIgnoreCase(col)) { counters.put(col, 0); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); } } else if (value.startsWith("%")) { if (currCol.equalsIgnoreCase(col)) { presetRefColumns.put(col, value.substring(1)); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); // System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1)); } } else if (!presetColumns.containsKey(col)) presetColumns.put(col, value); } if (currCol.equalsIgnoreCase(col)) { abort = true; updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++)); break; } } if (abort) continue; } if (first) { first = false; } else sbInsert.append(','); sbInsert.append(currCol); insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); } if (updateColumns.length > 0 && executeUpdatePhase) { sbUpdate.append("UPDATE ").append(table).append(" SET "); int counter = 0; for (String updateColumn : updateSetColumns.keySet()) { if (counter++ > 0) sbUpdate.append(','); sbUpdate.append(updateColumn).append("=?"); } sbUpdate.append(" WHERE "); boolean hasKeyColumn = false; for (String col : updateColumns) { if (!col.startsWith("KEY:")) continue; hasKeyColumn = true; String keyCol = col.substring(4); for (int i = 0; i < md.getColumnCount(); i++) { if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol)) continue; updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++)); sbUpdate.append(keyCol).append("=? AND "); break; } } if (!hasKeyColumn) throw new IllegalArgumentException("Update columns require a KEY!"); sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND " //"shift" clause indices for (String col : updateClauseColumns.keySet()) { GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col); ci.index += (updateSetIndex - 1); } } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(key); } sbInsert.append(")VALUES("); for (int i = 0; i < insertColumns.size(); i++) { if (i > 0) sbInsert.append(','); sbInsert.append('?'); } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(presetColumns.get(key)); } sbInsert.append(')'); if (DBG) { LOG.info("Insert statement:\n" + sbInsert.toString()); if (updateColumns.length > 0) LOG.info("Update statement:\n" + sbUpdate.toString()); } //build a map containing all nodes that require attributes //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data" final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5); for (String pElem : xpath.split("/")) { if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0)) continue; List<String> att = new ArrayList<String>(5); for (String pAtt : pElem.split("@")) { if (!(pAtt.indexOf('=') > 0)) continue; att.add(pAtt.substring(0, pAtt.indexOf('='))); } queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att); } final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString()); final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase ? stmt.getConnection().prepareStatement(sbUpdate.toString()) : null; try { final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final DefaultHandler handler = new DefaultHandler() { private String currentElement = null; private Map<String, String> data = new HashMap<String, String>(10); private StringBuilder sbData = new StringBuilder(10000); boolean inTag = false; boolean inElement = false; int counter; List<String> path = new ArrayList<String>(10); StringBuilder currPath = new StringBuilder(100); boolean insertMode = true; /** * {@inheritDoc} */ @Override public void startDocument() throws SAXException { counter = 0; inTag = false; inElement = false; path.clear(); currPath.setLength(0); sbData.setLength(0); data.clear(); currentElement = null; } /** * {@inheritDoc} */ @Override public void processingInstruction(String target, String data) throws SAXException { if (target != null && target.startsWith("fx_")) { if (target.equals("fx_mode")) insertMode = "insert".equals(data); } else super.processingInstruction(target, data); } /** * {@inheritDoc} */ @Override public void endDocument() throws SAXException { if (insertMode) LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath + "]"); else LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]"); } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { pushPath(qName, attributes); if (currPath.toString().equals(xpath)) { inTag = true; data.clear(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if (StringUtils.isEmpty(name)) name = attributes.getQName(i); data.put(name, attributes.getValue(i)); } } else { currentElement = qName; } inElement = true; sbData.setLength(0); } /** * Push a path element from the stack * * @param qName element name to push * @param att attributes */ private void pushPath(String qName, Attributes att) { if (att.getLength() > 0 && queryAttributes.containsKey(qName)) { String curr = qName + "["; boolean first = true; final List<String> attList = queryAttributes.get(qName); for (int i = 0; i < att.getLength(); i++) { if (!attList.contains(att.getQName(i))) continue; if (first) first = false; else curr += ','; curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'"; } curr += ']'; path.add(curr); } else path.add(qName); buildPath(); } /** * Pop the top path element from the stack */ private void popPath() { path.remove(path.size() - 1); buildPath(); } /** * Rebuild the current path */ private synchronized void buildPath() { currPath.setLength(0); for (String s : path) currPath.append(s).append('/'); if (currPath.length() > 1) currPath.delete(currPath.length() - 1, currPath.length()); // System.out.println("currPath: " + currPath); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (currPath.toString().equals(xpath)) { if (DBG) LOG.info("Insert [" + xpath + "]: [" + data + "]"); inTag = false; try { if (insertMode) { if (executeInsertPhase) { processColumnSet(insertColumns, psInsert); counter += psInsert.executeUpdate(); } } else { if (executeUpdatePhase) { if (processColumnSet(updateSetColumns, psUpdate)) { processColumnSet(updateClauseColumns, psUpdate); counter += psUpdate.executeUpdate(); } } } } catch (SQLException e) { throw new SAXException(e); } catch (ParseException e) { throw new SAXException(e); } } else { if (inTag) { data.put(currentElement, sbData.toString()); } currentElement = null; } popPath(); inElement = false; sbData.setLength(0); } /** * Process a column set * * @param columns the columns to process * @param ps prepared statement to use * @return if data other than <code>null</code> has been set * @throws SQLException on errors * @throws ParseException on date/time conversion errors */ private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps) throws SQLException, ParseException { boolean dataSet = false; for (String col : columns.keySet()) { ColumnInfo ci = columns.get(col); String value = data.get(col); if (insertMode && counters != null && counters.get(col) != null) { final int newVal = counters.get(col) - 1; value = String.valueOf(newVal); counters.put(col, newVal); // System.out.println("new value for " + col + ": " + newVal); } if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) { value = data.get(presetRefColumns.get(col)); // System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]"); } if (value == null) ps.setNull(ci.index, ci.columnType); else { dataSet = true; switch (ci.columnType) { case Types.BIGINT: case Types.NUMERIC: if (DBG) LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value)); ps.setBigDecimal(ci.index, new BigDecimal(value)); break; case java.sql.Types.DOUBLE: if (DBG) LOG.info("Double " + ci.index + "->" + Double.parseDouble(value)); ps.setDouble(ci.index, Double.parseDouble(value)); break; case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (DBG) LOG.info("Float " + ci.index + "->" + Float.parseFloat(value)); ps.setFloat(ci.index, Float.parseFloat(value)); break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (DBG) LOG.info("Timestamp/Date " + ci.index + "->" + FxFormatUtils.getDateTimeFormat().parse(value)); ps.setTimestamp(ci.index, new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime())); break; case Types.TINYINT: case Types.SMALLINT: if (DBG) LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value)); ps.setInt(ci.index, Integer.valueOf(value)); break; case Types.INTEGER: case Types.DECIMAL: try { if (DBG) LOG.info("Long " + ci.index + "->" + Long.valueOf(value)); ps.setLong(ci.index, Long.valueOf(value)); } catch (NumberFormatException e) { //Fallback (temporary) for H2 if the reported long is a big decimal (tree...) ps.setBigDecimal(ci.index, new BigDecimal(value)); } break; case Types.BIT: case Types.CHAR: case Types.BOOLEAN: if (DBG) LOG.info("Boolean " + ci.index + "->" + value); if ("1".equals(value) || "true".equals(value)) ps.setBoolean(ci.index, true); else ps.setBoolean(ci.index, false); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BLOB: case Types.BINARY: ZipEntry bin = zip.getEntry(value); if (bin == null) { LOG.error("Failed to lookup binary [" + value + "]!"); ps.setNull(ci.index, ci.columnType); break; } try { ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize()); } catch (IOException e) { LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e); } break; case Types.CLOB: case Types.LONGVARCHAR: case Types.VARCHAR: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: if (DBG) LOG.info("String " + ci.index + "->" + value); ps.setString(ci.index, value); break; default: LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]"); } } } return dataSet; } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (inElement) sbData.append(ch, start, length); } }; handler.processingInstruction("fx_mode", "insert"); parser.parse(zip.getInputStream(ze), handler); if (updateColumns.length > 0 && executeUpdatePhase) { handler.processingInstruction("fx_mode", "update"); parser.parse(zip.getInputStream(ze), handler); } } finally { Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <stream>} element. * * @param attrs//w w w . j ava2s . c om * List of element attributes * * @throws SAXException * if error occurs parsing element */ private void processStream(Attributes attrs) throws SAXException { if (currStream != null) { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.malformed.configuration", STREAM_ELMT), currParseLocation); } String name = null; String className = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { name = attValue; } else if (CLASS_ATTR.equals(attName)) { className = attValue; } } notEmpty(name, STREAM_ELMT, NAME_ATTR); notEmpty(className, STREAM_ELMT, CLASS_ATTR); if (streamsConfigData.getStream(name) != null) { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.duplicate", STREAM_ELMT, name), currParseLocation); } try { Object newStream = Utils.createInstance(className); if (!(newStream instanceof TNTInputStream)) { throw new SAXNotSupportedException(StreamsResources.getStringFormatted( StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.not.extend.class", STREAM_ELMT, CLASS_ATTR, className, TNTInputStream.class.getName(), getLocationInfo())); } currStream = (TNTInputStream<?, ?>) newStream; } catch (Exception exc) { throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.failed.to.load", STREAM_ELMT, CLASS_ATTR, className, getLocationInfo()), exc); } currStream.setName(name); streamsConfigData.addStream(currStream); currStream.ensureOutputSet(); }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <parser>} element. * * @param attrs/* w w w .ja v a 2 s.c o m*/ * List of element attributes * * @throws SAXException * if error occurs parsing element */ private void processParser(Attributes attrs) throws SAXException { if (currParser != null) { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.malformed.configuration", PARSER_ELMT), currParseLocation); } String name = null; String className = null; String tags = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { name = attValue; } else if (CLASS_ATTR.equals(attName)) { className = attValue; } else if (TAGS_ATTR.equals(attName)) { tags = attValue; } } notEmpty(name, PARSER_ELMT, NAME_ATTR); notEmpty(className, PARSER_ELMT, CLASS_ATTR); if (streamsConfigData.getParser(name) != null) { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.duplicate.parser.definition", name), currParseLocation); } try { Object newParser = Utils.createInstance(className); if (!(newParser instanceof ActivityParser)) { throw new SAXNotSupportedException(StreamsResources.getStringFormatted( StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.not.implement.interface", PARSER_ELMT, CLASS_ATTR, className, ActivityParser.class.getName(), getLocationInfo())); } currParser = (ActivityParser) newParser; } catch (Exception exc) { throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.failed.to.load", PARSER_ELMT, CLASS_ATTR, className, getLocationInfo()), exc); } if (currParser != null) { currParser.setName(name); currParser.setTags(tags); streamsConfigData.addParser(currParser); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <param>} element. * * @param attrs/*w ww . java 2 s .co m*/ * List of element attributes * * @throws SAXException * if error occurs parsing element */ private void processParam(Attributes attrs) throws SAXException { if (javaObjectData == null) { throw new SAXParseException( StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.malformed.configuration2", PARAM_ELMT, JAVA_OBJ_ELMT), currParseLocation); } String name = null; String value = null; String type = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { name = attValue; } else if (VALUE_ATTR.equals(attName)) { value = attValue; } else if (TYPE_ATTR.equals(attName)) { type = attValue; } } notEmpty(name, PARAM_ELMT, NAME_ATTR); notEmpty(type, PARAM_ELMT, TYPE_ATTR); try { Object obj; if (StringUtils.isEmpty(value)) { obj = Utils.createInstance(type); } else { obj = javaObjectsMap.get(value); if (obj == null) { obj = Utils.createInstance(type, new Object[] { value }, String.class); } } javaObjectData.addArg(obj); javaObjectData.addType(type); } catch (Exception exc) { throw new SAXParseException( StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.could.not.init.obj.param", javaObjectData.name, name), currParseLocation, exc); } }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java
/** * Processes a {@code <parser-ref>} element. * * @param attrs/* w w w . j av a 2s .c o m*/ * List of element attributes * * @throws SAXException * if error occurs element */ private void processParserRef(Attributes attrs) throws SAXException { if (currField == null && currStream == null) { throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.malformed.configuration4", PARSER_REF_ELMT, FIELD_ELMT, EMBEDDED_ACTIVITY_ELMT, STREAM_ELMT), currParseLocation); } String parserName = null; String aggregationType = null; for (int i = 0; i < attrs.getLength(); i++) { String attName = attrs.getQName(i); String attValue = attrs.getValue(i); if (NAME_ATTR.equals(attName)) { parserName = attValue; } else if (AGGREGATION_ATTR.equals(attName)) { aggregationType = attValue; } } notEmpty(parserName, PARSER_REF_ELMT, NAME_ATTR); ActivityParser parser = streamsConfigData.getParser(parserName); if (parser == null) { throw new SAXParseException( StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.undefined.reference", PARSER_REF_ELMT, parserName), currParseLocation); } if (currField != null) { currField.addStackedParser(parser, aggregationType); } else { try { currStream.addReference(parser); } catch (IllegalStateException exc) { throw new SAXParseException(StreamsResources.getStringFormatted( StreamsResources.RESOURCE_BUNDLE_NAME, "ConfigParserHandler.could.not.add.stream.parser", currStream.getName(), parserName), currParseLocation, exc); } } }