Friday, December 9, 2016

How to use localtunnel to test your website online

First you need to install Gulp.

Then in command prompt install local tunnel

npm install -g localtunnel

Test it

lt --help

And get a temporary adress

lt --port 8080

This adress you can use during few minutes and thei it will expire

Wednesday, December 7, 2016

How to run psql script

If you have a postgres database named myDatabase 
By user user with password password.

First need to set up the path for psql.exe which exists in the %Postgres_home_directory%\bin.
Then Push WIN ÿ button on your keyboard, in appeared window type "cmd", then ENTER to open your command prompt.
There go to the directory where your script is, using cd directoryadress/ ENTER.
In this folder type myscript psql -h localhost -U user -f cms-tables.psql myDatabase.
-h localhost - if you work locally
-p 5433 - if port of database is not default

Friday, November 4, 2016

My errors #1 Unable to create connection, postgresql_Driver_9_4 is already registered

After all I'm recieving the errors:
 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (ServerService Thread Pool -- 74) javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:jboss/datasources/PostgresDS  

Caused because previous warnings:
 2016-11-04 23:56:27,637 WARN [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-8) WFLYJCA0003: Unable to instantiate driver class "org.postgresql.Driver": org.jboss.msc.service.DuplicateServiceException: Service jboss.jdbc-driver.catshelter-java_war_org_postgresql_Driver_9_4 is already registered  

 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 70) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:345)  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:352)  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:287)  
      at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1320)  
      at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)  
      at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:617)  
      at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:589)  
      at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)  
      at org.jboss.jca.core.connectionmanager.tx.TxConnectionManagerImpl.getManagedConnection(TxConnectionManagerImpl.java:429)  
      at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)  
      at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)  
      at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)  
      at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)  
      at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)  
      at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)  
      at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)  
      at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)  
      at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)  
      at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)  
      at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)  
      at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)  
      at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)  
      at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)  
      at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)  
      at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)  
      at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)  
      at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)  
      at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)  
      at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)  
      at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:161)  
      at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:121)  
      at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)  
      at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:193)  
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)  
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)  
      at java.lang.Thread.run(Thread.java:745)  
      at org.jboss.threads.JBossThread.run(JBossThread.java:320)  
 Caused by: javax.resource.ResourceException: IJ031089: Failed to load datasource: org.postgresql.Driver  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDataSource(LocalManagedConnectionFactory.java:652)  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:313)  
      ... 36 more  
 Caused by: java.lang.ClassCastException: org.postgresql.Driver cannot be cast to javax.sql.DataSource  
      at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDataSource(LocalManagedConnectionFactory.java:635)  
      ... 37 more  

First of all: wrong hibernate settings in persistance.xml. I went to google and took ones for Postgres:
 <?xml version="1.0" encoding="UTF-8"?>  
   
 <persistence version="2.1"  
        xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="  
     http://xmlns.jcp.org/xml/ns/persistence  
     http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">  
   <persistence-unit name="postgres">  
     <!-- If you are running in a production environment, add a managed  
       data source, this example data source is just for development and testing! -->  
     <!-- The datasource is deployed as WEB-INF/greeter-quickstart-ds.xml,  
       you can find it in the source at src/main/webapp/WEB-INF/greeter-quickstart-ds.xml -->  
     <jta-data-source>java:jboss/datasources/PostgresDS</jta-data-source>  
     <!--Next is for version 9.4 and higher -->
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>  
     <properties>  
      <!--  <property name="hibernate.archive.autodetection" value="class" /> -->  
       <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL94Dialect" />  
       <!--  this I comment because I already have my connection registered as a module
       <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />  
       <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5433/cats" />  
       <property name="hibernate.connection.username" value="postgres" />  
       <property name="hibernate.connection.password" value="mei" />  
       Next I setup value of show_sql for false and hb2ddl.auto for "create-drop"-->  
       <property name="hibernate.show_sql" value="false"/>  
       <property name="hibernate.flushMode" value="FLUSH_AUTO" />  
       <property name="hibernate.hbm2ddl.auto" value="create-drop" />  
     </properties>  
   </persistence-unit>  
 </persistence>  
   

