List of usage examples for java.sql Timestamp valueOf
@SuppressWarnings("deprecation") public static Timestamp valueOf(LocalDateTime dateTime)
From source file:gov.nih.nci.cadsr.sentinel.tool.AlertRec.java
/** * Convert date strings to the expected format. Either '/' or '-' separators * can be used./*from w w w . j a v a2 s . c o m*/ * * @param val_ * The date string. * @return The timestamp object for the date given. */ static public Timestamp parseDate(String val_) { if (val_ == null || val_.length() == 0) return null; Timestamp temp = null; String tval[]; int pos = val_.indexOf('/'); if (pos > -1) { tval = val_.split("/"); temp = Timestamp.valueOf(fixDate(tval)); } else { pos = val_.indexOf('-'); if (pos > -1) { tval = val_.split("-"); temp = Timestamp.valueOf(fixDate(tval)); } } return temp; }
From source file:org.ecoinformatics.seek.dataquery.DBTablesGenerator.java
private synchronized PreparedStatement setupPreparedStatmentParameter(int index, PreparedStatement pStatement, String data, String javaDataType) throws SQLException, UnresolvableTypeException, IllegalArgumentException { if (pStatement == null) { return pStatement; }//from ww w . j a va 2 s . c o m // get rid of white space if (data != null) { data = data.trim(); } // set default type as string if (javaDataType == null) { pStatement.setString(index, data); } else { if (javaDataType.equals(STRING)) { pStatement.setString(index, data); } else if (javaDataType.equals(INTEGER)) { pStatement.setInt(index, (new Integer(data)).intValue()); } else if (javaDataType.equals(DOUBLE)) { pStatement.setDouble(index, (new Double(data)).doubleValue()); } else if (javaDataType.equals(FLOAT)) { pStatement.setFloat(index, (new Float(data)).floatValue()); } else if (javaDataType.equals(BOOLEAN)) { pStatement.setBoolean(index, (new Boolean(data)).booleanValue()); } else if (javaDataType.equals(LONG)) { pStatement.setLong(index, (new Long(data)).longValue()); } else if (javaDataType.equals(DATETIME)) { pStatement.setTimestamp(index, Timestamp.valueOf(data)); } else { throw new UnresolvableTypeException("This java type " + javaDataType + " has NOT implement in " + "DBTablesGenerator.setupPreparedStatmentParameter method"); } } return pStatement; }
From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java
public java.util.Date parseTimestamp(int type, String value) { try {/*from w ww . j a v a2 s. c o m*/ return Timestamp.valueOf(value); } catch (IllegalArgumentException ex) { try { return FormatUtils.parseDate(value, FormatUtils.TIMESTAMP_PATTERNS); } catch (Exception e) { int split = value.lastIndexOf(" "); String datetime = value.substring(0, split).trim(); String timezone = value.substring(split).trim(); try { return Timestamp.valueOf(datetime); // Try it again without the timezone component. } catch (IllegalArgumentException ex2) { return FormatUtils.parseDate(datetime, FormatUtils.TIMESTAMP_PATTERNS, getTimeZone(timezone)); } } } }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
/** * Method for adding API related information * * @param connection DB Connection//from ww w .ja va 2 s.com * @param statement PreparedStatement * @param api API object * @throws SQLException if error occurs while accessing data layer */ private void addAPIRelatedInformation(Connection connection, PreparedStatement statement, final API api) throws SQLException { String apiPrimaryKey = api.getId(); statement.setString(1, api.getProvider()); statement.setString(2, api.getName()); statement.setString(3, api.getContext()); statement.setString(4, api.getVersion()); statement.setBoolean(5, api.isDefaultVersion()); statement.setString(6, api.getDescription()); statement.setString(7, api.getVisibility().toString()); statement.setBoolean(8, api.isResponseCachingEnabled()); statement.setInt(9, api.getCacheTimeout()); statement.setString(10, apiPrimaryKey); BusinessInformation businessInformation = api.getBusinessInformation(); statement.setString(11, businessInformation.getTechnicalOwner()); statement.setString(12, businessInformation.getTechnicalOwnerEmail()); statement.setString(13, businessInformation.getBusinessOwner()); statement.setString(14, businessInformation.getBusinessOwnerEmail()); statement.setString(15, api.getLifecycleInstanceId()); statement.setString(16, api.getLifeCycleStatus()); CorsConfiguration corsConfiguration = api.getCorsConfiguration(); statement.setBoolean(17, corsConfiguration.isEnabled()); statement.setString(18, String.join(",", corsConfiguration.getAllowOrigins())); statement.setBoolean(19, corsConfiguration.isAllowCredentials()); statement.setString(20, String.join(",", corsConfiguration.getAllowHeaders())); statement.setString(21, String.join(",", corsConfiguration.getAllowMethods())); statement.setInt(22, getApiTypeId(connection, ApiType.STANDARD)); statement.setString(23, api.getCreatedBy()); statement.setTimestamp(24, Timestamp.valueOf(LocalDateTime.now())); statement.setTimestamp(25, Timestamp.valueOf(LocalDateTime.now())); statement.setString(26, api.getCopiedFromApiId()); statement.setString(27, api.getUpdatedBy()); statement.setString(28, APILCWorkflowStatus.APPROVED.toString()); statement.execute(); if (API.Visibility.RESTRICTED == api.getVisibility()) { addVisibleRole(connection, apiPrimaryKey, api.getVisibleRoles()); } addTagsMapping(connection, apiPrimaryKey, api.getTags()); addLabelMapping(connection, apiPrimaryKey, api.getLabels()); addGatewayConfig(connection, apiPrimaryKey, api.getGatewayConfig(), api.getCreatedBy()); addTransports(connection, apiPrimaryKey, api.getTransport()); addUrlMappings(connection, api.getUriTemplates().values(), apiPrimaryKey); addSubscriptionPolicies(connection, api.getPolicies(), apiPrimaryKey); addEndPointsForApi(connection, apiPrimaryKey, api.getEndpoint()); addAPIDefinition(connection, apiPrimaryKey, api.getApiDefinition(), api.getCreatedBy()); addAPIPermission(connection, api.getPermissionMap(), apiPrimaryKey); if (api.getApiPolicy() != null) { addApiPolicy(connection, api.getApiPolicy().getUuid(), apiPrimaryKey); } }
From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java
/** * Consume an XML message and update the specified Timestamp instance. * <br>/* w w w . jav a 2 s .com*/ * @param object the instance that is to be updated with the XML message data. * @param cellElement the XML element that contains the data * @return the updated instance. * @exception JDOMException if there is an error consuming the message. */ private Object consumeMsg(Timestamp object, Element cellElement) throws JDOMException { // ----------------------- // Process the element ... // ----------------------- Timestamp result; try { result = Timestamp.valueOf(cellElement.getTextTrim()); } catch (Exception e) { throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$ } return result; }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
/** * Method for adding Composite API related information * * @param connection DB Connection/*from w w w . j av a 2s . c o m*/ * @param statement PreparedStatement * @param api Composite API object * @throws SQLException if error occurs while accessing data layer */ private void addCompositeAPIRelatedInformation(Connection connection, PreparedStatement statement, final CompositeAPI api) throws SQLException { String apiPrimaryKey = api.getId(); statement.setString(1, api.getProvider()); statement.setString(2, api.getName()); statement.setString(3, api.getContext()); statement.setString(4, api.getVersion()); statement.setString(5, api.getDescription()); statement.setString(6, apiPrimaryKey); statement.setInt(7, getApiTypeId(connection, ApiType.COMPOSITE)); statement.setString(8, api.getCreatedBy()); statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now())); statement.setTimestamp(10, Timestamp.valueOf(LocalDateTime.now())); statement.setString(11, api.getCopiedFromApiId()); statement.setString(12, api.getUpdatedBy()); statement.setString(13, APILCWorkflowStatus.APPROVED.toString()); statement.execute(); addLabelMapping(connection, apiPrimaryKey, api.getLabels()); addGatewayConfig(connection, apiPrimaryKey, api.getGatewayConfig(), api.getCreatedBy()); addTransports(connection, apiPrimaryKey, api.getTransport()); addUrlMappings(connection, api.getUriTemplates().values(), apiPrimaryKey); addAPIDefinition(connection, apiPrimaryKey, api.getApiDefinition(), api.getCreatedBy()); addAPIPermission(connection, api.getPermissionMap(), apiPrimaryKey); }
From source file:com.indicator_engine.controller.ToolkitAdminController.java
@RequestMapping(value = "/add_json_events", method = RequestMethod.GET) public @ResponseBody String loadEventsfromJSON() { Gson eventGson = new Gson(); GLAEVENTDTO[] glaevents = null;/* w w w. ja va 2 s .c o m*/ GLAUserDao glauserBean = (GLAUserDao) appContext.getBean("glaUser"); GLACategoryDao glacategoryBean = (GLACategoryDao) appContext.getBean("glaCategory"); GLAEventDao glaEventBean = (GLAEventDao) appContext.getBean("glaEvent"); try { glaevents = eventGson.fromJson(new FileReader("c:\\gla_Event.json"), GLAEVENTDTO[].class); } catch (FileNotFoundException e) { } for (int i = 0; i < glaevents.length; i++) { GLAUser selectedglaUser = glauserBean.loaduserByName(glaevents[i].getUSERNAME()); GLACategory selectedglaCategory = glacategoryBean.loadCategoryByName(glaevents[i].getCATEGORY()); GLAEvent glaEvent = new GLAEvent(); glaEvent.setSession(glaevents[i].getSESSION()); glaEvent.setAction(glaevents[i].getACTION()); glaEvent.setPlatform(glaevents[i].getPLATFORM()); glaEvent.setTimestamp(Timestamp.valueOf(glaevents[i].getTIMESTAMP())); glaEvent.setSource(glaevents[i].getSOURCE()); glaEvent.setGlaUser(selectedglaUser); glaEvent.setGlaCategory(selectedglaCategory); GLAEntity glaEntity = new GLAEntity(glaevents[i].getKEY(), glaevents[i].getVALUE()); glaEventBean.add(glaEvent, glaEntity); } return eventGson.toJson(glaevents); }
From source file:com.hp.rest.OrdersHandle.java
@POST @Path("/updateDetailSaleOrder") @Consumes(MediaType.APPLICATION_JSON)//w ww . j a v a 2 s . c o m public Response updateDetailSaleOrder(String pSaleOrder) { SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); String time = sdf2.format(cal.getTime()); // pair to object ObjectMapper mapper = new ObjectMapper(); SaleOrderDetail saleOrderDetail = new SaleOrderDetail(); try { // File jsonFile = new File(jsonFilePath); saleOrderDetail = mapper.readValue(pSaleOrder, SaleOrderDetail.class); //System.out.println(track.getMMaKhachHang()); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Update location SaleOrderDetailDAO saleOrderDetailDAO = new SaleOrderDetailDAOImpl(); boolean st = saleOrderDetailDAO.update(saleOrderDetail); if (!st) return Response.status(200).entity(st + "").build(); //Update the order List<SaleOrderDetail> list = new ArrayList<SaleOrderDetail>(); list = saleOrderDetailDAO.getDetailSaleOrdersList(saleOrderDetail.getTakeOrderID()); float priceTotal = 0; for (int i = 0; i < list.size(); i++) { priceTotal += list.get(i).getPriceTotal(); } SaleOrder saleOrder = new SaleOrder(); SaleOrderDAO saleOrderDAO = new SaleOrderDAOImpl(); saleOrder = saleOrderDAO.getSaleOrder(saleOrderDetail.getTakeOrderID()); saleOrder.setAfterPrivate(priceTotal - priceTotal * saleOrder.getDiscount() / 100); saleOrder.setOrderEditDate(Timestamp.valueOf(time)); boolean st2 = saleOrderDAO.update(saleOrder); // String output = pTrack.toString(); System.out.println("____ " + pSaleOrder + "___ " + st); return Response.status(200).entity(st2 + "").build(); }
From source file:org.openmrs.module.spreadsheetimport.DatabaseBackend.java
public static void validateData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData) throws SQLException, SpreadsheetImportTemplateValidationException { Connection conn = null;/*www .j a va2 s.co m*/ Statement s = null; String sql = null; SQLException exception = null; ResultSet rs = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); s = conn.createStatement(); for (UniqueImport uniqueImport : rowData.keySet()) { if ("obs".equals(uniqueImport.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { String columnName = obsColumn.getColumnName(); String conceptId = getPrespecifiedConceptIdFromObsColumn(obsColumn); if (conceptId == null) throw new SpreadsheetImportTemplateValidationException("no prespecified concept ID"); if ("value_coded".equals(columnName)) { // skip if empty if (obsColumn.getValue().equals("")) continue; // verify the answers are the concepts which are possible answers //sql = "select answer_concept from concept_answer join concept_name on concept_answer.answer_concept = concept_name.concept_id where concept_name.name = '" + obsColumn.getValue() + "' and concept_answer.concept_id = '" + conceptId + "'"; sql = "select answer_concept from concept_answer where answer_concept = '" + obsColumn.getValue() + "' and concept_id = '" + conceptId + "'"; rs = s.executeQuery(sql); if (!rs.next()) { sql = "select name from concept_name where concept_id = " + conceptId; rs = s.executeQuery(sql); rs.next(); String conceptName = rs.getString(1); throw new SpreadsheetImportTemplateValidationException( "invalid concept answer for the prespecified concept ID " + conceptName); } } else if ("value_text".equals(columnName)) { // skip if empty if (obsColumn.getValue().equals("")) continue; // verify the number of characters is less than the allowed length } else if ("value_numeric".equals(columnName)) { // skip if empty if (obsColumn.getValue().equals("")) continue; // verify it's within the range specified in the concept definition sql = "select hi_absolute, low_absolute from concept_numeric where concept_id = '" + conceptId + "'"; rs = s.executeQuery(sql); if (!rs.next()) throw new SpreadsheetImportTemplateValidationException( "prespecified concept ID " + conceptId + " is not a numeric concept"); double hiAbsolute = rs.getDouble(1); double lowAbsolute = rs.getDouble(2); double value = 0.0; try { value = Double.parseDouble(obsColumn.getValue().toString()); } catch (NumberFormatException nfe) { throw new SpreadsheetImportTemplateValidationException( "concept value is not a number"); } if (hiAbsolute < value || lowAbsolute > value) throw new SpreadsheetImportTemplateValidationException( "concept value " + value + " of column " + columnName + " is out of range " + lowAbsolute + " - " + hiAbsolute); } else if ("value_datetime".equals(columnName) || "obs_datetime".equals(columnName)) { // skip if empty if (obsColumn.getValue().equals("")) continue; // verify datetime is defined and it can not be in the future String value = obsColumn.getValue().toString(); String date = value.substring(1, value.length() - 1); if (Timestamp.valueOf(date).after(new Timestamp(System.currentTimeMillis()))) throw new SpreadsheetImportTemplateValidationException("date is in the future"); } } } else if ("patient_identifier".equals(uniqueImport.getTableName())) { Set<SpreadsheetImportTemplateColumn> piColumns = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn piColumn : piColumns) { String columnName = piColumn.getColumnName(); if (!"identifier".equals(columnName)) continue; String pitId = getPrespecifiedPatientIdentifierTypeIdFromPatientIdentifierColumn(piColumn); if (pitId == null) throw new SpreadsheetImportTemplateValidationException( "no prespecified patient identifier type ID"); sql = "select format from patient_identifier_type where patient_identifier_type_id = " + pitId; rs = s.executeQuery(sql); if (!rs.next()) throw new SpreadsheetImportTemplateValidationException( "invalid prespcified patient identifier type ID"); String format = rs.getString(1); if (format != null && format.trim().length() != 0) { String value = piColumn.getValue().toString(); value = value.substring(1, value.length() - 1); Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(value); if (!matcher.matches()) throw new SpreadsheetImportTemplateValidationException( "Patient ID is not conforming to patient identifier type"); } } } } } catch (SQLException e) { log.debug(e.toString()); exception = e; } catch (IllegalAccessException e) { log.debug(e.toString()); } catch (InstantiationException e) { log.debug(e.toString()); } catch (ClassNotFoundException e) { log.debug(e.toString()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (s != null) { try { s.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } if (exception != null) { throw exception; } }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
/** * Update an existing API//from w w w. j a v a 2 s . c om * * @param apiID The {@link String} of the API that needs to be updated * @param substituteAPI Substitute {@link API} object that will replace the existing API * @throws APIMgtDAOException if error occurs while accessing data layer */ @Override public void updateAPI(String apiID, API substituteAPI) throws APIMgtDAOException { final String query = "UPDATE AM_API SET CONTEXT = ?, IS_DEFAULT_VERSION = ?, DESCRIPTION = ?, VISIBILITY = ?, " + "IS_RESPONSE_CACHED = ?, CACHE_TIMEOUT = ?, TECHNICAL_OWNER = ?, TECHNICAL_EMAIL = ?, " + "BUSINESS_OWNER = ?, BUSINESS_EMAIL = ?, CORS_ENABLED = ?, CORS_ALLOW_ORIGINS = ?, " + "CORS_ALLOW_CREDENTIALS = ?, CORS_ALLOW_HEADERS = ?, CORS_ALLOW_METHODS = ?, LAST_UPDATED_TIME = ?," + "UPDATED_BY = ?, LC_WORKFLOW_STATUS=? WHERE UUID = ?"; try (Connection connection = DAOUtil.getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { try { connection.setAutoCommit(false); statement.setString(1, substituteAPI.getContext()); statement.setBoolean(2, substituteAPI.isDefaultVersion()); statement.setString(3, substituteAPI.getDescription()); statement.setString(4, substituteAPI.getVisibility().toString()); statement.setBoolean(5, substituteAPI.isResponseCachingEnabled()); statement.setInt(6, substituteAPI.getCacheTimeout()); BusinessInformation businessInformation = substituteAPI.getBusinessInformation(); statement.setString(7, businessInformation.getTechnicalOwner()); statement.setString(8, businessInformation.getTechnicalOwnerEmail()); statement.setString(9, businessInformation.getBusinessOwner()); statement.setString(10, businessInformation.getBusinessOwnerEmail()); CorsConfiguration corsConfiguration = substituteAPI.getCorsConfiguration(); statement.setBoolean(11, corsConfiguration.isEnabled()); statement.setString(12, String.join(",", corsConfiguration.getAllowOrigins())); statement.setBoolean(13, corsConfiguration.isAllowCredentials()); statement.setString(14, String.join(",", corsConfiguration.getAllowHeaders())); statement.setString(15, String.join(",", corsConfiguration.getAllowMethods())); statement.setTimestamp(16, Timestamp.valueOf(LocalDateTime.now())); statement.setString(17, substituteAPI.getUpdatedBy()); statement.setString(18, substituteAPI.getWorkflowStatus()); statement.setString(19, apiID); statement.execute(); deleteVisibleRoles(connection, apiID); // Delete current visible roles if they exist if (API.Visibility.RESTRICTED == substituteAPI.getVisibility()) { addVisibleRole(connection, apiID, substituteAPI.getVisibleRoles()); } deleteAPIPermission(connection, apiID); updateApiPermission(connection, substituteAPI.getPermissionMap(), apiID); deleteTransports(connection, apiID); addTransports(connection, apiID, substituteAPI.getTransport()); deleteTagsMapping(connection, apiID); // Delete current tag mappings if they exist addTagsMapping(connection, apiID, substituteAPI.getTags()); deleteLabelsMapping(connection, apiID); addLabelMapping(connection, apiID, substituteAPI.getLabels()); deleteSubscriptionPolicies(connection, apiID); addSubscriptionPolicies(connection, substituteAPI.getPolicies(), apiID); deleteEndPointsForApi(connection, apiID); addEndPointsForApi(connection, apiID, substituteAPI.getEndpoint()); deleteEndPointsForOperation(connection, apiID); deleteUrlMappings(connection, apiID); addUrlMappings(connection, substituteAPI.getUriTemplates().values(), apiID); deleteApiPolicy(connection, apiID); if (substituteAPI.getApiPolicy() != null) { addApiPolicy(connection, substituteAPI.getApiPolicy().getUuid(), apiID); } connection.commit(); } catch (SQLException | IOException e) { String msg = "Couldn't update api : " + substituteAPI.getName(); connection.rollback(); log.error(msg, e); throw new APIMgtDAOException(e); } finally { connection.setAutoCommit(DAOUtil.isAutoCommit()); } } catch (SQLException e) { throw new APIMgtDAOException(e); } }