Advertisement
Guest User

Untitled

a guest
Sep 14th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.42 KB | None | 0 0
  1. package com.basilbourque.example;
  2.  
  3. import javax.servlet.annotation.WebServlet;
  4.  
  5. import com.vaadin.annotations.Theme;
  6. import com.vaadin.annotations.VaadinServletConfiguration;
  7. import com.vaadin.server.VaadinRequest;
  8. import com.vaadin.server.VaadinServlet;
  9. import com.vaadin.ui.*;
  10.  
  11. /**
  12. * This UI is the application entry point. A UI may either represent a browser window
  13. * (or tab) or some part of an HTML page where a Vaadin application is embedded.
  14. * <p>
  15. * The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
  16. * overridden to add component to the user interface and initialize non-component functionality.
  17. */
  18. @Theme ( "mytheme" )
  19. public class MyUI extends UI {
  20.  
  21. @Override
  22. protected void init ( VaadinRequest vaadinRequest ) {
  23. final Layout layout = new ProductPickerLayout();
  24. this.setContent( layout );
  25. }
  26.  
  27. @WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
  28. @VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
  29. public static class MyUIServlet extends VaadinServlet {
  30. }
  31. }
  32.  
  33. package com.basilbourque.example;
  34.  
  35. import javax.servlet.ServletContextEvent;
  36. import javax.servlet.ServletContextListener;
  37. import javax.servlet.annotation.WebListener;
  38. import java.time.Instant;
  39.  
  40. @WebListener
  41. public class MyServletContextListener implements ServletContextListener {
  42. MyDatabaseService databaseService;
  43.  
  44. @Override
  45. public void contextInitialized ( ServletContextEvent servletContextEvent ) {
  46. System.out.println( "TRACE - contextInitialized " + Instant.now() );
  47.  
  48. // Database.
  49. MyDatabaseService db = new MyDatabaseService();
  50. db.establishDatabase();
  51. }
  52.  
  53. @Override
  54. public void contextDestroyed ( ServletContextEvent servletContextEvent ) {
  55. // Nuttin' honey.
  56. }
  57. }
  58.  
  59. package com.basilbourque.example;
  60.  
  61. import java.sql.*;
  62. import java.time.Instant;
  63. import java.util.ArrayList;
  64. import java.util.List;
  65. import java.util.Locale;
  66.  
  67. public class MyDatabaseService {
  68. // ---------| Members |------------------------------------
  69. static final private String driverName = "org.h2.Driver";
  70. static final private String catalogName = "ProdPop";
  71. static final private String jdbcPath = "jdbc:h2:mem:" + MyDatabaseService.catalogName + ";DB_CLOSE_DELAY=-1"; // "jdbc:h2:mem:autogrid"; // Set delay to keep in-memory database even after last connection closed.
  72. static final private String productTableName = "product_";
  73. static final private String orderTableName = "order_";
  74.  
  75. public void establishDatabase () {
  76. // Verify JDBC driver.
  77. try {
  78. Class.forName( MyDatabaseService.driverName );
  79. } catch ( ClassNotFoundException e ) {
  80. e.printStackTrace();
  81. }
  82.  
  83. // Connect, and create database.
  84. try ( Connection conn = DriverManager.getConnection( MyDatabaseService.jdbcPath ) ;
  85. ) {
  86. String sql = null;
  87.  
  88. // Create product_ table.
  89. // Columns: pkey_ name_
  90. try ( Statement stmt = conn.createStatement() ; ) {
  91. sql = "CREATE TABLE " + productTableName + " ( n" +
  92. " pkey_ IDENTITY PRIMARY KEY , n" +
  93. " name_ VARCHAR ( 80 ) NOT NULL n" +
  94. ") ; n";
  95. System.out.println( "TRACE - SQL:n" + sql );
  96. stmt.execute( sql );
  97. }
  98. System.out.println( "TRACE - Created table product_." );
  99.  
  100. // Create order_ table.
  101. // Columns: pkey_ fkey_product_ when_ordered_
  102. try ( Statement stmt = conn.createStatement() ; ) {
  103. sql = "CREATE TABLE " + orderTableName + " ( n" +
  104. " pkey_ IDENTITY PRIMARY KEY , n" +
  105. " fkey_product_ LONG NOT NULL , n" +
  106. " when_ordered_ TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP n" +
  107. ") ; n" +
  108. "ALTER TABLE " + orderTableName + " ADD FOREIGN KEY ( fkey_product_ ) REFERENCES product_ ( pkey_ ) ; n "
  109. ;
  110. System.out.println( "TRACE - SQL:n" + sql );
  111. stmt.execute( sql );
  112. }
  113.  
  114. // List tables
  115. DatabaseMetaData md = conn.getMetaData();
  116. try ( ResultSet rs = md.getTables( null , null , null , null ) ) {
  117. while ( rs.next() ) {
  118. System.out.println( rs.getString( 3 ) );
  119. }
  120. }
  121.  
  122. // List columns of `product_` table.
  123. try ( ResultSet rs = md.getColumns( null , null , productTableName.toUpperCase( Locale.US ) , null ) ) {
  124. System.out.println( "Columns of table: " + productTableName );
  125. while ( rs.next() ) {
  126. System.out.println( rs.getString( 4 ) + " | " + rs.getString( 5 ) + " | " + rs.getString( 6 ) ); // COLUMN_NAME, DATA_TYPE , TYPE_NAME.
  127. }
  128. }
  129.  
  130. // List columns of `order_` table.
  131. try ( ResultSet rs = md.getColumns( null , null , orderTableName.toUpperCase( Locale.US ) , null ) ) {
  132. System.out.println( "Columns of table: " + orderTableName );
  133. while ( rs.next() ) {
  134. System.out.println( rs.getString( 4 ) + " | " + rs.getString( 5 ) + " | " + rs.getString( 6 ) ); // COLUMN_NAME, DATA_TYPE , TYPE_NAME.
  135. }
  136. }
  137.  
  138. // Add rows
  139. sql = "INSERT INTO product_ ( name_ ) n" +
  140. "VALUES ( ? ) " +
  141. "; ";
  142.  
  143. List< String > planets = List.of( "Mercury" , "Venus" , "Earth" , "Mars" , "Ceres" , "Jupiter" , "Saturn" , "Uranus" , "Neptune" , "Pluto" );
  144. try ( PreparedStatement ps = conn.prepareStatement( sql ) ; ) {
  145. for ( String planet : planets ) {
  146. ps.setString( 1 , planet );
  147. ps.executeUpdate();
  148. }
  149. }
  150.  
  151. System.out.println( "TRACE - Dumping tables in their initial state. " + Instant.now() );
  152. this.dumpTableToConsole( MyDatabaseService.productTableName );
  153. this.dumpTableToConsole( MyDatabaseService.orderTableName );
  154. } catch ( SQLException e ) {
  155. e.printStackTrace();
  156. }
  157. }
  158.  
  159. public void dumpTableToConsole ( String tableName ) {
  160.  
  161. try ( Connection conn = DriverManager.getConnection( MyDatabaseService.jdbcPath ) ;
  162. ) {
  163. System.out.println( "TRACE - « " + tableName + " » table dump to console at " + Instant.now() );
  164. String sql = "SELECT * FROM " + tableName + " ;";
  165. try ( Statement stmt = conn.createStatement() ;
  166. ResultSet rs = stmt.executeQuery( sql ) ; ) {
  167. ResultSetMetaData meta = rs.getMetaData();
  168. int colCount = meta.getColumnCount();
  169. int rowCount = 0;
  170. while ( rs.next() ) {
  171. rowCount++;
  172. System.out.print( "Row # " + rowCount + ": " );
  173. for ( int col = 1 ; col <= colCount ; col++ ) {
  174. System.out.print( meta.getColumnLabel( col ) + "=" );
  175. Object o = rs.getObject( col );
  176. if ( null != o ) {
  177. System.out.print( o.toString() + " " );
  178. }
  179. }
  180. System.out.println( "" ); // Newline.
  181. }
  182. System.out.println( "« fin de " + tableName + " »" );
  183. }
  184. } catch ( SQLException e ) {
  185. e.printStackTrace();
  186. }
  187. }
  188.  
  189. public List< Product > fetchAllProducts () {
  190. System.out.println( "TRACE MyDatabaseService::fetchAllOrders at " + Instant.now() );
  191.  
  192. List< Product > products = new ArrayList<>();
  193.  
  194. // Query. Loop ResultSet, instantiating object, and collecting.
  195. try ( Connection conn = DriverManager.getConnection( MyDatabaseService.jdbcPath ) ;
  196. ) {
  197. System.out.println( "TRACE - fetchAllProducts at " + Instant.now() );
  198. String sql = "SELECT * FROM " + productTableName + " ;";
  199. try (
  200. Statement stmt = conn.createStatement() ;
  201. ResultSet rs = stmt.executeQuery( sql ) ;
  202. ) {
  203. int rowCount = 0;
  204. while ( rs.next() ) {
  205. Long pkey = rs.getLong( "pkey_" );
  206. String name = rs.getString( "name_" );
  207. // Make object from column values.
  208. Product p = new Product( pkey , name );
  209. products.add( p ); // Collect each `Order` object retrieved from database.
  210. }
  211. }
  212. } catch ( SQLException e ) {
  213. e.printStackTrace();
  214. }
  215.  
  216. return products;
  217. }
  218.  
  219. public List< Order > fetchAllOrders () {
  220. System.out.println( "TRACE MyDatabaseService::fetchAllOrders at " + Instant.now() );
  221.  
  222. List< Order > orders = new ArrayList<>();
  223.  
  224. // Query. Loop ResultSet, instantiating object, and collecting.
  225. try ( Connection conn = DriverManager.getConnection( MyDatabaseService.jdbcPath ) ;
  226. ) {
  227. String sql = "SELECT * FROM " + orderTableName + " n ORDER BY pkey_ DESC n ;";
  228. try (
  229. Statement stmt = conn.createStatement() ;
  230. ResultSet rs = stmt.executeQuery( sql ) ;
  231. ) {
  232. int rowCount = 0;
  233. while ( rs.next() ) {
  234. Long pkey = rs.getLong( "pkey_" );
  235. Long fkey_product = rs.getLong( "fkey_product_" );
  236. Instant when_ordered = rs.getObject( "when_ordered_" , Instant.class );
  237. // Make object from column values.
  238. Order o = new Order( pkey , fkey_product , when_ordered );
  239. orders.add( o ); // Collect each `Order` object retrieved from database.
  240. }
  241. }
  242. } catch ( SQLException e ) {
  243. e.printStackTrace();
  244. }
  245.  
  246. return orders;
  247. }
  248.  
  249. public void insertOrder ( Long fkeyProduct ) {
  250. System.out.println( "TRACE - MyDatabaseService::insertOrder at " + Instant.now() );
  251. try ( Connection conn = DriverManager.getConnection( MyDatabaseService.jdbcPath ) ;
  252. ) {
  253. String sql = "INSERT INTO " + orderTableName + "( fkey_product_ )n" + " VALUES ( ? ) ;n";
  254. PreparedStatement ps = conn.prepareStatement( sql );
  255. ps.setLong( 1 , fkeyProduct );
  256. ps.executeUpdate();
  257. } catch ( SQLException e ) {
  258. e.printStackTrace();
  259. }
  260. }
  261. }
  262.  
  263. package com.basilbourque.example;
  264.  
  265. import com.vaadin.data.HasValue;
  266. import com.vaadin.data.HasValue.ValueChangeEvent;
  267. import com.vaadin.ui.*;
  268.  
  269. import java.time.Instant;
  270. import java.util.List;
  271.  
  272. public class ProductPickerLayout extends VerticalLayout {
  273. Label prodPopLabel;
  274. NativeSelect< Product > productSelect;
  275. Button orderButton;
  276.  
  277. Grid< Product > productsGrid;
  278. Grid< Order > ordersGrid;
  279.  
  280. // Constructor
  281. public ProductPickerLayout () {
  282. this.widgetsMake();
  283. this.widgetsArrange();
  284. }
  285.  
  286. private void widgetsMake () {
  287.  
  288. // Create the selection component
  289. this.prodPopLabel = new Label( "Products: " );
  290. this.productSelect = new NativeSelect<>();
  291. // Add some items
  292. List< Product > products = new MyDatabaseService().fetchAllProducts();
  293. this.productSelect.setItems( products );
  294. this.productSelect.setItemCaptionGenerator( Product :: getName );
  295. // Show 5 items and a scrollbar if there are more
  296. // select.setRows( 3 );
  297.  
  298. productSelect.addValueChangeListener( new HasValue.ValueChangeListener< Product >() {
  299. @Override
  300. public void valueChange ( ValueChangeEvent< Product > valueChangeEvent ) {
  301. Product p = valueChangeEvent.getValue();
  302. orderButton.setEnabled( null != p );
  303. Notification.show( "Selected: " + p.name );
  304. }
  305. } );
  306.  
  307. this.orderButton = new Button( "Order" );
  308. this.orderButton.setEnabled( this.productSelect.getValue() != null );
  309. this.orderButton.addClickListener( ( Button.ClickEvent e ) -> {
  310. this.placeOrder();
  311. this.ordersGrid.setItems( new MyDatabaseService().fetchAllOrders() );
  312. } );
  313.  
  314. MyDatabaseService db = new MyDatabaseService();
  315.  
  316. this.productsGrid = new Grid<>( Product.class );
  317. this.productsGrid.setItems( products );
  318. this.productsGrid.setCaption( "Products" );
  319.  
  320. this.ordersGrid = new Grid<>( Order.class );
  321. List< Order > orders = db.fetchAllOrders();
  322. this.ordersGrid.setItems( orders );
  323. this.ordersGrid.setCaption( "Orders" );
  324. }
  325.  
  326. private void widgetsArrange () {
  327. HorizontalLayout orderBar = new HorizontalLayout();
  328. orderBar.setSpacing( true );
  329. orderBar.addComponents( this.prodPopLabel , this.productSelect , this.orderButton );
  330. orderBar.setComponentAlignment( this.prodPopLabel , Alignment.MIDDLE_CENTER );
  331. orderBar.setComponentAlignment( this.productSelect , Alignment.MIDDLE_CENTER );
  332. orderBar.setComponentAlignment( this.orderButton , Alignment.MIDDLE_CENTER );
  333.  
  334. HorizontalLayout gridsBar = new HorizontalLayout();
  335. gridsBar.setSpacing( true );
  336. gridsBar.addComponents( this.productsGrid , this.ordersGrid );
  337.  
  338. this.addComponents( orderBar , gridsBar );
  339. this.setExpandRatio( gridsBar , 1.0F );
  340. }
  341.  
  342. private void placeOrder () {
  343. // Get pkey of the currently selected product.
  344.  
  345. Product p = this.productSelect.getValue();
  346. if ( null == p ) {
  347. throw new IllegalStateException( "The `productSelect` NativeSelect does not have a current value." );
  348. }
  349. Long fkeyProduct = p.pkey;
  350.  
  351. // Insert row into table.
  352. new MyDatabaseService().insertOrder( fkeyProduct );
  353.  
  354. this.updateOrdersGrid();
  355. }
  356.  
  357. private void updateOrdersGrid () {
  358. }
  359. }
  360.  
  361. package com.basilbourque.example;
  362.  
  363. public class Product {
  364. Long pkey;
  365. String name;
  366.  
  367. public Product ( Long pkey , String name ) {
  368. this.pkey = pkey;
  369. this.name = name;
  370. }
  371.  
  372. @Override
  373. public String toString () {
  374. return "Product{ " +
  375. "pkey=" + pkey +
  376. "| name='" + name +
  377. " }";
  378. }
  379.  
  380.  
  381. // -----------| Accessors |-----------------
  382.  
  383. public Long getPkey () {
  384. return pkey;
  385. }
  386.  
  387. public void setPkey ( Long pkey ) {
  388. this.pkey = pkey;
  389. }
  390.  
  391. public String getName () {
  392. return name;
  393. }
  394.  
  395. public void setName ( String name ) {
  396. this.name = name;
  397. }
  398. }
  399.  
  400. package com.basilbourque.example;
  401.  
  402. import java.time.Instant;
  403.  
  404. public class Order {
  405. Long pkey; // Identifier of this order.
  406. Long fkeyProduct; // Identifier of the product being ordered.
  407. Instant whenOrdered; // The moment the order was placed.
  408.  
  409. public Order ( Long pkey , Long fkeyProduct , Instant whenOrdered ) {
  410. this.pkey = pkey;
  411. this.fkeyProduct = fkeyProduct;
  412. this.whenOrdered = whenOrdered;
  413. }
  414.  
  415. @Override
  416. public String toString () {
  417. return "Order{ " +
  418. "pkey=" + pkey +
  419. "| fkeyProduct=" + fkeyProduct +
  420. "| whenOrdered=" + whenOrdered +
  421. " }";
  422. }
  423.  
  424. // -----------| Accessors |-----------------
  425.  
  426. public Long getPkey () {
  427. return pkey;
  428. }
  429.  
  430. public void setPkey ( Long pkey ) {
  431. this.pkey = pkey;
  432. }
  433.  
  434. public Long getFkeyProduct () {
  435. return fkeyProduct;
  436. }
  437.  
  438. public void setFkeyProduct ( Long fkeyProduct ) {
  439. this.fkeyProduct = fkeyProduct;
  440. }
  441.  
  442. public Instant getWhenOrdered () {
  443. return whenOrdered;
  444. }
  445.  
  446. public void setWhenOrdered ( Instant whenOrdered ) {
  447. this.whenOrdered = whenOrdered;
  448. }
  449. }
  450.  
  451. <?xml version="1.0" encoding="UTF-8"?>
  452. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  453. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  454. <modelVersion>4.0.0</modelVersion>
  455.  
  456. <groupId>com.basilbourque.example</groupId>
  457. <artifactId>prodpop</artifactId>
  458. <packaging>war</packaging>
  459. <version>1.0-SNAPSHOT</version>
  460. <name>prodpop</name>
  461.  
  462. <prerequisites>
  463. <maven>3</maven>
  464. </prerequisites>
  465.  
  466. <properties>
  467. <vaadin.version>8.5.2</vaadin.version>
  468. <vaadin.plugin.version>8.5.2</vaadin.plugin.version>
  469. <jetty.plugin.version>9.4.12.v20180830</jetty.plugin.version>
  470. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  471. <maven.compiler.source>10</maven.compiler.source>
  472. <maven.compiler.target>10</maven.compiler.target>
  473. <!-- If there are no local customizations, this can also be "fetch" or "cdn" -->
  474. <vaadin.widgetset.mode>local</vaadin.widgetset.mode>
  475. </properties>
  476.  
  477. <repositories>
  478. <repository>
  479. <id>vaadin-addons</id>
  480. <url>http://maven.vaadin.com/vaadin-addons</url>
  481. </repository>
  482. </repositories>
  483.  
  484. <dependencyManagement>
  485. <dependencies>
  486. <dependency>
  487. <groupId>com.vaadin</groupId>
  488. <artifactId>vaadin-bom</artifactId>
  489. <version>${vaadin.version}</version>
  490. <type>pom</type>
  491. <scope>import</scope>
  492. </dependency>
  493. </dependencies>
  494. </dependencyManagement>
  495.  
  496. <dependencies>
  497. <dependency>
  498. <groupId>javax.servlet</groupId>
  499. <artifactId>javax.servlet-api</artifactId>
  500. <version>3.1.0</version>
  501. <scope>provided</scope>
  502. </dependency>
  503. <dependency>
  504. <groupId>com.vaadin</groupId>
  505. <artifactId>vaadin-server</artifactId>
  506. </dependency>
  507. <dependency>
  508. <groupId>com.vaadin</groupId>
  509. <artifactId>vaadin-push</artifactId>
  510. </dependency>
  511. <dependency>
  512. <groupId>com.vaadin</groupId>
  513. <artifactId>vaadin-client-compiled</artifactId>
  514. </dependency>
  515. <dependency>
  516. <groupId>com.vaadin</groupId>
  517. <artifactId>vaadin-themes</artifactId>
  518. </dependency>
  519.  
  520. <!--Basil-->
  521. <dependency>
  522. <groupId>com.h2database</groupId>
  523. <artifactId>h2</artifactId>
  524. <version>1.4.197</version>
  525. </dependency>
  526.  
  527. </dependencies>
  528.  
  529. <build>
  530. <plugins>
  531. <plugin>
  532. <groupId>org.apache.maven.plugins</groupId>
  533. <artifactId>maven-war-plugin</artifactId>
  534. <version>3.2.2</version>
  535. <configuration>
  536. <failOnMissingWebXml>false</failOnMissingWebXml>
  537. <!-- Exclude an unnecessary file generated by the GWT compiler. -->
  538. <packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
  539. </configuration>
  540. </plugin>
  541. <plugin>
  542. <groupId>com.vaadin</groupId>
  543. <artifactId>vaadin-maven-plugin</artifactId>
  544. <version>${vaadin.plugin.version}</version>
  545. <executions>
  546. <execution>
  547. <goals>
  548. <goal>update-theme</goal>
  549. <goal>update-widgetset</goal>
  550. <goal>compile</goal>
  551. <!-- Comment out compile-theme goal to use on-the-fly theme compilation -->
  552. <goal>compile-theme</goal>
  553. </goals>
  554. </execution>
  555. </executions>
  556. </plugin>
  557. <plugin>
  558. <groupId>org.apache.maven.plugins</groupId>
  559. <artifactId>maven-clean-plugin</artifactId>
  560. <version>3.1.0</version>
  561. <!-- Clean up also any pre-compiled themes -->
  562. <configuration>
  563. <filesets>
  564. <fileset>
  565. <directory>src/main/webapp/VAADIN/themes</directory>
  566. <includes>
  567. <include>**/styles.css</include>
  568. <include>**/styles.scss.cache</include>
  569. </includes>
  570. </fileset>
  571. </filesets>
  572. </configuration>
  573. </plugin>
  574.  
  575. <!-- The Jetty plugin allows us to easily test the development build by
  576. running jetty:run on the command line. -->
  577. <plugin>
  578. <groupId>org.eclipse.jetty</groupId>
  579. <artifactId>jetty-maven-plugin</artifactId>
  580. <version>${jetty.plugin.version}</version>
  581. <configuration>
  582. <scanIntervalSeconds>2</scanIntervalSeconds>
  583. </configuration>
  584. </plugin>
  585. </plugins>
  586. </build>
  587.  
  588. <profiles>
  589. <profile>
  590. <!-- Vaadin pre-release repositories -->
  591. <id>vaadin-prerelease</id>
  592. <activation>
  593. <activeByDefault>false</activeByDefault>
  594. </activation>
  595.  
  596. <repositories>
  597. <repository>
  598. <id>vaadin-prereleases</id>
  599. <url>http://maven.vaadin.com/vaadin-prereleases</url>
  600. </repository>
  601. <repository>
  602. <id>vaadin-snapshots</id>
  603. <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
  604. <releases>
  605. <enabled>false</enabled>
  606. </releases>
  607. <snapshots>
  608. <enabled>true</enabled>
  609. </snapshots>
  610. </repository>
  611. </repositories>
  612. <pluginRepositories>
  613. <pluginRepository>
  614. <id>vaadin-prereleases</id>
  615. <url>http://maven.vaadin.com/vaadin-prereleases</url>
  616. </pluginRepository>
  617. <pluginRepository>
  618. <id>vaadin-snapshots</id>
  619. <url>https://oss.sonatype.org/content/repositories/vaadin-snapshots/</url>
  620. <releases>
  621. <enabled>false</enabled>
  622. </releases>
  623. <snapshots>
  624. <enabled>true</enabled>
  625. </snapshots>
  626. </pluginRepository>
  627. </pluginRepositories>
  628. </profile>
  629. </profiles>
  630.  
  631. </project>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement