List of usage examples for java.sql PreparedStatement setFloat
void setFloat(int parameterIndex, float x) throws SQLException;
float
value. From source file:org.apache.phoenix.end2end.DateTimeIT.java
private String initAtable() throws SQLException { String tableName = generateUniqueName(); ensureTableCreated(getUrl(), tableName, ATABLE_NAME, (byte[][]) null, null); PreparedStatement stmt = conn.prepareStatement("upsert into " + tableName + "(" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_STRING, " + " B_STRING, " + " A_INTEGER, " + " A_DATE, " + " X_DECIMAL, " + " X_LONG, " + " X_INTEGER," + " Y_INTEGER," + " A_BYTE," + " A_SHORT," + " A_FLOAT," + " A_DOUBLE," + " A_UNSIGNED_FLOAT," + " A_UNSIGNED_DOUBLE)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, tenantId);/*from w w w. j a v a 2 s .c om*/ stmt.setString(2, ROW1); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 1); stmt.setDate(6, date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 1); stmt.setShort(12, (short) 128); stmt.setFloat(13, 0.01f); stmt.setDouble(14, 0.0001); stmt.setFloat(15, 0.01f); stmt.setDouble(16, 0.0001); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW2); stmt.setString(3, A_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 2); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 2); stmt.setShort(12, (short) 129); stmt.setFloat(13, 0.02f); stmt.setDouble(14, 0.0002); stmt.setFloat(15, 0.02f); stmt.setDouble(16, 0.0002); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW3); stmt.setString(3, A_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 3); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 3); stmt.setShort(12, (short) 130); stmt.setFloat(13, 0.03f); stmt.setDouble(14, 0.0003); stmt.setFloat(15, 0.03f); stmt.setDouble(16, 0.0003); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW4); stmt.setString(3, A_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 4); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 4); stmt.setShort(12, (short) 131); stmt.setFloat(13, 0.04f); stmt.setDouble(14, 0.0004); stmt.setFloat(15, 0.04f); stmt.setDouble(16, 0.0004); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW5); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 5); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 5); stmt.setShort(12, (short) 132); stmt.setFloat(13, 0.05f); stmt.setDouble(14, 0.0005); stmt.setFloat(15, 0.05f); stmt.setDouble(16, 0.0005); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW6); stmt.setString(3, B_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 6); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, null); stmt.setNull(8, Types.BIGINT); stmt.setNull(9, Types.INTEGER); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 6); stmt.setShort(12, (short) 133); stmt.setFloat(13, 0.06f); stmt.setDouble(14, 0.0006); stmt.setFloat(15, 0.06f); stmt.setDouble(16, 0.0006); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW7); stmt.setString(3, B_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 7); stmt.setDate(6, date == null ? null : date); stmt.setBigDecimal(7, BigDecimal.valueOf(0.1)); stmt.setLong(8, 5L); stmt.setInt(9, 5); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 7); stmt.setShort(12, (short) 134); stmt.setFloat(13, 0.07f); stmt.setDouble(14, 0.0007); stmt.setFloat(15, 0.07f); stmt.setDouble(16, 0.0007); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW8); stmt.setString(3, B_VALUE); stmt.setString(4, C_VALUE); stmt.setInt(5, 8); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.9)); long l = Integer.MIN_VALUE - 1L; assert (l < Integer.MIN_VALUE); stmt.setLong(8, l); stmt.setInt(9, 4); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 8); stmt.setShort(12, (short) 135); stmt.setFloat(13, 0.08f); stmt.setDouble(14, 0.0008); stmt.setFloat(15, 0.08f); stmt.setDouble(16, 0.0008); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW9); stmt.setString(3, C_VALUE); stmt.setString(4, E_VALUE); stmt.setInt(5, 9); stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2)); stmt.setBigDecimal(7, BigDecimal.valueOf(3.3)); l = Integer.MAX_VALUE + 1L; assert (l > Integer.MAX_VALUE); stmt.setLong(8, l); stmt.setInt(9, 3); stmt.setInt(10, 300); stmt.setByte(11, (byte) 9); stmt.setShort(12, (short) 0); stmt.setFloat(13, 0.09f); stmt.setDouble(14, 0.0009); stmt.setFloat(15, 0.09f); stmt.setDouble(16, 0.0009); stmt.execute(); stmt.setString(1, tenantId); stmt.setString(2, ROW10); stmt.setString(3, B_VALUE); stmt.setString(4, B_VALUE); stmt.setInt(5, 7); // Intentionally null stmt.setDate(6, null); stmt.setBigDecimal(7, BigDecimal.valueOf(0.1)); stmt.setLong(8, 5L); stmt.setInt(9, 5); stmt.setNull(10, Types.INTEGER); stmt.setByte(11, (byte) 7); stmt.setShort(12, (short) 134); stmt.setFloat(13, 0.07f); stmt.setDouble(14, 0.0007); stmt.setFloat(15, 0.07f); stmt.setDouble(16, 0.0007); stmt.execute(); conn.commit(); return tableName; }
From source file:gsn.storage.StorageManager.java
public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement, Connection connection) throws SQLException { PreparedStatement ps = null; String query = getStatementInsert(tableName, fields).toString(); try {/*from w ww.j a v a2 s.co m*/ ps = connection.prepareStatement(query); int counter = 1; for (DataField dataField : fields) { if (dataField.getName().equalsIgnoreCase("timed")) continue; Serializable value = streamElement.getData(dataField.getName()); switch (dataField.getDataTypeID()) { case DataTypes.VARCHAR: if (value == null) ps.setNull(counter, Types.VARCHAR); else ps.setString(counter, value.toString()); break; case DataTypes.CHAR: if (value == null) ps.setNull(counter, Types.CHAR); else ps.setString(counter, value.toString()); break; case DataTypes.INTEGER: if (value == null) ps.setNull(counter, Types.INTEGER); else ps.setInt(counter, ((Number) value).intValue()); break; case DataTypes.SMALLINT: if (value == null) ps.setNull(counter, Types.SMALLINT); else ps.setShort(counter, ((Number) value).shortValue()); break; case DataTypes.TINYINT: if (value == null) ps.setNull(counter, Types.TINYINT); else ps.setByte(counter, ((Number) value).byteValue()); break; case DataTypes.DOUBLE: if (value == null) ps.setNull(counter, Types.DOUBLE); else ps.setDouble(counter, ((Number) value).doubleValue()); break; case DataTypes.FLOAT: if (value == null) ps.setNull(counter, Types.FLOAT); else ps.setFloat(counter, ((Number) value).floatValue()); break; case DataTypes.BIGINT: if (value == null) ps.setNull(counter, Types.BIGINT); else ps.setLong(counter, ((Number) value).longValue()); break; case DataTypes.BINARY: if (value == null) ps.setNull(counter, Types.BINARY); else ps.setBytes(counter, (byte[]) value); break; default: logger.error("The type conversion is not supported for : " + dataField.getName() + "(" + dataField.getDataTypeID() + ") : "); } counter++; } ps.setLong(counter, streamElement.getTimeStamp()); ps.execute(); } catch (GSNRuntimeException e) { //if (e.getType() == GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) { // if (logger.isDebugEnabled()) // logger.debug("An stream element dropped due to unexpected virtual sensor removal. (Stream element: " + streamElement.toString() + ")+ Query: " + query, e); //} else logger.warn("Inserting a stream element failed : " + streamElement.toString(), e); } catch (SQLException e) { if (e.getMessage().toLowerCase().contains("duplicate entry")) logger.info("Error occurred on inserting data to the database, an stream element dropped due to: " + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query); else logger.warn("Error occurred on inserting data to the database, an stream element dropped due to: " + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query); throw e; } finally { close(ps); } }
From source file:piramide.interaction.reasoner.db.deploy.DatabaseMigrator.java
/** * Given the Downloaded table, we populate the Devices and Trends tables. *///w w w . j a v a 2s .c o m public void populateTables() { int invalidData = 0; try { final Connection con = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD); final Statement stmtClearTrends = con.createStatement(); stmtClearTrends.execute("DELETE FROM Trends"); stmtClearTrends.close(); final Statement stmtClearDevices = con.createStatement(); stmtClearDevices.execute("DELETE FROM Devices"); stmtClearDevices.close(); con.setAutoCommit(false); final Statement stmtDownloaded = con.createStatement(); final ResultSet rsDownloaded = stmtDownloaded .executeQuery("SELECT device_name, wurfl_id, marketing_name, brand_name, model_name, " + "real_height, real_width, reso_height, " + "reso_width, value, region FROM Downloaded"); final List<String> deviceNames = new Vector<String>(); final PreparedStatement stmtDevices = con.prepareStatement( "" + "INSERT INTO Devices(device_name, wurfl_id, marketing_name, brand_name, model_name, " + "real_height, real_width, real_size, reso_height, reso_width, reso_size) " + "Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); final PreparedStatement stmtTrends = con.prepareStatement( "" + "INSERT INTO Trends( device_name, region, month, year, value, error_margin ) " + "Values(?, ?, ?, ?, ?, ? )"); final Map<String, Integer> month2month = new HashMap<String, Integer>(); month2month.put("Jan", Integer.valueOf(1)); month2month.put("Feb", Integer.valueOf(2)); month2month.put("Mar", Integer.valueOf(3)); month2month.put("Apr", Integer.valueOf(4)); month2month.put("May", Integer.valueOf(5)); month2month.put("Jun", Integer.valueOf(6)); month2month.put("Jul", Integer.valueOf(7)); month2month.put("Aug", Integer.valueOf(8)); month2month.put("Sep", Integer.valueOf(9)); month2month.put("Oct", Integer.valueOf(10)); month2month.put("Nov", Integer.valueOf(11)); month2month.put("Dec", Integer.valueOf(12)); int counter = 0; final Set<String> badOnes = new HashSet<String>(); while (rsDownloaded.next()) { ++counter; if (counter % 100 == 0) { System.out.println("committed... " + counter); con.commit(); } final String deviceName = rsDownloaded.getString("device_name"); if (deviceName.equals("htc x7500") || deviceName.equals("samsung sgh-m300") || deviceName.equals("nokia verizon") || deviceName.equals("kddi a1407pt") || deviceName.equals("nokia thr880i") || deviceName.equals("softbank softbank 910t") || deviceName.equals("nokia 8860") || deviceName.equals("sony ericsson w580i") || deviceName.equals("motorola c139") || deviceName.equals("samsung stripe") || deviceName.equals("samsung sgh-c414") || deviceName.equals("samsung gt-e2121l") || deviceName.equals("samsung sgh-z400") || deviceName.equals("i-mobile 606") || deviceName.equals("softbank v302sh") || deviceName.equals("motorola krzr k1c")) continue; if (!deviceNames.contains(deviceName)) { stmtDevices.setString(1, deviceName); stmtDevices.setString(2, rsDownloaded.getString("wurfl_id")); stmtDevices.setString(3, rsDownloaded.getString("marketing_name")); stmtDevices.setString(4, rsDownloaded.getString("brand_name")); stmtDevices.setString(5, rsDownloaded.getString("model_name")); stmtDevices.setFloat(6, rsDownloaded.getFloat("real_height")); stmtDevices.setFloat(7, rsDownloaded.getFloat("real_width")); stmtDevices.setFloat(8, rsDownloaded.getFloat("real_height") * rsDownloaded.getFloat("real_width")); stmtDevices.setInt(9, rsDownloaded.getInt("reso_height")); stmtDevices.setInt(10, rsDownloaded.getInt("reso_width")); stmtDevices.setInt(11, rsDownloaded.getInt("reso_height") * rsDownloaded.getInt("reso_width")); stmtDevices.execute(); deviceNames.add(deviceName); } final String base64csv = rsDownloaded.getString("value"); final CsvReader csvReader2 = buildCSVReader(base64csv); if (!csvReader2.readRecord() && base64csv.length() != 924) { final byte[] binaryCSV = new Base64().decode(base64csv); final String stringCSV = new String(binaryCSV, "utf-8"); if (stringCSV.contains("could not be interpreted")) { badOnes.add(rsDownloaded.getString("region") + "@" + deviceName); } } final CsvReader csvReader = buildCSVReader(base64csv); int previousMonth = 0; int previousYear = 0; float currentValue = 0.0f; String currentErrorMargin = ""; boolean executed = false; while (csvReader.readRecord()) { executed = true; final String week = csvReader.get(0); final float value = Float.parseFloat(csvReader.get(1)); final String errorMargin = csvReader.get(2); final String[] weekParts = week.split(" "); final Integer monthString = month2month.get(weekParts[0]); if (monthString == null) { System.err.println("Failed to load device: " + deviceName); continue; } final int month = monthString.intValue(); final int year = Integer.parseInt(weekParts[2]); if (month == previousMonth && year == previousYear) { currentValue += value; currentErrorMargin = currentErrorMargin + "; " + errorMargin; continue; } final String region = rsDownloaded.getString("region"); //System.out.println(deviceName + " " + region + " " + month + " " + year); stmtTrends.setString(1, deviceName); stmtTrends.setString(2, region); stmtTrends.setInt(3, previousMonth); stmtTrends.setInt(4, previousYear); stmtTrends.setFloat(5, currentValue); stmtTrends.setString(6, currentErrorMargin); stmtTrends.execute(); currentValue = value; currentErrorMargin = errorMargin; previousMonth = month; previousYear = year; } if (!executed) { invalidData++; badOnes.add(rsDownloaded.getString("region") + "@" + deviceName); } } con.commit(); stmtDevices.close(); stmtTrends.close(); stmtDownloaded.close(); System.out.println("Counter: " + counter); System.out.println("Invalid data: " + invalidData); if (invalidData > 0) { final StringBuilder builder = new StringBuilder(); for (String badOne : badOnes) { builder.append(badOne); builder.append("\n"); } FileUtils.writeStringToFile(new File(INVALID_FILE_PATH), builder.toString()); System.err.println("Warning: data of " + invalidData + " mobile devices is wrong. Check which devices at " + INVALID_FILE_PATH); } } catch (Exception e) { e.printStackTrace(); } }
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 om */ 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:org.siphon.jssql.SqlExecutor.java
void setArg(PreparedStatement ps, int index, Object arg) throws SQLException, SqlExecutorException, UnsupportedDataTypeException, NoSuchMethodException, ScriptException { boolean output = false; int outputParameterType = 0; CallableStatement cs = null;// w w w .j a v a2 s .co m if (ps instanceof CallableStatement) { cs = (CallableStatement) ps; if (arg instanceof ScriptObjectMirror && ((ScriptObjectMirror) arg).containsKey("OUT")) { ScriptObjectMirror jsarg = ((ScriptObjectMirror) arg); outputParameterType = (int) jsarg.get("JDBC_TYPE"); arg = jsarg.get("VALUE"); output = true; } } if (output) { cs.registerOutParameter(index + 1, outputParameterType); if (JsTypeUtil.isNull(arg) || (arg instanceof Double && Double.isNaN((Double) arg))) { return; } } if (JsTypeUtil.isNull(arg)) { ps.setObject(index + 1, null); } else if (arg instanceof CharSequence) { ps.setString(index + 1, arg.toString()); } else if (arg instanceof NativeString) { ps.setString(index + 1, arg.toString()); } else if (arg instanceof Double) { // js number always be // Doublebut if its came from // JSON.parse since JSON is jdk // given global object, it will // make Integer and ... double d = ((Double) arg).doubleValue(); if (d == (int) d) { ps.setInt(index + 1, (int) d); } else if (d == (long) d) { ps.setLong(index + 1, (long) d); } else { ps.setBigDecimal(index + 1, new BigDecimal(d)); } } else if (arg instanceof Integer) { ps.setInt(index + 1, (Integer) arg); } else if (arg instanceof Long) { ps.setLong(index + 1, (Long) arg); } else if (arg instanceof Float) { ps.setFloat(index + 1, (Float) arg); } else if (jsTypeUtil.isNativeDate(arg)) { ps.setTimestamp(index + 1, parseDate(arg)); } else if (arg instanceof ZonedDateTime) { ZonedDateTime zdt = (ZonedDateTime) arg; ps.setTimestamp(index + 1, new Timestamp(zdt.toInstant().toEpochMilli())); } else if (arg instanceof Boolean) { ps.setBoolean(index + 1, JsTypeUtil.isTrue(arg)); } else if (arg instanceof ScriptObjectMirror || arg instanceof ScriptObject) { String attr = null; Object value = null; if (arg instanceof ScriptObjectMirror) { ScriptObjectMirror atm = (ScriptObjectMirror) arg; if (atm.keySet().contains("toJavaObject")) { Object obj = atm.callMember("toJavaObject"); setArg(ps, index, obj); return; } attr = atm.keySet().iterator().next(); value = atm.get(attr); } else { ScriptObject obj = (ScriptObject) arg; if (obj.containsKey("toJavaObject")) { ScriptObjectMirror atm = (ScriptObjectMirror) jsTypeUtil.toScriptObjectMirror(obj); Object result = atm.callMember("toJavaObject"); setArg(ps, index, result); return; } String[] arr = obj.getOwnKeys(false); if (arr.length == 0) { throw new SqlExecutorException("js argument " + arg + " (" + arg.getClass() + ") at " + index + " is an empty js object"); } attr = arr[0]; value = obj.get(attr); } if ("STRING".equals(attr)) { ps.setString(index + 1, String.valueOf(value)); } else if ("DECIMAL".equals(attr)) { if (value instanceof Double) { ps.setBigDecimal(index + 1, new BigDecimal((Double) value)); } else { ps.setBigDecimal(index + 1, new BigDecimal(value + "")); } } else if ("INT".equals(attr)) { if (value instanceof Double) { if (((Double) value).isNaN()) { ps.setObject(index + 1, null); } else { ps.setInt(index + 1, ((Double) value).intValue()); } } else { ps.setInt(index + 1, new Integer(value + "")); } } else if ("BOOLEAN".equals(attr)) { ps.setBoolean(index + 1, JsTypeUtil.isTrue(arg)); } else if ("DOUBLE".equals(attr)) { if (value instanceof Double) { if (((Double) value).isNaN()) { ps.setObject(index + 1, null); } else { ps.setDouble(index + 1, (double) value); } } else { ps.setDouble(index + 1, new Double(value + "")); } } else if ("FLOAT".equals(attr)) { if (value instanceof Double) { if (((Double) value).isNaN()) { ps.setObject(index + 1, null); } else { ps.setFloat(index + 1, (float) (double) value); } } else { ps.setFloat(index + 1, new Float(value + "")); } } else if ("DATE".equals(attr)) { ps.setTimestamp(index + 1, parseDate(value)); } else if ("TIME".equals(attr)) { ps.setTimestamp(index + 1, parseTime(value)); } else if ("BINARY".equals(attr)) { ps.setBytes(index + 1, parseBinary(value)); } else if ("CLOB".equals(attr)) { Clob clob = ps.getConnection().createClob(); clob.setString(1, String.valueOf(value)); ps.setClob(index + 1, clob); } else if ("LONG".equals(attr)) { if (value instanceof Double) { if (((Double) value).isNaN()) { ps.setObject(index + 1, null); } else { ps.setLong(index + 1, ((Double) value).longValue()); } } else { ps.setLong(index + 1, new Long(value + "")); } } else if ("OUTCURSOR".equals(attr)) { // cs.registerOutParameter(i+1, OracleTypes.CURSOR); cs.registerOutParameter(index + 1, -10); } else if ("ARRAY".equals(attr)) { if (value instanceof NativeArray) { ps.setArray(index + 1, createSqlArray(ps.getConnection(), (NativeArray) value)); } else { setArg(ps, index, value); // value is {ARRAY : ['int', e1, e2, ...]} } // ps.setObject(i+1, createSqlArray(ps.getConnection(), // (NativeArray) value)); } else if ("JSON".equals(attr) || "JSONB".equals(attr)) { PGobject obj = new PGobject(); obj.setType(attr.toLowerCase()); obj.setValue(this.JSON.tryStringify(value)); ps.setObject(index + 1, obj); } else if ("UUID".equals(attr)) { if (value != null) { ps.setObject(index + 1, UUID.fromString(value.toString())); } else { ps.setObject(index + 1, null); } } else { if (this.defaultJsonDbType != null) { PGobject obj = new PGobject(); obj.setType(this.defaultJsonDbType); obj.setValue(this.JSON.tryStringify(arg)); ps.setObject(index + 1, obj); } else { throw new SqlExecutorException("js argument " + arg + " (" + arg.getClass() + ") not support"); } } } else { throw new SqlExecutorException( "js argument " + arg + " (" + arg.getClass() + ") at " + index + " not support"); } }
From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java
private void updatePreparedStatement(String tablename, Hashtable<String, Object[]> fieldswithcontent, PreparedStatement ps) throws Exception { Enumeration en = fieldswithcontent.keys(); int i = 0;//ww w.ja v a2 s.c o m while (en.hasMoreElements()) { i++; try { String field = (String) en.nextElement(); Object[] o2 = fieldswithcontent.get(field); String type = (String) o2[0]; Object o = o2[1]; //System.out.println(field+" "+type+" "+o); if (type.equals("string")) { ps.setString(i, (String) o); } else if (type.equals("byte[]") || type.equals("base64Binary")) { ps.setBinaryStream(i, new ByteArrayInputStream((byte[]) o)); } else if (type.equals("dateTime")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; Date d = null; if (cal.toString().indexOf("0003-11-30") > -1) { ps.setString(i, "0000-00-00 00:00:00"); } else { d = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(cal.toString()); ps.setTimestamp(i, new java.sql.Timestamp(d.getTime())); } } else if (type.equals("date")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; Date d1 = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(cal.toString()); ps.setDate(i, java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(d1))); } else if (type.equals("time")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; String c = cal.toString(); c = c.replaceFirst("0003-11-30", "0000-00-00"); Date d1 = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(c); ps.setTime(i, new java.sql.Time(d1.getTime())); } else if (type.equals("integer")) { ps.setInt(i, ((BigInteger) o).intValue()); } else if (type.equals("double")) { ps.setDouble(i, (Double) o); } else if (type.equals("float")) { ps.setFloat(i, (Float) o); } else if (type.equals("long")) { ps.setLong(i, (Long) o); } else { throw new Exception("unknown type [" + type + "] for field [" + field + "] encountered while trying to update table [" + tablename + "]."); } } catch (Exception e) { e.printStackTrace(); throw e; } } }
From source file:ro.nextreports.engine.queryexec.QueryExecutor.java
private void setParameterValue(PreparedStatement pstmt, Class paramValueClass, Object paramValue, int index) throws SQLException, QueryException { // for "NOT IN (?)" setting null -> result is undeterminated // ParameterUtil.NULL was good only for list of strings (for NOT IN)! if (ParameterUtil.NULL.equals(paramValue)) { paramValue = null;/*from w w w . ja va 2s. co m*/ } if (paramValueClass.equals(Object.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.JAVA_OBJECT); } else { if (paramValue instanceof IdName) { pstmt.setObject(index + 1, ((IdName) paramValue).getId()); } else { pstmt.setObject(index + 1, paramValue); } } } else if (paramValueClass.equals(Boolean.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.BIT); } else { if (paramValue instanceof IdName) { pstmt.setBoolean(index + 1, (Boolean) ((IdName) paramValue).getId()); } else { pstmt.setBoolean(index + 1, (Boolean) paramValue); } } } else if (paramValueClass.equals(Byte.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.TINYINT); } else { if (paramValue instanceof IdName) { pstmt.setByte(index + 1, (Byte) ((IdName) paramValue).getId()); } else { pstmt.setByte(index + 1, (Byte) paramValue); } } } else if (paramValueClass.equals(Double.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.DOUBLE); } else { if (paramValue instanceof IdName) { pstmt.setDouble(index + 1, (Double) ((IdName) paramValue).getId()); } else { pstmt.setDouble(index + 1, (Double) paramValue); } } } else if (paramValueClass.equals(Float.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.FLOAT); } else { if (paramValue instanceof IdName) { pstmt.setFloat(index + 1, (Float) ((IdName) paramValue).getId()); } else { pstmt.setFloat(index + 1, (Float) paramValue); } } } else if (paramValueClass.equals(Integer.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.INTEGER); } else { if (paramValue instanceof IdName) { pstmt.setObject(index + 1, ((IdName) paramValue).getId()); } else { pstmt.setInt(index + 1, (Integer) paramValue); } } } else if (paramValueClass.equals(Long.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.BIGINT); } else { if (paramValue instanceof IdName) { pstmt.setLong(index + 1, (Long) ((IdName) paramValue).getId()); } else { pstmt.setLong(index + 1, (Long) paramValue); } } } else if (paramValueClass.equals(Short.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.SMALLINT); } else { if (paramValue instanceof IdName) { pstmt.setShort(index + 1, (Short) ((IdName) paramValue).getId()); } else { pstmt.setShort(index + 1, (Short) paramValue); } } //@todo // ParameterUtil -> values are taken from dialect (where there is no BigDecimal yet!) // or from meta data } else if (paramValueClass.equals(BigDecimal.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.DECIMAL); } else { if (paramValue instanceof IdName) { Serializable ser = ((IdName) paramValue).getId(); if (ser instanceof BigDecimal) { pstmt.setBigDecimal(index + 1, (BigDecimal) (ser)); } else { pstmt.setInt(index + 1, (Integer) (ser)); } } else { // a simple value cannot be cast to BigDecimal! pstmt.setObject(index + 1, paramValue); } } } else if (paramValueClass.equals(BigInteger.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.BIGINT); } else { if (paramValue instanceof IdName) { Serializable ser = ((IdName) paramValue).getId(); if (ser instanceof BigInteger) { pstmt.setBigDecimal(index + 1, new BigDecimal((BigInteger) (ser))); } else if (ser instanceof BigDecimal) { pstmt.setBigDecimal(index + 1, (BigDecimal) (ser)); } else { pstmt.setInt(index + 1, (Integer) (ser)); } } else { // a simple value cannot be cast to BigDecimal! pstmt.setObject(index + 1, paramValue); } } } else if (paramValueClass.equals(String.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.VARCHAR); } else { if (paramValue instanceof IdName) { if (((IdName) paramValue).getId() == null) { pstmt.setNull(index + 1, Types.VARCHAR); } else { pstmt.setString(index + 1, ((IdName) paramValue).getId().toString()); } } else { pstmt.setString(index + 1, paramValue.toString()); } } } else if (paramValueClass.equals(Date.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.DATE); } else { if (paramValue instanceof IdName) { Serializable obj = ((IdName) paramValue).getId(); Date date; if (obj instanceof String) { try { date = IdNameRenderer.sdf.parse((String) obj); } catch (ParseException e) { e.printStackTrace(); LOG.error(e.getMessage(), e); date = new Date(); } } else { date = (Date) obj; } pstmt.setDate(index + 1, new java.sql.Date(date.getTime())); } else { pstmt.setDate(index + 1, new java.sql.Date(((Date) paramValue).getTime())); } } } else if (paramValueClass.equals(Timestamp.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.TIMESTAMP); } else { if (paramValue instanceof IdName) { Serializable obj = ((IdName) paramValue).getId(); Date date; if (obj instanceof String) { try { date = IdNameRenderer.sdf.parse((String) obj); } catch (ParseException e) { e.printStackTrace(); LOG.error(e.getMessage(), e); date = new Date(); } } else { date = (Date) obj; } pstmt.setTimestamp(index + 1, new Timestamp(date.getTime())); } else { pstmt.setTimestamp(index + 1, new Timestamp(((Date) paramValue).getTime())); } } } else if (paramValueClass.equals(Time.class)) { if (paramValue == null) { pstmt.setNull(index + 1, Types.TIME); } else { if (paramValue instanceof IdName) { Serializable obj = ((IdName) paramValue).getId(); Date date; if (obj instanceof String) { try { date = IdNameRenderer.sdf.parse((String) obj); } catch (ParseException e) { e.printStackTrace(); LOG.error(e.getMessage(), e); date = new Date(); } } else { date = (Date) obj; } pstmt.setTime(index + 1, new Time(date.getTime())); } else { pstmt.setTime(index + 1, new Time(((Date) paramValue).getTime())); } } } else { throw new QueryException("Parameter type " + paramValueClass.getName() + " not supported in query"); } // for logSql() statementParameters.put(index, paramValue); }
From source file:servlets.SearchServlet.java
/** * A function that assigns points to the result of a search based on its start time and end time, and if the result fulfills a requirement. * @param conn, An instance of Connection. * @param reqs, A HashMap containing requirements needed to be fulfilled for a degree. * @param schedule, A Schedule instance containing available and unavailable time slots for each day of the week. * @param searcher, An instance of Search. * @param isTimeBased, A boolean indicating what type of search (time focused or requirement focused search) so the proper point system can be used. *///ww w . j a v a 2 s .c o m protected void assignPts(Connection conn, HashMap<String, List<JSONObject>> reqs, Schedule schedule, Search searcher, boolean isTimeBased) { PreparedStatement preparedStatement; ResultSet resultSet; float value = 0; String queryA = "select * from " + searcher.tableName(); try { String days; preparedStatement = conn.prepareStatement(queryA); preparedStatement.execute(); resultSet = preparedStatement.executeQuery(); PreparedStatement update = conn.prepareStatement("UPDATE " + searcher.tableName() + " " + "SET points=? WHERE cdept=? AND cnbr=? AND sec=? AND starttime=? AND endtime=?"); while (resultSet.next()) { value = 0; update.setString(2, resultSet.getString("cdept")); update.setString(3, resultSet.getString("cnbr")); update.setString(4, resultSet.getString("sec")); update.setInt(5, resultSet.getInt("starttime")); update.setInt(6, resultSet.getInt("endtime")); days = resultSet.getString("days"); // skip if section has no times if (days != null) { for (int i = 0; i < schedule.getWeek().length; ++i) { if (days.contains(schedule.getWeek()[i])) { Day temp = schedule.getElementFromSchedule(i); value = closeTimeMatchAction(resultSet, update, temp, value, isTimeBased); } } value = addHalfAPt(conn, resultSet, schedule, searcher, value); } String cnbr = resultSet.getString("cnbr"); String cdept = resultSet.getString("cdept"); if (isTimeBased) { boolean hasMatch = false; List<JSONObject> courses = reqs.get(cdept); if (null != courses) { for (JSONObject obj : courses) { try { // check if cnum is null String cnum; if (JSONObject.NULL == obj.get("cnum")) { cnum = null; } else { cnum = Integer.toString(obj.getInt("cnum")); } String dept = obj.getString("dept"); if (null == cnum || cnbr.startsWith(cnum)) { hasMatch = true; break; } } catch (JSONException e) { e.printStackTrace(); } } // end for courses } // and if courses!=null if (!hasMatch && !reqs.isEmpty()) { value += 1; update.setFloat(1, value); update.execute(); } else { update.setFloat(1, value); update.execute(); } } else { update.setFloat(1, value); update.execute(); } // end if(isTimeBased) } // end while(rs.next()) } catch (SQLException e) { e.printStackTrace(); } }
From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java
private int fillPreparedStatementFromActivity(Identity owner, ExoSocialActivity activity, PreparedStatement preparedStatement, int index) throws SQLException { preparedStatement.setString(index++, activity.getTitle()); preparedStatement.setString(index++, activity.getTitleId()); preparedStatement.setString(index++, activity.getBody()); preparedStatement.setString(index++, activity.getBodyId()); preparedStatement.setLong(index++, activity.getPostedTime()); preparedStatement.setLong(index++, activity.getUpdated().getTime()); preparedStatement.setString(index++, activity.getPosterId()); preparedStatement.setString(index++, owner.getRemoteId()); preparedStatement.setString(index++, owner.getId()); preparedStatement.setString(index++, activity.getPermaLink()); preparedStatement.setString(index++, activity.getAppId()); preparedStatement.setString(index++, activity.getExternalId()); if (activity.getPriority() == null) { preparedStatement.setNull(index++, Types.FLOAT); } else {//from www.j a va 2 s .c om preparedStatement.setFloat(index++, activity.getPriority()); } preparedStatement.setBoolean(index++, activity.isHidden()); preparedStatement.setBoolean(index++, activity.isLocked()); preparedStatement.setString(index++, StringUtils.join(activity.getLikeIdentityIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getMentionedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getCommentedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getReplyToId(), ",")); preparedStatement.setString(index++, null); // if (activity.getTemplateParams() != null) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(b); output.writeObject(activity.getTemplateParams()); preparedStatement.setBinaryStream(index++, new ByteArrayInputStream(b.toByteArray())); } catch (IOException e) { LOG.debug("Failed to save templateParams of activity into database"); } } else { preparedStatement.setNull(index++, Types.BLOB); } preparedStatement.setString(index++, activity.getType()); return index; }
From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java
/** * Return a Prepared statement for the given Statement object, which is ready to be executed * * @param stmnt SQL stataement to be executed * @param con The connection to be used * @param msgCtx Current message context * @return a PreparedStatement//from ww w.j a v a 2 s.c o m * @throws SQLException on error */ protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException { SynapseLog synLog = getLog(msgCtx); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement()); } if (con == null) { String msg = "Connection from DataSource " + getDSName() + " is null."; log.error(msg); throw new SynapseException(msg); } if (dataSource instanceof BasicDataSource) { BasicDataSource basicDataSource = (BasicDataSource) dataSource; int numActive = basicDataSource.getNumActive(); int numIdle = basicDataSource.getNumIdle(); String connectionId = Integer.toHexString(con.hashCode()); DBPoolView dbPoolView = getDbPoolView(); if (dbPoolView != null) { dbPoolView.setNumActive(numActive); dbPoolView.setNumIdle(numIdle); dbPoolView.updateConnectionUsage(connectionId); } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("[ DB Connection : " + con + " ]"); synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]"); synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]"); synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]"); } } PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement()); // set parameters if any List<Statement.Parameter> params = stmnt.getParameters(); int column = 1; for (Statement.Parameter param : params) { if (param == null) { continue; } String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx)); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)"); } switch (param.getType()) { // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: { if (value != null && value.length() != 0) { ps.setString(column++, value); } else { ps.setString(column++, null); } break; } case Types.NUMERIC: case Types.DECIMAL: { if (value != null && value.length() != 0) { ps.setBigDecimal(column++, new BigDecimal(value)); } else { ps.setBigDecimal(column++, null); } break; } case Types.BIT: { if (value != null && value.length() != 0) { ps.setBoolean(column++, Boolean.parseBoolean(value)); } else { ps.setNull(column++, Types.BIT); } break; } case Types.TINYINT: { if (value != null && value.length() != 0) { ps.setByte(column++, Byte.parseByte(value)); } else { ps.setNull(column++, Types.TINYINT); } break; } case Types.SMALLINT: { if (value != null && value.length() != 0) { ps.setShort(column++, Short.parseShort(value)); } else { ps.setNull(column++, Types.SMALLINT); } break; } case Types.INTEGER: { if (value != null && value.length() != 0) { ps.setInt(column++, Integer.parseInt(value)); } else { ps.setNull(column++, Types.INTEGER); } break; } case Types.BIGINT: { if (value != null && value.length() != 0) { ps.setLong(column++, Long.parseLong(value)); } else { ps.setNull(column++, Types.BIGINT); } break; } case Types.REAL: { if (value != null && value.length() != 0) { ps.setFloat(column++, Float.parseFloat(value)); } else { ps.setNull(column++, Types.REAL); } break; } case Types.FLOAT: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.FLOAT); } break; } case Types.DOUBLE: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.DOUBLE); } break; } // skip BINARY, VARBINARY and LONGVARBINARY case Types.DATE: { if (value != null && value.length() != 0) { ps.setDate(column++, Date.valueOf(value)); } else { ps.setNull(column++, Types.DATE); } break; } case Types.TIME: { if (value != null && value.length() != 0) { ps.setTime(column++, Time.valueOf(value)); } else { ps.setNull(column++, Types.TIME); } break; } case Types.TIMESTAMP: { if (value != null && value.length() != 0) { ps.setTimestamp(column++, Timestamp.valueOf(value)); } else { ps.setNull(column++, Types.TIMESTAMP); } break; } // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT default: { String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)"; handleException(msg, msgCtx); } } } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName()); } return ps; }