List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
private int[] setArguments(PreparedStatement pstmt) throws SQLException, IOException { if (getQueryArguments().trim().length() == 0) { return new int[] {}; }//from w ww . j av a 2s . c o m String[] arguments = CSVSaveService.csvSplitString(getQueryArguments(), COMMA_CHAR); String[] argumentsTypes = getQueryArgumentsTypes().split(COMMA); if (arguments.length != argumentsTypes.length) { throw new SQLException("number of arguments (" + arguments.length + ") and number of types (" + argumentsTypes.length + ") are not equal"); } int[] outputs = new int[arguments.length]; for (int i = 0; i < arguments.length; i++) { String argument = arguments[i]; String argumentType = argumentsTypes[i]; String[] arg = argumentType.split(" "); String inputOutput = ""; if (arg.length > 1) { argumentType = arg[1]; inputOutput = arg[0]; } int targetSqlType = getJdbcType(argumentType); try { if (!OUT.equalsIgnoreCase(inputOutput)) { if (argument.equals(NULL_MARKER)) { pstmt.setNull(i + 1, targetSqlType); } else { setArgument(pstmt, argument, targetSqlType, i + 1); } } if (OUT.equalsIgnoreCase(inputOutput) || INOUT.equalsIgnoreCase(inputOutput)) { CallableStatement cs = (CallableStatement) pstmt; cs.registerOutParameter(i + 1, targetSqlType); outputs[i] = targetSqlType; } else { outputs[i] = java.sql.Types.NULL; // can't have an output parameter type null } } catch (NullPointerException e) { // thrown by Derby JDBC (at least) if there are no "?" markers in statement throw new SQLException("Could not set argument no: " + (i + 1) + " - missing parameter marker?"); } } return outputs; }
From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java
/** * {@inheritDoc}/* w w w. j a v a 2 s . c om*/ */ @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public void track(Long mandator, String typeName, String loginname, String application, String session, String remoteHost, String message, String data, String key, Object... args) { Connection con = null; PreparedStatement ps = null; try { final UserTicket ticket = FxContext.getUserTicket(); con = Database.getDbConnection(); boolean hasMandator = mandator != null; ps = con.prepareStatement( StorageManager.escapeReservedWords(hasMandator ? HISTORY_INSERT_MANDATOR : HISTORY_INSERT)); ps.setLong(1, ticket.getUserId()); ps.setString(2, StringUtils.isBlank(loginname) ? ticket.getLoginName() : loginname); ps.setLong(3, System.currentTimeMillis()); ps.setString(4, key); StorageManager.setBigString(ps, 5, StringUtils.join(args, '|')); try { if (StringUtils.isNotBlank(message)) ps.setString(6, message); else ps.setString(6, FxSharedUtils.getLocalizedMessage("History", FxLanguage.ENGLISH, "en", key, args)); } catch (Exception e) { ps.setString(6, key); } FxContext si = FxContext.get(); ps.setString(7, StringUtils.isNotBlank(session) ? session : (si.getSessionId() == null ? "<unknown>" : si.getSessionId())); ps.setString(8, StringUtils.isNotBlank(application) ? application : (si.getApplicationId() == null ? "<unknown>" : si.getApplicationId())); ps.setString(9, StringUtils.isNotBlank(remoteHost) ? remoteHost : (si.getRemoteHost() == null ? "<unknown>" : si.getRemoteHost())); if (StringUtils.isNotBlank(typeName)) { ps.setNull(10, java.sql.Types.NUMERIC); ps.setString(11, typeName); } else { ps.setNull(10, java.sql.Types.NUMERIC); ps.setNull(11, java.sql.Types.VARCHAR); } ps.setNull(12, java.sql.Types.NUMERIC); ps.setNull(13, java.sql.Types.NUMERIC); if (StringUtils.isNotBlank(data)) StorageManager.setBigString(ps, 14, data); else ps.setNull(14, java.sql.Types.VARCHAR); if (hasMandator) ps.setLong(15, mandator); ps.executeUpdate(); } catch (Exception ex) { LOG.error(ex.getMessage()); } finally { Database.closeObjects(HistoryTrackerEngineBean.class, con, ps); } }
From source file:helma.objectmodel.db.NodeManager.java
private void setStatementValue(PreparedStatement stmt, int columnNumber, String value, DbColumn col) throws SQLException { if (value == null) { stmt.setNull(columnNumber, col.getType()); } else if (col.needsQuotes()) { stmt.setString(columnNumber, value); } else {//from w ww . j a v a 2 s . c om stmt.setLong(columnNumber, Long.parseLong(value)); } }
From source file:org.jobjects.dao.annotation.Manager.java
/** * Persistance du bean annot avec DaoTable ainsi que DaoField. Si pour une * raison quelconque une problme survient, l'exception CreateException sera * leve.//from w ww . j a v a 2s . c o m * @param bean Le bean d'un type quelconque comportant des annotations daoTable et * DaoField * @return Un bean de mme type que celui pass en paramtre. Les donnes du * bean sont rafraichi partir de la base au cas o celle-ci aurait * modifi les donnes grace des trigger ou autre. * @throws CreateException * Exception leve au sur problme de persistance. */ public final T create(final T bean) throws CreateException { T returnValue = null; try { String msg = "Cannot create " + entityClass.getCanonicalName() + " : " + ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE); if (null == sql_create) { sql_create = loadSqlCreate(usualTable, fields); } returnValue = entityClass.newInstance(); try { Connection connection = getConnection(); try { PreparedStatement pstmt = connection.prepareStatement(sql_create); try { int i = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { Object obj = BeanUtils.getProperty(bean, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } break; } } } pstmt.executeUpdate(); } finally { pstmt.close(); } pstmt = null; } finally { connection.close(); } connection = null; } catch (SQLException sqle) { log.error(msg, sqle); throw new CreateException(msg, sqle); } try { returnValue = load(bean); } catch (FinderException le) { log.error(msg, le); throw new CreateException(msg, le); } } catch (Exception e) { throw new CreateException(e); } return returnValue; }
From source file:com.flexive.ejb.beans.workflow.StepDefinitionEngineBean.java
/** * {@inheritDoc}// w w w. jav a 2 s . c om */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public long create(StepDefinition stepDefinition) throws FxApplicationException { final UserTicket ticket = FxContext.getUserTicket(); // Security checks FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement); // Create the new step Connection con = null; PreparedStatement ps = null; String sql; FxString label = stepDefinition.getLabel(); if (StringUtils.isEmpty(stepDefinition.getName())) throw new FxInvalidParameterException("NAME", "ex.stepdefinition.name.empty"); if (label.isEmpty()) throw new FxInvalidParameterException("LABEL", "ex.stepdefinition.label.empty"); String name = stepDefinition.getName(); long uniqueTargetId = stepDefinition.getUniqueTargetId(); boolean success = false; long newId = -1; try { // Check the unique target checkValidUniqueTarget(-1, uniqueTargetId); if (StringUtils.isBlank(label.getDefaultTranslation())) { FxInvalidParameterException ip = new FxInvalidParameterException("NAME", "ex.stepdefinition.name.empty"); if (LOG.isDebugEnabled()) LOG.debug(ip); throw ip; } // Obtain a database connection con = Database.getDbConnection(); // Create the new workflow instance sql = "INSERT INTO " + TBL_WORKFLOW_STEPDEFINITION + " (ID,NAME,UNIQUE_TARGET) VALUES (?,?,?)"; ps = con.prepareStatement(sql); newId = seq.getId(FxSystemSequencer.STEPDEFINITION); ps.setLong(1, newId); ps.setString(2, name); if (uniqueTargetId != -1) { ps.setLong(3, uniqueTargetId); } else { ps.setNull(3, Types.NUMERIC); } if (ps.executeUpdate() != 1) throw new FxCreateException(LOG, "ex.stepdefinition.create"); Database.storeFxString(label, con, TBL_WORKFLOW_STEPDEFINITION, "name", "id", newId); success = true; } catch (FxInvalidParameterException exc) { throw exc; } catch (Exception exc) { if (StorageManager.isUniqueConstraintViolation(exc)) { FxEntryExistsException ee = new FxEntryExistsException("ex.stepdefinition.name.exists", name); if (LOG.isDebugEnabled()) LOG.debug(ee); throw ee; } else { FxCreateException ce = new FxCreateException(LOG, "ex.stepdefinition.create", exc); LOG.error("Internal error: " + exc.getMessage(), ce); throw ce; } } finally { Database.closeObjects(StepDefinitionEngineBean.class, con, ps); if (!success) { EJBUtils.rollback(ctx); } else { StructureLoader.reloadWorkflows(FxContext.get().getDivisionId()); } } return newId; }
From source file:org.jobjects.dao.annotation.Manager.java
/** * @param beanPk le bean supprimer/*from w w w . j a va2s . com*/ * @throws RemoveException Problme de suppression */ public final void remove(final P beanPk) throws RemoveException { String msg = "Delete error " + entityClass.getCanonicalName() + " : " + ToStringBuilder.reflectionToString(beanPk, ToStringStyle.MULTI_LINE_STYLE); try { Connection connection = getConnection(); try { if (null == sql_delete) { sql_delete = loadSqlDelete(usualTable, fields); } PreparedStatement pstmt = connection.prepareStatement(sql_delete); try { int i = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { if (((DaoField) annotation).isPrimary()) { Object obj = BeanUtils.getProperty(beanPk, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } } break; } } } pstmt.executeUpdate(); } finally { pstmt.close(); } pstmt = null; } finally { connection.close(); } connection = null; } catch (Exception sqle) { log.error(msg, sqle); throw new RemoveException(msg, sqle); } }
From source file:com.flexive.ejb.beans.structure.TypeEngineBean.java
/** * Create a new type//ww w . ja v a 2 s.co m * * @param type the type to create * @return id of the new type * @throws FxApplicationException on errors */ private long create(FxTypeEdit type) throws FxApplicationException { final UserTicket ticket = FxContext.getUserTicket(); FxPermissionUtils.checkRole(ticket, Role.StructureManagement); final FxEnvironment environment = CacheAdmin.getEnvironment(); if (StringUtils.isEmpty(type.getName())) throw new FxInvalidParameterException("NAME", "ex.structure.create.nameMissing"); if (!type.getStorageMode().isSupported()) throw new FxInvalidParameterException("STORAGEMODE", "ex.structure.typeStorageMode.notSupported", type.getStorageMode().getLabel().getBestTranslation(ticket)); if (type.getACL().getCategory() != ACLCategory.STRUCTURE) throw new FxInvalidParameterException("aclId", "ex.acl.category.invalid", type.getACL().getCategory().name(), ACLCategory.STRUCTURE.name()); if (type.hasDefaultInstanceACL() && type.getDefaultInstanceACL().getCategory() != ACLCategory.INSTANCE) throw new FxInvalidParameterException("DEFACL", "ex.acl.category.invalid", type.getDefaultInstanceACL().getCategory(), ACLCategory.INSTANCE); Connection con = null; PreparedStatement ps = null; long newId = seq.getId(FxSystemSequencer.TYPEDEF); final long NOW = System.currentTimeMillis(); try { con = Database.getDbConnection(); ps = con.prepareStatement(TYPE_CREATE); ps.setLong(1, newId); ps.setString(2, type.getName()); if (type.getParent() != null) ps.setLong(3, type.getParent().getId()); else ps.setNull(3, java.sql.Types.INTEGER); ps.setInt(4, type.getStorageMode().getId()); ps.setInt(5, type.getCategory().getId()); ps.setInt(6, type.getMode().getId()); ps.setInt(7, type.getLanguage().getId()); ps.setInt(8, type.getState().getId()); ps.setByte(9, type.getBitCodedPermissions()); ps.setBoolean(10, type.isTrackHistory()); ps.setLong(11, type.getHistoryAge()); ps.setLong(12, type.getMaxVersions()); ps.setInt(13, type.getMaxRelSource()); ps.setInt(14, type.getMaxRelDestination()); ps.setLong(15, ticket.getUserId()); ps.setLong(16, NOW); ps.setLong(17, ticket.getUserId()); ps.setLong(18, NOW); ps.setLong(19, type.getACL().getId()); ps.setLong(20, type.getWorkflow().getId()); if (type.getIcon().isEmpty()) ps.setNull(21, java.sql.Types.INTEGER); else ps.setLong(21, type.getIcon().getDefaultTranslation().getId()); ps.setBoolean(22, type.isUseInstancePermissions() && type.isMultipleContentACLs()); ps.setBoolean(23, type.isIncludedInSupertypeQueries()); if (type.hasDefaultInstanceACL()) ps.setLong(24, type.getDefaultInstanceACL().getId()); else ps.setNull(24, java.sql.Types.INTEGER); ps.setBoolean(25, type.isAutoVersion()); ps.executeUpdate(); Database.storeFxString(type.getLabel(), con, TBL_STRUCT_TYPES, "DESCRIPTION", "ID", newId); StructureLoader.reload(con); FxType thisType = CacheAdmin.getEnvironment().getType(newId); htracker.track(thisType, "history.type.create", type.getName(), newId); //store relations ps.close(); if (type.getAddedRelations().size() > 0) { ps = con.prepareStatement("INSERT INTO " + TBL_STRUCT_TYPERELATIONS + " (TYPEDEF,TYPESRC,TYPEDST,MAXSRC,MAXDST)VALUES(?,?,?,?,?)"); ps.setLong(1, thisType.getId()); for (FxTypeRelation rel : type.getAddedRelations()) { if (rel.getSource().isRelation()) throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget", type.getName(), rel.getSource().getName()); if (rel.getDestination().isRelation()) throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget", type.getName(), rel.getDestination().getName()); ps.setLong(2, rel.getSource().getId()); ps.setLong(3, rel.getDestination().getId()); ps.setLong(4, rel.getMaxSource()); ps.setLong(5, rel.getMaxDestination()); ps.addBatch(); htracker.track(thisType, "history.type.create.relation.add", type.getName(), rel.getSource().getName(), rel.getMaxSource(), rel.getDestination().getName(), rel.getMaxDestination()); } ps.executeBatch(); } if (type.getParent() == null) { for (FxPropertyAssignment spa : environment.getSystemInternalRootPropertyAssignments()) { final FxPropertyAssignmentEdit derived = FxPropertyAssignmentEdit.createNew(spa, thisType, spa.getAlias(), "/"); assignmentEngine.save( updateAclAssignmentMultiplicity(type, derived).setEnabled(true)._setSystemInternal(), false); } } else { //create parent assignments List<FxAssignment> parentAssignments = type.getParent().getConnectedAssignments("/"); for (FxAssignment as : parentAssignments) { if (as instanceof FxPropertyAssignment) { FxPropertyAssignmentEdit pae = FxPropertyAssignmentEdit.createNew((FxPropertyAssignment) as, thisType, as.getAlias(), "/"); pae.setEnabled(type.isEnableParentAssignments()); assignmentEngine.save(updateAclAssignmentMultiplicity(type, pae), false); } else if (as instanceof FxGroupAssignment) { FxGroupAssignmentEdit pge = FxGroupAssignmentEdit.createNew((FxGroupAssignment) as, thisType, as.getAlias(), "/"); pge.setEnabled(type.isEnableParentAssignments()); assignmentEngine.save(pge, true); } } } // store structure options storeTypeOptions(con, TBL_STRUCT_TYPES_OPTIONS, "ID", newId, type.getOptions(), false); StructureLoader.reload(con); } catch (SQLException e) { if (StorageManager.isUniqueConstraintViolation(e)) { EJBUtils.rollback(ctx); throw new FxCreateException("ex.structure.type.exists", type.getName()); } EJBUtils.rollback(ctx); throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage()); } catch (FxCacheException e) { EJBUtils.rollback(ctx); throw new FxCreateException(LOG, e, "ex.cache", e.getMessage()); } catch (FxLoadException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } catch (FxNotFoundException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } catch (FxEntryExistsException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } catch (FxUpdateException e) { EJBUtils.rollback(ctx); throw new FxCreateException(e); } finally { Database.closeObjects(TypeEngineBean.class, con, ps); } return newId; }
From source file:org.jobjects.dao.annotation.Manager.java
/** * @param beanPk le bean qui on doit vrifier l'existance. * @return return true si il existe sinon false. *//*from ww w . j av a 2 s .c o m*/ public final boolean isExist(final P beanPk) { boolean returnValue = false; if (beanPk == null) { return returnValue; } try { Connection connection = getConnection(); try { if (null == sql_exist) { sql_exist = loadSqlExist(usualTable, fields); } PreparedStatement pstmt = connection.prepareStatement(sql_exist); try { int i = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { if (((DaoField) annotation).isPrimary()) { Object obj = BeanUtils.getProperty(beanPk, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } } break; } } } ResultSet rs = pstmt.executeQuery(); try { rs.next(); returnValue = rs.getInt(1) == 1; } finally { rs.close(); } rs = null; } finally { pstmt.close(); } pstmt = null; } finally { connection.close(); } connection = null; } catch (Exception sqle) { log.error("Exist error TrsProduitProfformBean : " + beanPk, sqle); } return returnValue; }
From source file:org.jobjects.dao.annotation.Manager.java
/** * Sauvegarde le bean dans la base. Une exception SaveException peut tre * leve si un problme survient.//from w w w .j ava2 s. c o m * @param bean le bean sauvegarder * @return Un boolean positif si la mise en jour s'est relement pass. * @throws SaveException Problme de persistance */ private boolean saveReal(final T bean) throws SaveException { boolean returnValue = true; String msg = "Cannot save " + entityClass.getCanonicalName() + " : " + ToStringBuilder.reflectionToString(bean, ToStringStyle.MULTI_LINE_STYLE); try { Connection connection = getConnection(); try { if (null == sql_save) { sql_save = loadSqlSave(usualTable, fields); } PreparedStatement pstmt = connection.prepareStatement(sql_save); try { int i = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { if (!((DaoField) annotation).isPrimary()) { Object obj = BeanUtils.getProperty(bean, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } } break; } } } for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { if (((DaoField) annotation).isPrimary()) { Object obj = BeanUtils.getProperty(bean, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } } break; } } } returnValue = pstmt.executeUpdate() == 1; } finally { pstmt.close(); } pstmt = null; } finally { connection.close(); } connection = null; } catch (Exception sqle) { log.error(msg, sqle); throw new SaveException(msg, sqle); } return returnValue; }
From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java
protected Object deliver(final String queryString, final List<ParameterMapping> parameterMappings, final Map<String, Object> row) { // log.debug("delivering : 1"); return getJdbcTemplate().update(queryString, new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { for (ParameterMapping mapping : parameterMappings) { JdbcType jdbcType = mapping.getJdbcType(); Object value = row.get(mapping.getProperty()); Object valueToUse = value; if (valueToUse == null && mapping.getJavaType() == Date.class) { valueToUse = new Date(); }//from w w w. j a va2 s . c o m if (valueToUse instanceof Date && jdbcType == JdbcType.VARCHAR) { valueToUse = DateFormatUtils.format((Date) valueToUse, mapping.getPattern()); } if (valueToUse instanceof String && jdbcType == JdbcType.VARCHAR) { String stringValue = (String) valueToUse; if (!StringUtils.isEmpty(mapping.getEncoding())) { if (!StringUtils.isEmpty(stringValue)) { String[] encoding = StringUtils.split(mapping.getEncoding(), ">"); try { if (encoding.length == 2) valueToUse = new String(stringValue.getBytes(encoding[0]), encoding[1]); else if (encoding.length == 1) valueToUse = new String(stringValue.getBytes(), encoding[0]); } catch (UnsupportedEncodingException e) { LOG.error(e); } } } } if (valueToUse == null) ps.setNull(mapping.getIndex(), jdbcType.TYPE_CODE); else ps.setObject(mapping.getIndex(), valueToUse, jdbcType.TYPE_CODE); } } }); }