Then I need to add some new dependencies to my pom.xml:
     <dependency>  
       <groupId>org.hibernate</groupId>  
       <artifactId>hibernate-entitymanager</artifactId>  
       <version>5.2.4.Final</version>  
     </dependency>   
   
     <dependency>  
       <groupId>org.postgresql</groupId>  
       <artifactId>postgresql</artifactId>  
       <version>9.4.1211</version>  
     </dependency>  

Then I've got a BUILD SUCCESS wiht my project deployment.

Thursday, November 3, 2016

Add another datasource to your WildFly.

To create my own database and deploy in on my WildFly serve I will use PostgreSQL sql system.
I already installed Postgres Server, Pgadmin to manage your database and StackBuilder - all in one from official download page.
I installed two servers: one on the 5432 port and one on the 5433. the last one I started to use and added there new database cats, there I creater a schema list where I put the table cats.
There are two variants how to include database to wildfly server: as deployment or as module. I will add my datasource as a module.

To do it I create a folder named postgres in %WILDFLY_HOME%\modules\system\layers\base\org wherewe create a new folder main and file module.xml inside this folder. Also download jdbs postgres driver
In module.xml I configure access to our driver:
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <module xmlns="urn:jboss:module:1.1" name="org.postgres">  
3:    <resources>  
4:      <resource-root path="postgresql-9.4.1211.jar"/>  
5:    </resources>  
6:    <dependencies>  
7:      <module name="javax.api"/>  
8:      <module name="javax.transaction.api"/>  
9:      <module name="javax.servlet.api" optional="true"/>  
10:    </dependencies>  
11:  </module>  


Then I modify standalone.xml which I can find in %WILDFLY_HOME%\standalone\configuration.
There, between the tags 
 <datasources> </datasources>  
we describe our custom datasource:
1:      <subsystem xmlns="urn:jboss:domain:datasources:4.0">  
2:        <datasources>  
3:          <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">  
4:            <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>  
5:            <driver>h2</driver>  
6:            <security>  
7:              <user-name>sa</user-name>  
8:              <password>sa</password>  
9:            </security>  
10:          </datasource>  
11:          <datasource jta="false" jndi-name="java:jboss/datasources/PostgresDS" pool-name="PostgresDS" enabled="true" use-java-context="true">  
12:            <connection-url>jdbc:postgresql://localhost:5433/cats</connection-url>  
13:            <connection-property name="cats">dictionary</connection-property>  
14:            <driver>postgres</driver>  
15:            <security>  
16:                 <user-name>postgres</user-name>  
17:                 <password>postgres</password>  
18:            </security>  
19:          </datasource>  
20:          <drivers>  
21:            <driver name="postgres" module="org.postgres">  
22:                 <datasource-class>org.postgresql.Driver</datasource-class>  
23:                 <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>  
24:            </driver>  
25:                 <driver name="h2" module="com.h2database.h2">  
26:             <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>  
27:            </driver>  
28:          </drivers>  
29:        </datasources>  
30:      </subsystem>  

Here we see both: ExampleDS and our custom PostgreDS. There I combined datasources separately from drivers declarations and those declarations I put at the end of the datasources div as you can see.
Connection URL is where our datasource is. Connection-property we need since wildfly 10.1.0, here we set up the name of our database and the name of our application.

Now if we  start our server
Open your command prompt:

      a. Push WIN ÿ button on your keyboard, in appeared window type "cmd", then ENTER.
     or

      b. Go "Start" -> Search -> type "cmd" -> choose "Command prompt".
then type
%WILDFLY_HOME%\bin\standalone.bat
we will find our new datasource:
Next time I will try to lookup data from this datasource to my servlett and update datasource from application.

How to post code in your blogspot?

This is a source to make your code formatted as you need

Monday, October 31, 2016

Create an easy Servlet

Today I will try to create an asy servlet to run at my server. To encapsulate buisness logic (how my fields and variables will interact with each other) I will use CDI beans. We will (use EJB to) manually control transactions and JSF to display view.

Our program is to manage cats in cat shelter where we should add the cat if we found one, delete one from the list if it found it's house and to see the full list of cats in the shelter if somebody wants to choose one.

Every cat is going to be entity for us and this entity we want to store in the relational database and to map entity there we're using JPA. It is the popular API for the management of persistence and object/relationalmapping with Java EE, we will stay with it.

