List of usage examples for java.sql PreparedStatement setTimestamp
void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException;
java.sql.Timestamp
value. From source file:edu.ku.brc.specify.conversion.ConvertMiscData.java
/** * @param oldDBConn//from w w w. j av a 2s . c om * @param newDBConn */ public static void moveStratFieldsToCEA(final Connection oldDBConn, final Connection newDBConn) { String sql = null; try { IdMapperIFace ceMapper = IdMapperMgr.getInstance().addTableMapper("collectingevent", "CollectingEventID", false); String postFix = " FROM collectingevent ce Inner Join collectingeventattribute AS cea ON ce.CollectingEventAttributeID = cea.CollectingEventAttributeID "; /* Specify 5 Field ----------> Specify 6 Field Stratigraphy.superGroup --> CEA.text3 Stratigraphy.group --> CEA.text4 Stratigraphy.formation --> CEA.text5 Stratigraphy.text1 --> CEA.text1 Stratigraphy.number1 --> CEA.number1 Stratigraphy.text2 --> CEA.text2 */ Timestamp now = new Timestamp(System.currentTimeMillis()); PreparedStatement pStmt = newDBConn.prepareStatement( "UPDATE collectingeventattribute SET Text1=?, Text2=?, Text3=?, Text4=?, Text5=?, Number1=? WHERE CollectingEventAttributeID=?"); PreparedStatement pStmt2 = newDBConn.prepareStatement( "INSERT INTO collectingeventattribute SET Text1=?, Text2=?, Text3=?, Text4=?, Text5=?, Number1=?, Version=0, DisciplineID=?, TimestampCreated=?, TimestampModified=?", Statement.RETURN_GENERATED_KEYS); PreparedStatement pStmt3 = newDBConn.prepareStatement( "UPDATE collectingevent SET CollectingEventAttributeID=? WHERE CollectingEventID=?"); int cnt = 0; // Query to Create PickList sql = "SELECT StratigraphyID, Text1, Text2, SuperGroup, `Group`, Formation, Number1 FROM stratigraphy"; for (Object[] row : BasicSQLUtils.query(oldDBConn, sql)) { Integer id = (Integer) row[0]; Integer newCEId = ceMapper.get(id); if (newCEId != null) { Vector<Object[]> colList = BasicSQLUtils.query( "SELECT DisciplineID, CollectingEventAttributeID FROM collectingevent WHERE CollectingEventID = " + newCEId); Object[] cols = colList.get(0); if (cols[1] != null) { pStmt.setString(1, (String) row[1]); pStmt.setString(2, (String) row[2]); pStmt.setString(3, (String) row[3]); pStmt.setString(4, (String) row[4]); pStmt.setString(5, (String) row[5]); pStmt.setString(6, (String) row[6]); pStmt.setInt(7, newCEId); int rv = pStmt.executeUpdate(); if (rv != 1) { log.error(String.format("Error updating CEA New Id %d Old: %d rv: %d", newCEId, id, rv)); } } else { Integer disciplineID = (Integer) cols[0]; pStmt2.setString(1, (String) row[1]); pStmt2.setString(2, (String) row[2]); pStmt2.setString(3, (String) row[3]); pStmt2.setString(4, (String) row[4]); pStmt2.setString(5, (String) row[5]); pStmt2.setString(6, (String) row[6]); pStmt2.setInt(7, disciplineID); pStmt2.setTimestamp(8, now); pStmt2.setTimestamp(9, now); int rv = pStmt2.executeUpdate(); if (rv == 1) { Integer newCEAId = BasicSQLUtils.getInsertedId(pStmt2); if (newCEAId != null) { pStmt3.setInt(1, newCEAId); pStmt3.setInt(2, newCEId); rv = pStmt3.executeUpdate(); if (rv != 1) { log.error(String.format("Error updating CEA New Id %d To CE ID: %d", newCEAId, newCEId)); } } else { log.error("Couldn't get inserted CEAId"); } } else { log.error(String.format("Error updating CEA New Id %d Old: %d rv: %d", newCEId, id, rv)); } } } else { log.error(String.format("No Map for Old CE Id %d", id)); } cnt++; if (cnt % 500 == 0) { log.debug("Count " + cnt); } } log.debug("Count " + cnt); pStmt.close(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.uas.document.DocumentDAO.java
@Override public DocumentDTO updateDocument(DocumentDTO dDto) { DocumentDTO dtoViejo = getDocument(dDto); DocumentDTO objectDto = null;//from w w w. ja v a2s . com ResultSet rs = null; Connection c = null; PreparedStatement preparedStmt = null; try { c = DataSourceSingleton.getInstance().getConnection(); String SQL = "update \"public\".\"document\" set \"fileDate\"=?,\"deleted\"=?,\"backedUp\"=?,\"idArea\"=? where \"id\"=? "; preparedStmt = c.prepareStatement(SQL); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date parsedDate = dateFormat.parse(dDto.getFileDate().substring(0, 10)); Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime()); preparedStmt.setTimestamp(1, timestamp); preparedStmt.setBoolean(2, dDto.getDeleted()); //System.out.println("dDto.getBackedUp() : " + dDto.getBackedUp()); preparedStmt.setBoolean(3, dDto.getBackedUp()); preparedStmt.setInt(4, dDto.getIdArea()); preparedStmt.setInt(5, dDto.getId()); preparedStmt.executeUpdate(); //System.out.println("dDto.getVengoDeRootYPuedoCambiarDeArea() : " + dDto.getVengoDeRootYPuedoCambiarDeArea()); if ((dtoViejo.getIdArea() != dDto.getIdArea()) && (dDto.getVengoDeRootYPuedoCambiarDeArea())) { DocumentDTO dtoNuevo = getDocument(dDto); if (dDto.getDeleted()) { Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolderInDeleted()).getParent()); Files.move(Paths.get(dtoViejo.getFullPathToFolderInDeleted()), Paths.get(dtoNuevo.getFullPathToFolderInDeleted())); } else { //Si Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolder()).getParent()); Files.move(Paths.get(dtoViejo.getFullPathToFolder()), Paths.get(dtoNuevo.getFullPathToFolder())); } } /* if (!dDto.getBackedUp()){ TransactionRecordFacade tFac = new TransactionRecordFacade(); TransactionRecordDTO tDto = new TransactionRecordDTO(); tDto.getObjectDTO().setId(dDto.getId()); tDto.getTransactionTypeDTO().setId(4); tDto.getUsuarioDTO().setId(dDto.getCreatedBy()); tFac.createTransactionRecord(tDto); } */ } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (c != null) { c.close(); } if (preparedStmt != null) { preparedStmt.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return dDto; }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insertStandplaatsen(final List<Standplaats> standplaatsen) throws DAOException { try {// www. j a v a2 s .c o m transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.batchUpdate("insert into bag_standplaats (" + "bag_standplaats_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "officieel," + "standplaats_status," + "standplaats_geometrie," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer," + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setLong(1, standplaatsen.get(i).getIdentificatie()); ps.setInt(2, standplaatsen.get(i).getAanduidingRecordInactief().ordinal()); ps.setLong(3, standplaatsen.get(i).getAanduidingRecordCorrectie()); ps.setInt(4, standplaatsen.get(i).getOfficieel().ordinal()); ps.setInt(5, standplaatsen.get(i).getStandplaatsStatus().ordinal()); ps.setString(6, standplaatsen.get(i).getStandplaatsGeometrie()); ps.setTimestamp(7, new Timestamp( standplaatsen.get(i).getBegindatumTijdvakGeldigheid().getTime())); if (standplaatsen.get(i).getEinddatumTijdvakGeldigheid() == null) ps.setNull(8, Types.TIMESTAMP); else ps.setTimestamp(8, new Timestamp( standplaatsen.get(i).getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(9, standplaatsen.get(i).getInOnderzoek().ordinal()); ps.setDate(10, new Date(standplaatsen.get(i).getDocumentdatum().getTime())); ps.setString(11, standplaatsen.get(i).getDocumentnummer()); ps.setLong(12, standplaatsen.get(i).getHoofdAdres()); } @Override public int getBatchSize() { return standplaatsen.size(); } }); insertNevenadressen(TypeAdresseerbaarObject.STANDPLAATS, standplaatsen); } }); } catch (DataAccessException e) { throw new DAOException("Error inserting standplaatsen", e); } }
From source file:net.sf.farrago.namespace.sfdc.SfdcUdx.java
public static void query(String query, String types, PreparedStatement resultInserter) throws SQLException { SoapBindingStub binding = (SoapBindingStub) FarragoUdrRuntime.getDataServerRuntimeSupport(null); try {/*www. j av a 2 s . c om*/ QueryOptions qo = new QueryOptions(); int batchsize = 500; qo.setBatchSize(new Integer(batchsize)); binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "QueryOptions", qo); String objName = query; int fromIdx = query.lastIndexOf(" from"); if (fromIdx > 0) { objName = query.substring(fromIdx + 6); } // strip off quotes for boolean values query = stripQuotes(query, objName); log.info("SFDC Query: " + query); QueryResult qr = binding.query(query); if (qr.isDone()) { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievedAllRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } else { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievingRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } SObject[] records = qr.getRecords(); String[] metadataType = types.split(","); // query is of following format: // "select col1,col2,... from" String cols = query.substring(7); fromIdx = cols.lastIndexOf(" from"); cols = cols.substring(0, fromIdx); cols = cols.trim(); String[] columnValues = new String[metadataType.length]; if (records != null) { boolean bContinue = true; while (bContinue) { // for each record returned in query, // get value of each field for (int i = 0; i < records.length; i++) { MessageElement[] elements = records[i].get_any(); if (elements != null) { for (int j = 0; j < elements.length; j++) { MessageElement elt = elements[j]; String eltVal = elt.getValue(); columnValues[j] = (eltVal != null) ? eltVal : "null"; if (metadataType[j].indexOf("TIMESTAMP") != -1) { // TIMESTAMP if (eltVal != null) { String tstampstr = eltVal.replace("T", " "); tstampstr = tstampstr.substring(0, tstampstr.indexOf(".")); java.sql.Timestamp tstamp = java.sql.Timestamp.valueOf(tstampstr); resultInserter.setTimestamp(j + 1, tstamp); } else { resultInserter.setNull(j + 1, java.sql.Types.TIMESTAMP); } } else if (metadataType[j].indexOf("TIME") != -1) { // TIME if (eltVal != null) { String timestr = eltVal.substring(0, eltVal.indexOf(".")); java.sql.Time time = java.sql.Time.valueOf(timestr); resultInserter.setTime(j + 1, time); } else { resultInserter.setNull(j + 1, java.sql.Types.TIME); } } else if (metadataType[j].indexOf("DATE") != -1) { // DATE if (eltVal != null) { java.sql.Date dt = java.sql.Date.valueOf(eltVal); resultInserter.setDate(j + 1, dt); } else { resultInserter.setNull(j + 1, java.sql.Types.DATE); } } else if (metadataType[j].indexOf("INTEGER") != -1) { // INTEGER if (eltVal != null) { int iValue = 0; iValue = Integer.parseInt(eltVal); resultInserter.setInt(j + 1, iValue); } else { resultInserter.setNull(j + 1, java.sql.Types.INTEGER); } } else if (metadataType[j].indexOf("DOUBLE") != -1) { // DOUBLE if (eltVal != null) { resultInserter.setDouble(j + 1, Double.parseDouble(eltVal)); } else { resultInserter.setNull(j + 1, java.sql.Types.DOUBLE); } } else if (eltVal != null) { // VARCHAR - default int rightParen = metadataType[j].indexOf(")"); int prec = Integer.parseInt(metadataType[j].substring(8, rightParen)); if (eltVal.length() > prec) { eltVal = eltVal.substring(0, prec); columnValues[j] = eltVal; } resultInserter.setString(j + 1, eltVal); } else { resultInserter.setNull(j + 1, java.sql.Types.VARCHAR); } } resultInserter.executeUpdate(); } } if (qr.isDone()) { bContinue = false; } else { boolean relogin = true; int retryCnt = 0; while (relogin) { try { qr = binding.queryMore(qr.getQueryLocator()); relogin = false; } catch (AxisFault a) { if (a.getFaultString().contains("Invalid Session ID") && (retryCnt < RETRY_CNT)) { relogin = true; retryCnt++; binding = (SoapBindingStub) FarragoUdrRuntime .getDataServerRuntimeSupport(binding); } else { throw a; } } } records = qr.getRecords(); if (qr.isDone()) { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievedAllRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } else { if (qr.getRecords() != null) { log.info(SfdcResource.instance().RetrievingRecordsMsg .str(Integer.toString(qr.getRecords().length), objName)); } } } } } } catch (AxisFault ae) { SQLException retryExcn = new SQLException(ae.getFaultString(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(ae.getFaultString(), chainedEx); } catch (RemoteException re) { SQLException retryExcn = new SQLException(re.getMessage(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(re.getMessage(), chainedEx); } }
From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java
/** * /*w w w . jav a 2s. c o m*/ */ public static void fixUserPermissions(final boolean doSilently) { final String FIXED_USER_PERMS = "FIXED_USER_PERMS"; boolean isAlreadyFixed = AppPreferences.getRemote().getBoolean(FIXED_USER_PERMS, false); if (isAlreadyFixed) { return; } String whereStr = " WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.UserPrincipal' "; String whereStr2 = "AND p.userGroupScopeID IS NULL"; String postSQL = " FROM specifyuser su " + "INNER JOIN specifyuser_spprincipal ss ON su.SpecifyUserID = ss.SpecifyUserID " + "INNER JOIN spprincipal p ON ss.SpPrincipalID = p.SpPrincipalID " + "LEFT JOIN spprincipal_sppermission pp ON p.SpPrincipalID = pp.SpPrincipalID " + "LEFT OUTER JOIN sppermission pm ON pp.SpPermissionID = pm.SpPermissionID " + whereStr; String sql = "SELECT COUNT(*)" + postSQL + whereStr2; log.debug(sql); if (BasicSQLUtils.getCountAsInt(sql) < 1) { sql = "SELECT COUNT(*)" + postSQL; log.debug(sql); if (BasicSQLUtils.getCountAsInt(sql) > 0) { return; } } final String updatePermSQL = "DELETE FROM %s WHERE SpPermissionID = %d"; final String updatePrinSQL = "DELETE FROM %s WHERE SpPrincipalID = %d"; sql = "SELECT p.SpPrincipalID, pp.SpPermissionID" + postSQL; log.debug(sql); HashSet<Integer> prinIds = new HashSet<Integer>(); for (Object[] row : query(sql)) { Integer prinId = (Integer) row[0]; if (prinId != null) { prinIds.add(prinId); } Integer permId = (Integer) row[1]; if (permId != null) { update(String.format(updatePermSQL, "spprincipal_sppermission", permId)); update(String.format(updatePermSQL, "sppermission", permId)); log.debug("Removing PermId: " + permId); } } StringBuilder sb1 = new StringBuilder(); for (Integer prinId : prinIds) { update(String.format(updatePrinSQL, "specifyuser_spprincipal", prinId)); update(String.format(updatePrinSQL, "spprincipal", prinId)); log.debug("Removing PrinId: " + prinId); if (sb1.length() > 0) sb1.append(","); sb1.append(prinId.toString()); } log.debug("(" + sb1.toString() + ")"); // Create all the necessary UperPrincipal records // Start by figuring out what group there are and then create one UserPrincipal record // for each one TreeSet<String> nameSet = new TreeSet<String>(); sql = "SELECT su.Name, su.SpecifyUserID, p.userGroupScopeID, p.SpPrincipalID FROM specifyuser su " + "INNER JOIN specifyuser_spprincipal sp ON su.SpecifyUserID = sp.SpecifyUserID " + "INNER JOIN spprincipal p ON sp.SpPrincipalID = p.SpPrincipalID " + "WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.GroupPrincipal'"; String fields = "TimestampCreated, TimestampModified, Version, GroupSubClass, groupType, Name, Priority, Remarks, userGroupScopeID, CreatedByAgentID, ModifiedByAgentID"; String insertSQL = "INSERT INTO spprincipal (" + fields + ") VALUES(?,?,?,?,?,?,?,?,?,?,?)"; String insertSQL2 = "INSERT INTO specifyuser_spprincipal (SpecifyUserID, SpPrincipalID) VALUES(?,?)"; String searchSql = "SELECT " + fields + " FROM spprincipal WHERE SpPrincipalID = ?"; sb1 = new StringBuilder(); PreparedStatement selStmt = null; PreparedStatement pStmt = null; PreparedStatement pStmt2 = null; try { Connection conn = DBConnection.getInstance().getConnection(); pStmt = conn.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS); pStmt2 = conn.prepareStatement(insertSQL2); selStmt = conn.prepareStatement(searchSql); String adtSQL = "SELECT DISTINCT ca.AgentID FROM specifyuser AS su INNER Join agent AS ca ON su.CreatedByAgentID = ca.AgentID"; Integer createdById = BasicSQLUtils.getCount(conn, adtSQL); if (createdById == null) { createdById = BasicSQLUtils.getCount(conn, "SELECT AgentID FROM agent ORDER BY AgentID ASC LIMIT 0,1"); if (createdById == null) { UIRegistry.showError("The permissions could not be fixed because there were no agents."); AppPreferences.shutdownAllPrefs(); DBConnection.shutdownFinalConnection(true, true); return; } } for (Object[] row : query(sql)) { String usrName = (String) row[0]; Integer userId = (Integer) row[1]; Integer collId = (Integer) row[2]; Integer prinId = (Integer) row[3]; nameSet.add(usrName); log.debug("usrName: " + usrName + " prinId: " + prinId); if (sb1.length() > 0) sb1.append(","); sb1.append(prinId.toString()); selStmt.setInt(1, prinId); ResultSet rs = selStmt.executeQuery(); if (rs.next()) { log.debug(String.format("%s - adding UserPrincipal for Collection %d / %d", usrName, rs.getInt(9), collId)); Integer createdByAgentID = (Integer) rs.getObject(10); Integer modifiedByAgentID = (Integer) rs.getObject(11); pStmt.setTimestamp(1, rs.getTimestamp(1)); pStmt.setTimestamp(2, rs.getTimestamp(2)); pStmt.setInt(3, 1); // Version pStmt.setString(4, "edu.ku.brc.af.auth.specify.principal.UserPrincipal"); // GroupSubClass pStmt.setString(5, null); // groupType pStmt.setString(6, rs.getString(6)); // Name pStmt.setInt(7, 80); // Priority pStmt.setString(8, rs.getString(8)); // Remarks pStmt.setInt(9, rs.getInt(9)); // userGroupScopeID pStmt.setInt(10, createdByAgentID != null ? createdByAgentID : createdById); pStmt.setInt(11, modifiedByAgentID != null ? modifiedByAgentID : createdById); // Create UserPrincipal pStmt.executeUpdate(); int newPrinId = BasicSQLUtils.getInsertedId(pStmt); // Join the new Principal to the SpecifyUser record pStmt2.setInt(1, userId); pStmt2.setInt(2, newPrinId); pStmt2.executeUpdate(); } else { // error } rs.close(); } log.debug("(" + sb1.toString() + ")"); AppPreferences.getRemote().putBoolean(FIXED_USER_PERMS, true); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (pStmt != null) pStmt.close(); if (pStmt2 != null) pStmt2.close(); if (selStmt != null) selStmt.close(); } catch (Exception ex) { } } final StringBuilder sb = new StringBuilder(); for (String nm : nameSet) { if (sb.length() > 0) sb.append('\n'); sb.append(nm); } if (!doSilently) { JTextArea ta = UIHelper.createTextArea(15, 30); ta.setText(sb.toString()); ta.setEditable(false); JEditorPane htmlPane = new JEditorPane("text/html", //$NON-NLS-1$ UIRegistry.getResourceString("FDBAL_PERMFIXEDDESC")); htmlPane.setEditable(false); htmlPane.setOpaque(false); CellConstraints cc = new CellConstraints(); PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p:g,8px,f:p:g")); pb.add(htmlPane, cc.xy(1, 1)); pb.add(UIHelper.createScrollPane(ta), cc.xy(1, 3)); pb.setDefaultDialogBorder(); CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), UIRegistry.getResourceString("FDBAL_PERMFIXED"), true, CustomDialog.OK_BTN, pb.getPanel()); dlg.setOkLabel(UIRegistry.getResourceString("CLOSE")); UIHelper.centerAndShow(dlg); } }
From source file:net.sf.infrared.collector.impl.persistence.ApplicationStatisticsDaoImpl.java
void saveExecutionTimes(final ApplicationStatistics stats) { final String appName = stats.getApplicationName(); final String instanceId = stats.getInstanceId(); final String[] layers = stats.getLayers(); for (int i = 0; i < layers.length; i++) { final AggregateExecutionTime[] aets = stats.getExecutionsInLayer(layers[i]); final String layerName = layers[i]; getJdbcTemplate().batchUpdate(SQL_INSERT_AGGREGATE_EXECUTION_TIME, new BatchPreparedStatementSetter() { public int getBatchSize() { return aets.length; }//from ww w.java2 s. c o m public void setValues(PreparedStatement ps, int j) throws SQLException { String name = aets[j].getContext().getName(); ps.setString(1, appName); ps.setString(2, instanceId); ps.setString(3, aets[j].getContext().getLayer()); ps.setString(4, aets[j].getContext().getClass().getName()); // since sql query strigs can be very large and hence those shall be stored // after trimming. if (name != null && name.length() > MAX_LENGTH_OF_NAME) { name = name.substring(0, MAX_LENGTH_OF_NAME - 1); log.debug("The name element : " + name + " of the " + aets[j].getContext() + " context exceeded its maximum allotted length of " + MAX_LENGTH_OF_NAME + " and shall be trimmed down to the permitted size before persisting to database."); } ps.setString(5, name); ps.setLong(6, aets[j].getExecutionCount()); ps.setLong(7, aets[j].getTotalInclusiveTime()); ps.setLong(8, aets[j].getMaxInclusiveTime()); ps.setLong(9, aets[j].getMinInclusiveTime()); ps.setLong(10, aets[j].getTotalExclusiveTime()); ps.setLong(11, aets[j].getMaxExclusiveTime()); ps.setLong(12, aets[j].getMinExclusiveTime()); ps.setLong(13, aets[j].getTimeOfFirstExecution()); ps.setLong(14, aets[j].getTimeOfLastExecution()); ps.setLong(15, aets[j].getInclusiveFirstExecutionTime()); ps.setLong(16, aets[j].getInclusiveLastExecutionTime()); ps.setLong(17, aets[j].getExclusiveFirstExecutionTime()); ps.setLong(18, aets[j].getExclusiveLastExecutionTime()); ps.setString(19, aets[j].getLayerName()); ps.setTimestamp(20, new Timestamp(System.currentTimeMillis())); } }); if (log.isDebugEnabled()) { log.debug("Scheduled batch update for saving " + aets.length + " executions times in layer " + layerName + " to DB; stats=" + stats); } } if (log.isDebugEnabled()) { log.debug("Saved all execution times of " + layers.length + " layers in " + stats + " to DB"); } }
From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java
/** * Persist the TGT in the JDBC storage.//from w w w. ja v a2 s . c o m * @param tgt The TGT to persist. * @param bProcessEvent TRUE if event must be performed * @return the event that was or would be performed * @throws PersistenceException If persistance. * @see IEntityManager#persist(IEntity) */ private TGTListenerEvent performPersist(JDBCTGT tgt, boolean bProcessEvent) throws PersistenceException { if (tgt == null) throw new IllegalArgumentException("Suplied tgt is empty or invalid"); TGTListenerEvent listenerEvent = null; List<TGTEventError> listTGTEventErrors = null; Connection oConnection = null; PreparedStatement ps = null; String id = tgt.getId(); try { oConnection = _oDataSource.getConnection(); if (id == null) // New TGT { byte[] baId = new byte[ITGT.TGT_LENGTH]; do { _random.nextBytes(baId); try { id = ModifiedBase64.encode(baId); } catch (UnsupportedEncodingException e) { _logger.error("Could not create tgt id for byte[]: " + baId, e); throw new PersistenceException(SystemErrors.ERROR_INTERNAL); } } while (exists(id)); //Key allready exists //Update expiration time and id tgt.setId(id); long expiration = System.currentTimeMillis() + _lExpiration; tgt.setTgtExpTime(expiration); try { //Create statement ps = oConnection.prepareStatement(_sInsertQuery); ps.setString(1, id); ps.setTimestamp(2, new Timestamp(expiration)); ps.setBytes(3, Serialize.encode(tgt.getUser())); ps.setBytes(4, Serialize.encode(tgt.getAuthenticationProfile())); ps.setBytes(5, Serialize.encode(tgt.getModifiableAuthNProfileIDs())); ps.setBytes(6, Serialize.encode(tgt.getModifiableRequestorIDs())); ps.setBytes(7, Serialize.encode(tgt.getAttributes())); int i = ps.executeUpdate(); _logger.debug(i + " New TGT(s) added:" + id); listenerEvent = TGTListenerEvent.ON_CREATE; if (bProcessEvent) { try { processEvent(listenerEvent, tgt); } catch (TGTListenerException e) { listTGTEventErrors = e.getErrors(); } } } catch (SQLException e) { _logger.error("Could not execute insert query: " + _sInsertQuery, e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT); } } else if (tgt.isExpired()) // Expired { _logger.debug("TGT Expired: " + id); IUser tgtUser = tgt.getUser(); _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.TGT_EXPIRED, tgtUser.getID(), tgtUser.getOrganization(), null, null, this, null)); listenerEvent = TGTListenerEvent.ON_REMOVE; if (bProcessEvent) { try { processEvent(listenerEvent, tgt); } catch (TGTListenerException e) { listTGTEventErrors = e.getErrors(); } } try { ps = oConnection.prepareStatement(_sRemoveQuery); ps.setString(1, id); int i = ps.executeUpdate(); _logger.debug(i + " TGT removed: " + id); } catch (SQLException e) { _logger.error("Could not execute delete query: " + _sRemoveQuery, e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE); } int iCountR = 0; if (_aliasStoreSP != null) iCountR = _aliasStoreSP.remove(oConnection, id); int iCountF = 0; if (_aliasStoreIDP != null) iCountF = _aliasStoreIDP.remove(oConnection, id); if (_logger.isDebugEnabled() && iCountR + iCountF > 0) { StringBuffer sbDebug = new StringBuffer("Removed '"); sbDebug.append(iCountR); sbDebug.append("' (requestor based) aliasses and '"); sbDebug.append(iCountF); sbDebug.append("' (remote enitity based) aliasses"); _logger.debug(sbDebug.toString()); } } else // Update { try { // Update expiration time long expiration = System.currentTimeMillis() + _lExpiration; tgt.setTgtExpTime(expiration); // Update tgt ps = oConnection.prepareStatement(_sUpdateQuery); ps.setTimestamp(1, new Timestamp(expiration)); ps.setBytes(2, Serialize.encode(tgt.getUser())); ps.setBytes(3, Serialize.encode(tgt.getAuthenticationProfile())); ps.setBytes(4, Serialize.encode(tgt.getModifiableAuthNProfileIDs())); ps.setBytes(5, Serialize.encode(tgt.getModifiableRequestorIDs())); ps.setBytes(6, Serialize.encode(tgt.getAttributes())); ps.setString(7, id); int i = ps.executeUpdate(); _logger.debug(i + " TGT updated:" + id); listenerEvent = TGTListenerEvent.ON_UPDATE; if (bProcessEvent) { try { processEvent(listenerEvent, tgt); } catch (TGTListenerException e) { listTGTEventErrors = e.getErrors(); } } } catch (SQLException e) { _logger.error("Could not execute update query: " + _sUpdateQuery, e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE); } } if (listTGTEventErrors != null) {//TGT Event processing failed, error has been logged already throw new TGTListenerException(listTGTEventErrors); } } catch (PersistenceException e) { throw e; } catch (Exception e) { _logger.error("Internal error during persist of tgt with id: " + id, e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE); } finally { try { if (ps != null) ps.close(); } catch (SQLException e) { _logger.error("Could not close statement", e); } try { if (oConnection != null) oConnection.close(); } catch (SQLException e) { _logger.error("Could not close connection", e); } } return listenerEvent; }
From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java
private Set<Folder> listDeletedAddressbook(Date date, AccessToken at) throws SQLException { PreparedStatement ps = null; ResultSet rs = null;/*from www . j av a2s . co m*/ Connection con = null; String sql = "SELECT id, name, userobm_id, userobm_lastname, userobm_firstname, userobm_login, domain.domain_name" + " FROM AddressBook" + " INNER JOIN DeletedAddressbook ON (addressbook_id = id)" + " INNER JOIN UserObm ON (owner = userobm_id)" + " INNER JOIN Domain as domain ON (userobm_domain_id=domain.domain_id) " + " WHERE user_id = ? AND timestamp >= ?"; Set<Folder> folders = new HashSet<Folder>(); try { con = obmHelper.getConnection(); ps = con.prepareStatement(sql); ps.setInt(1, at.getObmId()); ps.setTimestamp(2, new Timestamp(date.getTime())); rs = ps.executeQuery(); while (rs.next()) { Folder f = buildFolder(at, rs); folders.add(f); } } finally { obmHelper.cleanup(con, ps, rs); } return folders; }
From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java
private Set<Folder> listDeletedSyncedAddressbook(Date date, AccessToken at) throws SQLException { PreparedStatement ps = null; ResultSet rs = null;/*from ww w . j a v a2 s . co m*/ Connection con = null; String sql = "SELECT id, name, userobm_id, userobm_lastname, userobm_firstname, userobm_login, domain.domain_name" + " FROM AddressBook" + " INNER JOIN DeletedSyncedAddressbook ON (addressbook_id = id)" + " INNER JOIN UserObm ON (owner = userobm_id)" + " INNER JOIN Domain as domain ON (userobm_domain_id=domain.domain_id) " + " WHERE user_id = ? AND timestamp >= ?"; Set<Folder> folders = new HashSet<Folder>(); try { con = obmHelper.getConnection(); ps = con.prepareStatement(sql); ps.setInt(1, at.getObmId()); ps.setTimestamp(2, new Timestamp(date.getTime())); rs = ps.executeQuery(); while (rs.next()) { Folder f = buildFolder(at, rs); folders.add(f); } } finally { obmHelper.cleanup(con, ps, rs); } return folders; }
From source file:com.kylinolap.rest.service.QueryService.java
/** * @param preparedState//from www . j a v a2s . c o m * @param param * @throws SQLException */ private void setParam(PreparedStatement preparedState, int index, StateParam param) throws SQLException { boolean isNull = (null == param.getValue()); Class<?> clazz = Object.class; try { clazz = Class.forName(param.getClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } Rep rep = Rep.of(clazz); switch (rep) { case PRIMITIVE_CHAR: case CHARACTER: case STRING: preparedState.setString(index, isNull ? null : String.valueOf(param.getValue())); break; case PRIMITIVE_INT: case INTEGER: preparedState.setInt(index, isNull ? null : Integer.valueOf(param.getValue())); break; case PRIMITIVE_SHORT: case SHORT: preparedState.setShort(index, isNull ? null : Short.valueOf(param.getValue())); break; case PRIMITIVE_LONG: case LONG: preparedState.setLong(index, isNull ? null : Long.valueOf(param.getValue())); break; case PRIMITIVE_FLOAT: case FLOAT: preparedState.setFloat(index, isNull ? null : Float.valueOf(param.getValue())); break; case PRIMITIVE_DOUBLE: case DOUBLE: preparedState.setDouble(index, isNull ? null : Double.valueOf(param.getValue())); break; case PRIMITIVE_BOOLEAN: case BOOLEAN: preparedState.setBoolean(index, isNull ? null : Boolean.parseBoolean(param.getValue())); break; case PRIMITIVE_BYTE: case BYTE: preparedState.setByte(index, isNull ? null : Byte.valueOf(param.getValue())); break; case JAVA_UTIL_DATE: case JAVA_SQL_DATE: preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue())); break; case JAVA_SQL_TIME: preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue())); break; case JAVA_SQL_TIMESTAMP: preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue())); break; default: preparedState.setObject(index, isNull ? null : param.getValue()); } }