Before we started, here is working code you can download and try. If you have any problems feel free to ask in comments.
Let's see what we need in pom.xml (which we place in the root directory of our project):
1:  <?xml version="1.0" encoding="UTF-8"?> <!-- standalone="no"?> -->  
2:  <project xmlns="http://maven.apache.org/POM/4.0.0"  
3:       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4:       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
5:    <modelVersion>4.0.0</modelVersion>  
6:    <groupId>catchelter</groupId>  
7:    <artifactId>catshelter-java</artifactId>  
8:    <version>1.0-SNAPSHOT</version>  
9:    <packaging>war</packaging>  
10:    <properties>  
11:      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
12:      <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>  
13:      <version.jboss.spec.javaee.7.0>1.0.3.Final</version.jboss.spec.javaee.7.0>  
14:      <version.war.plugin>3.0.0</version.war.plugin>  
15:      <maven.compiler.target>1.8</maven.compiler.target>  
16:      <maven.compiler.source>1.8</maven.compiler.source>  
17:    </properties>  
18:    <dependencyManagement>  
19:      <dependencies>  
20:        <!-- JBoss version  
21:           JavaEE 7  
22:           Any d-s from org.jboss.spec-->  
23:        <dependency>  
24:          <groupId>org.jboss.spec</groupId>  
25:          <artifactId>jboss-javaee-7.0</artifactId>  
26:          <version>${version.jboss.spec.javaee.7.0}</version>  
27:          <type>pom</type>  
28:          <scope>import</scope>  
29:        </dependency>  
30:      </dependencies>  
31:    </dependencyManagement>  
32:    <dependencies>  
33:      <!-- CDI API Context and Dependency injection-->  
34:      <dependency>  
35:        <groupId>javax.enterprise</groupId>  
36:        <artifactId>cdi-api</artifactId>  
37:        <scope>provided</scope>  
38:      </dependency>  
39:      <!-- Common annotation API (JRS-250)-->  
40:      <dependency>  
41:        <groupId>org.jboss.spec.javax.annotation</groupId>  
42:        <artifactId>jboss-annotations-api_1.2_spec</artifactId>  
43:        <scope>provided</scope>  
44:      </dependency>  
45:      <!-- JSF API Java Server Faces-->  
46:      <dependency>  
47:        <groupId>org.jboss.spec.javax.faces</groupId>  
48:        <artifactId>jboss-jsf-api_2.2_spec</artifactId>  
49:        <scope>provided</scope>  
50:      </dependency>  
51:      <!-- JTA - transaction api-->  
52:      <!-- JPA Java Persistence api-->  
53:      <dependency>  
54:        <groupId>org.hibernate.javax.persistence</groupId>  
55:        <artifactId>hibernate-jpa-2.1-api</artifactId>  
56:        <scope>provided</scope>  
57:      </dependency>  
58:      <!--JPA -->  
59:      <dependency>  
60:        <groupId>org.jboss.spec.javax.transaction</groupId>  
61:        <artifactId>jboss-transaction-api_1.2_spec</artifactId>  
62:        <scope>provided</scope>  
63:      </dependency>  
64:      <!--EJB API-->  
65:      <dependency>  
66:        <groupId>org.jboss.spec.javax.ejb</groupId>  
67:        <artifactId>jboss-ejb-api_3.2_spec</artifactId>  
68:        <scope>provided</scope>  
69:      </dependency>  
70:    </dependencies>  
71:    <build>  
72:      <finalName>${project.artifactId}</finalName>  
73:      <plugins>  
74:        <plugin>  
75:          <artifactId>maven-war-plugin</artifactId>  
76:          <version>${version.war.plugin}</version>  
77:          <configuration>  
78:            <failOnMissingWebXml>false</failOnMissingWebXml>  
79:          </configuration>  
80:        </plugin>  
81:        <plugin>  
82:          <groupId>org.wildfly.plugins</groupId>  
83:          <artifactId>wildfly-maven-plugin</artifactId>  
84:          <version>${version.wildfly.maven.plugin}</version>  
85:          <configuration>  
86:            <hostname>${wildfly-hostname}</hostname>  
87:            <port>9991</port>  
88:            <username>${wildfly-username}</username>  
89:            <password>${wildfly-password}</password>  
90:          </configuration>  
91:        </plugin>  
92:      </plugins>  
93:    </build>  
94:  </project>  
Note we configured wildfly-maven-plugin with our local configuration, as said in previous post.

To include CDI and JSF to our project we need to add empty bean beans.xml to directory %PROJECT%/src/main/webapp to make wildfly look for beans in this application and accept the CDI.
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <beans  
3:      xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
4:      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
5:      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   
6:             http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"  
7:      bean-discovery-mode="all">  
8:  </beans>  

Also we have faces-config.xml in the same place, we use a standardized version JSF-2.0, that's why we leave default configurations.
1:  <?xml version='1.0' encoding='UTF-8'?>  
2:  <faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
3:    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4:    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee   
5:    http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">  
6:  </faces-config>  

What is very nice - we can add all the default configurations of beans.xml and faces-config.xml by one click if we use Intellij IDE? which I really like.
  
Same folder we will add web.xml where we configure start page where we will display the information.
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <web-app version="3.1"  
3:       xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
4:       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
5:       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">  
6:    <servlet>  
7:      <servlet-name>Faces Servlet</servlet-name>  
8:      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
9:      <load-on-startup>1</load-on-startup>  
10:    </servlet>  
11:    <servlet-mapping>  
12:      <servlet-name>Faces Servlet</servlet-name>  
13:      <url-pattern>*.xhtml</url-pattern>  
14:    </servlet-mapping>  
15:    <session-config>  
16:      <session-timeout>  
17:        30  
18:      </session-timeout>  
19:    </session-config>  
20:    <welcome-file-list>  
21:      <welcome-file>main.xhtml</welcome-file>  
22:    </welcome-file-list>  
23:  </web-app>  

Each cat will be an Entity, for it we create an Entity class in %PROGECT%/main/java/org/jboss/cats/domain


1:  package org.jboss.cats.domain;  
2:  import javax.persistence.Column;  
3:  import javax.persistence.Entity;  
4:  import javax.persistence.GeneratedValue;  
5:  import javax.persistence.Id;  
6:  import javax.persistence.Table;  
7:  /**  
8:   * Created by Anna Leonenko on 30/10/2016.  
9:   */  
10:  @Entity  
11:  @Table(name = "Users")  
12:  public class Cat {  
13:    @Id  
14:    @GeneratedValue  
15:    private Long id;  
16:    @Column(unique = true)  
17:    private String name;  
18:    private String color;  
19:    private int age;  
20:    private String fluffy;  
21:    public String isFluffy() {  
22:      return fluffy;  
23:    }  
24:    public int getAge() {  
25:      return age;  
26:    }  
27:    public Long getId() {  
28:      return id;  
29:    }  
30:    public String getColor() {  
31:      return color;  
32:    }  
33:    public String getName() {  
34:      return name;  
35:    }  
36:    public void setAge(int age) {  
37:      this.age = age;  
38:    }  
39:    public void setColor(String color) {  
40:      this.color = color;  
41:    }  
42:    public void setFluffy(String fluffy) {  
43:      this.fluffy = fluffy;  
44:    }  
45:    public void setName(String name) {  
46:      this.name = name;  
47:    }  
48:  }  
We wired the Table "Cats" there by special annotation, set primary key which is String name here and set generated value id.

Then we create a class to manage our datasource (let's use ExampleDS database for now).
First declare the interface at %PROGECT%/main/java/org/jboss/cats/domain:
1:  package org.jboss.cats.domain;  
2:  public interface CatDao {  
3:    Cat getForName(String name);  
4:    void addCat(Cat cat);  
5:  }  

Then, implement it in same folder:
1:  package org.jboss.cats.domain;  
2:  import javax.inject.Inject;  
3:  import javax.persistence.EntityManager;  
4:  import javax.transaction.SystemException;  
5:  import javax.transaction.UserTransaction;  
6:  public class ManagedBeanCatDao implements CatDao {  
7:    @Inject  
8:    private EntityManager entityManager;  
9:    @Inject  
10:    UserTransaction utx;  
11:    @Override  
12:    public Cat getForName(String name) {  
13:      return null;  
14:    }  
15:    public void addCat (Cat cat) {  
16:      try {  
17:        try {  
18:          utx.begin();  
19:          entityManager.persist(cat);  
20:        } finally {  
21:          utx.commit();  
22:        }  
23:      } catch (Exception e) {  
24:        try {  
25:          utx.rollback();  
26:        } catch (SystemException se) {  
27:          throw new RuntimeException(se);  
28:        }  
29:        throw new RuntimeException(e);  
30:      }  
31:    }  
32:  }  

For the begining it's enough for us to implement just one of the methods, then we will add more specific code.

To declare Entity manager we create class Resources in %PROGECT%/main/java/org/jboss/cats/:
1:  package org.jboss.cats;  
2:    
3:  import javax.enterprise.context.RequestScoped;  
4:  import javax.enterprise.inject.Produces;  
5:  import javax.faces.context.FacesContext;  
6:  import javax.persistence.EntityManager;  
7:  import javax.persistence.PersistenceContext;  
8:    
9:  public class Resources {  
10:    @PersistenceContext  
11:    @Produces  
12:    private EntityManager em;  
13:    
14:    
15:    @Produces  
16:    @RequestScoped  
17:    public FacesContext getFacesContext() {  
18:      return FacesContext.getCurrentInstance();  
19:    }  
20:  }  
21:    
Now annotation @Inject is avalibale for us.

In %PROGECT%/main/resources/META-INF we create persistence.xml to include datasource:

1:  <?xml version="1.0" encoding="UTF-8"?>  
2:    
3:  <persistence version="2.1"  
4:         xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
5:         xsi:schemaLocation="  
6:      http://xmlns.jcp.org/xml/ns/persistence  
7:      http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">  
8:    <persistence-unit name="primary">  
9:      <!-- If you are running in a production environment, add a managed  
10:        data source, this example data source is just for development and testing! -->  
11:      <!-- The datasource is deployed as WEB-INF/greeter-quickstart-ds.xml,  
12:        you can find it in the source at src/main/webapp/WEB-INF/greeter-quickstart-ds.xml -->  
13:      <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>  
14:      <properties>  
15:        <!-- Properties for Hibernate -->  
16:        <property name="hibernate.hbm2ddl.auto" value="create-drop" />  
17:        <property name="hibernate.show_sql" value="false" />  
18:      </properties>  
19:    </persistence-unit>  
20:  </persistence>  

Almost all is done, now we need to add a page controller which will generate dynamic content of the page. Put it in the folder %PROGECT%/main/java/org/jboss/cats/web:


1:  package org.jboss.cats.web;  
2:    
3:  import org.jboss.cats.domain.Cat;  
4:  import org.jboss.cats.domain.CatDao;  
5:    
6:  import javax.enterprise.context.RequestScoped;  
7:  import javax.enterprise.inject.Produces;  
8:  import javax.faces.application.FacesMessage;  
9:  import javax.faces.context.FacesContext;  
10:  import javax.inject.Inject;  
11:  import javax.inject.Named;  
12:    
13:  @Named  
14:  @RequestScoped  
15:  public class AddController {  
16:    
17:    @Inject  
18:    private FacesContext facesContext;  
19:    
20:    @Inject  
21:    private CatDao catDao;  
22:    
23:    @Named  
24:    @Produces  
25:    @RequestScoped  
26:    private Cat newCat = new Cat();  
27:    
28:    public void add() {  
29:      try {  
30:        catDao.addCat(newCat);  
31:        String message = "A new user with id " + newCat.getId() + " has been created successfully";  
32:        facesContext.addMessage(null, new FacesMessage(message));  
33:      } catch (Exception e) {  
34:        String message = "An error has occured while creating the user (see log for details)";  
35:        facesContext.addMessage(null, new FacesMessage(message));  
36:      }  
37:    }  
38:  }  

And  we are done with the backend of our application. The frontend is going to be very simple. In
%PROJECT%/src/main/webapp folder we create template.xhtml (we need it for future when we add more pages) and main.xhtml to show our output form:

template.xhtml:
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml"  
    xmlns:h="http://xmlns.jcp.org/jsf/html"  
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"  
    xmlns:f="http://xmlns.jcp.org/jsf/core">  
 <f:view>  
   <h:outputLabel value="Hello, world"/>  
 </f:view>  
   
 <head>  
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  
   <title>Cat shelter</title>  
   <ui:insert name="head" />  
 </head>  
   
 <body>  
   
 <div id="container">  
   <div id="header"></div>  
   
   <div id="sidebar"></div>  
   
   <div id="content">  
     <ui:insert name="content" />  
   </div>  
   
   <br style="clear: both" />  
 </div>  
   
 </body>  
 </html>  

main.xhtml:


 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml"  
    xmlns:h="http://xmlns.jcp.org/jsf/html"  
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"  
    xmlns:f="http://xmlns.jcp.org/jsf/core">  
   
   
 <ui:composition template="template.xhtml">  
   <ui:define name="content">  
     <h:messages />  
     <h:form>  
       <h:panelGrid columns="3">  
         <h:outputLabel for="name">Enter cat's name:</h:outputLabel>  
         <h:inputText id="name" value="#{newCat.name}" />  
         <h:message for="name" />  
   
         <h:outputLabel for="color">Enter color:</h:outputLabel>  
         <h:inputText id="color" value="#{newCat.color}" />  
         <h:message for="color" />  
   
         <h:outputLabel for="fluffy">Enter age:</h:outputLabel>  
         <h:inputText id="fluffy" value="#{newCat.age}" />  
         <h:message for="fluffy" />  
   
       </h:panelGrid>  
       <h:commandButton action="#{addController.add}"  
                value="Add User" />  
     </h:form>  
     <h:link outcome="/allcats.xhtml">See the cat's we have!</h:link>  
   </ui:define>  
 </ui:composition>  
 </html>  

Let's deploy our application to WildFly server.
Open command prompt and go to the project's root directory. There type:

mvn package wildfly:deploy

The result we can see at the adress: http://localhost:8081/catshelter-java/main.xhtml
Here is working code you can download and try. If you have any problems feel free to ask in comments.

See you here next time to implement ManagingBean and to add more functionality to our cat's shelter application!

Friday, October 21, 2016

WildFly 10. Getting started on Windows

                 WildFly is a JBOSS application server which is one of the most popular frameworks to run your web application and to connect database there.

I'm using Windows 10 home edition, but I'm prettu sure same steps are going to work with Windows 7 and Windows 8 as well.

To setup WildFly:
1. Go to the official download page;
2. Choose the latest version .zip (for windows);
3. Unpack it whereever you want in your computer (keep remember where).
4. Install Java Development Kit (JDK) which wildfly uses
5. (Optional) It's useful to set up enviroment variable for your wildfly directory %WILDFLY_HOME% and %JAVA_HOME% - path to your jdk folder. I will use those variables here in the text if I need to show where the file is.

Now we could be ready to start the server, but I highly recomment to make some additional steps.
WildFly opens a new port (8080) where it runs and the other port (9990) where it runs the application.

There are two default ports for most of applications you are running everytime (for example I had a NIVIDIA driver at 9990 port which supported my videocard, so I couldn't relocate it.

(How to know which ports are busy)

That's why my preposition is to change default wildfly portsat the very beginning just for sure.

At the %WILDFLY_HOME%\standalone\configuration we can find config file standalone.xml.
If we open it to modify we can find there:

        <socket-binding name="http" port="${jboss.http.port:8080}"/>

and

        <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>

All we need is to change 8080 for 8081 and 9990 for 9991 (or any ports which are not open by the other applications). We change port numbers right here in the file and save changings.

Also we need to modify same way

%WILDFLY_HOME%\domain\configuration\host.xml

and

%WILDFLY_HOME%\domain\configuration\host-master.xml

There we find only the 9990 settings.

Now we are completely ready to start the server. For this:
1. From command prompt type

%WILDFLY_HOME%\bin\standalone.bat

2. Or from file system go %WILDFLY_HOME%\bin\ , then run standalone.bat by double mouse clicking.


After all you have an access to the http:\\localhost:8081.
There you can find a link "Administration console" where you cal also access by the link http://localhost:9991/console/

For now there you will se the ERROR window. It happened because we didn't setup any user yet.
To do it we can use provided script add-user.bat in \bin folder

Open new command prompt window (the same as previous) and type there

%WILDFLY_HOME%\bin\add-user.bat

Command prompt is gonna ask
What type of user do you wish to add?
 a) Management User (mgmt-users.properties)
 b) Application User (application-users.properties)
(a):

For now we need a management user so we push ENTER

Then we follow the instructions and setting up username

manager

And password

manager

It's enough for today and now we can follow the link for "Administration console" again. This time browser's asking us for username and password and if we remember both correct, we are able to see the main administration menue.






















To stop the server we can type CTRL + c in command prompt, then type Y.

How to write service application to run on this sever will see in the next posts.

Monitoring ports from the Windows command prompt

You can also use netstat -noa | find "port number" and then tasklist | findstr PID_of_process to check which process uses your ports.

To open your command prompt:
1. Push WIN ÿ button on your keyboard, in appeared window type "cmd", then ENTER.
or
2. Go "Start" -> Search -> type "cmd" -> choose "Command prompt".

To check your ports:

In any directory:

1. If you want to see the full list of your connections this moment, type

netstat -noa 


2. If you know the port number you want to see if it's busy 

netstat -noa | find "port number"

3. If you want to know which process takes your port
  3. 1. Take a PID of this process as shown above
  3. 2.  Push CTRL + ALT + DEL, choose "Task manager"
  3. 3.  Choose "more"
  3. 4.  Press the head of the "ID" column to sort all the running processes by their ID and find the goal process by it's PID (which is the ID in this table). 
  3. 5. Here you can also stop the process if it's not system.



Also you can kill any process from the command prompt typing 


taskkill /F /PID 1196

Monitoring ports from the Windows command prompt

You can also use netstat -noa | find "port number" and then tasklist | findstr PID_of_process to check which process uses your ports.

To open your command prompt:
1. Push WIN ÿ button on your keyboard, in appeared window type "cmd", then ENTER.
or
2. Go "Start" -> Search -> type "cmd" -> choose "Command prompt".

To check your ports:

In any directory:

1. If you want to see the full list of your connections this moment, type

netstat -noa 


2. If you know the port number you want to see if it's busy 

netstat -noa | find "port number"

3. If you want to know which process takes your port
  3. 1. Take a PID of this process as shown above
  3. 2.  Push CTRL + ALT + DEL, choose "Task manager"
  3. 3.  Choose "more"
  3. 4.  Press the head of the "ID" column to sort all the running processes by their ID and find the goal process by it's PID (which is the ID in this table). 
  3. 5. Here you can also stop the process if it's not system.

How to setup enviroment variable

  5. 1. Go System ->  Advanced settings -> Enviroment variables
  5. 2. Click New, name %WILDFLY_HOME% and put the path to your wildfly directory there.

Saturday, January 9, 2016

Line following robot

Yesterday I finished my Line Follower Robot on Arduino.
As the main controller I took an Arduino Uno board
I have choosen this board because of the multiple shields I can connect to it. One of them is l298p Motor Shield for driving my DC motors:
As the motors I've took the cheapest ones with the 1:25 reductor because I didn't really care how fast my robot will be, I needed just principle working one.
3-12 V and 120 rounds per second.
The other thing I needed is the optosensor which sees the line on the floor.
I've choosen Pololu - QTR-1A Reflectance Sensor
Again, because it's cheap and easy.
To connect all together I took one more shield and it was IO Expansion Shield For Arduino[V7].
And, of course, I needed some board to put everything on it. I've decided to make it by myself by laser cutting from the piece of wood (was not the best idea as I researched later).
There is what I've done:
I put the arduino board on my piece of wood, then connected a motor shield. Connecting my motors took some time because I had to be sure that the Motor 1 is the right one (if I look at the picture I've published), the Motor 2 at the left and both rolling forward (backward if I look this picture). For that experiments I wrote simple example with Arduino IDE which I previously installed on my computer.
This code you can find here.
Then I made a sensor test simple application to know what my sensors return.
I put my sensors on A4 and A5 pins on my top shield watching when I have Ground (squared pin), Vin (connected to 5 v) and Vout (A4 and A5).

I figured out that when it's totally dark (when I push the sensot with my finger it returns 1024 and when it's bright (when I show sensor my monitor white background or my daylight lamp) it's around 10.

That's why I used those values for my calibration function which I wrote to make my robot know how light is my white floor and how dark is the line. I set previos values for light the blackest one and the lightest one for black. Then I moved the robot in my program and said it to use any "lighter" value for light and any "darker" for black.



To make my robot to see the line I wrote a Proportional Regulator using my sensor values and my middle gray values.
k there is a proportional coefficient which I guessed (firstly I've tried some more values and watched how it works).
Here is the full code for my robot.
And here is it :)