Archive for the ‘java’ Category

Usando Maven da maneira fácil


26 Jul

Introdução

Apache Maven é um projeto de software e ferramentas de compreensão. Baseado no conceito de um Project Object Model (POM), o Maven pode gerenciar um projeto da construção, elaboração de relatórios e documentação a partir de uma peça central de informações. Maven pode fazer mais do que apenas construir software – mas pode ajudar com os testes, executar aplicações web e produzir relatórios sobre os projetos, bem como qualquer número de outras tarefas previstas pelo plug-ins. Esta documentação é para aqueles que têm o código fonte num projeto que deseja usar com o Maven, e gostaria de saber como usar Maven para construí-lo (ou executar outras tarefas comuns). Essa documentação é útil para novos usuários Maven. Download

Instalação do Maven

Maven é um aplicativo Java, então você deve ter necessariamente o Java instalado no seu ambiente. Instale (unzip) num diretório de sua preferência (eu gosto /opt). Após a instalação, e colocar o ${maven}/bin no path, crie a variável de ambiente M2_HOME apontando pro Maven.

set M2_HOME=c:\Java\apache-maven-3.0.2
set PATH=%M2_HOME%\bin;%PATH%

ou

export M2_HOME=/opt/apache-maven-3.0.2
PATH=$M2_HOME/bin:$PATH

Para testar, use o comando abaixo numa console:

mvn --version

Ela deve imprimir a sua versão do Maven, por exemplo:

Apache Maven 3.0 (r1004208; 2010-10-04 08:50:56-0300)
Java version: 1.6.0_23
Java home: /opt/jdk1.6.0_23/jre
Default locale: pt_BR, platform encoding: UTF-8
OS name: "linux" version: "2.6.35-25-generic-pae" arch: "i386" Family: "unix"

Configurando o Maven

Por default o Maven será executado com padrões sensíveis pré-configurados, sendo assim você pode ir rodando direto. No entanto, se você estiver operando em um ambiente restrito ou atrás de um firewall, talvez seja necessário preparar-se para executar o Maven, uma vez que requer acesso de gravação para o diretório home: a) ~/.m2 no Linux e Mac OS X b) C:\Documents and Settings\username\.m2 no Windows) e acesso à rede para baixar as dependências binárias (maven repo).

A Configuração do Maven ocorre em três níveis

Projeto – configuração mais estática ocorre no pom.xml do projeto

Instalação – esta configuração é adicionada uma única vez para uma instalação Maven

Usuário – esta é a configuração específica para um determinado usuário A separação é muito clara – o projeto define a informação que se aplica ao projeto, não importa quem está construindo, enquanto as outras duas definições, para o ambiente atual.

Nota: a instalação e configuração do usuário não podem ser usados para adicionar informações sobre o projeto compartilhado, como por exemplo, a criação, ou para toda a empresa. Para isso, você deve ter em seus projetos uma forma de herdar de um projeto pai, um pom.xml para toda a empresa. Você pode especificar a configuração de usuário em ${user.home}/.m2/settings.xml. A referência completa para o arquivo de configuração está disponível aqui. Esta seção irá mostrar como fazer algumas pequenas configurações comuns. Observe que o arquivo não é necessário, nesse caso, a configuração padrão será utilizada se não esse não for encontrado.

O POM

O arquivo pom.xml é o núcleo de uma configuração do projeto no Maven. É o único arquivo de configuração que contém a maioria das informações necessárias para construir um projeto no jeito que você quer. O POM é enorme e pode ser assustador em sua complexidade, mas não é necessário entender todos os meandros, apenas usá-lo eficazmente. O POM do projeto é:

<project
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0</modelversion>
  <groupid>com.mycompany.app</groupid>
  <artifactid>my-app</artifactid>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  Maven Quick Start Archetype
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupid>junit</groupid>
      <artifactid>junit</artifactid>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>




				
				

Securing JBOSS 4.2.x JMX and Web Console, and JBoss Web Service


08 Apr

Always I want to protect the jmx-console and web-console on JBoss 4.2.x I look forward something that works effectivelly… let’s go.

After installing the JBOSS Application Server, the jmx console can be accessed by anybody without providing any username/password. This is a big security risk as anybody can perform changes though the jmx and web console. Setting up basic username/password security for the jboss jmx/web console can be accomplished by performing the following steps on the JBoss Application Server.

  • Edit $JBOSS_HOME/server/all/conf/props/jmx-console-users.properties to add jmx console users. Replace “all” with your JBOSS profile name. The syntax to add users is username=password. By default admin user would be available in this file with admin as password.
  • o provide admin privileges on jmx and web console to the newly created user, edit jmx-console-roles.properties file available in $JBOSS_HOME/server/all/conf/props folder and add username=JBossAdmin.
  • Edit $JBOSS_HOME/server/all/deploy/jmx-console.war/WEB-INF/jboss-web.xml file and uncomment the security domain as shown below.
<jboss-web>
  <security-domain>java:/jaas/jmx-console</security-domain>
</jboss-web>
  • Edit $JBOSS_HOME/server/all/deploy/jmx-console.war/WEB-INF/web.xml file and uncomment the security constraint as shown below.
<security-constraint>
  <web-resource-collection>
    <web-resource-name>HtmlAdaptor</web-resource-name>
    <description>An example security config that only allows users with the role JBossAdmin to access the HTML JMX console web application</description>
    <url-pattern>/*</url-pattern>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
  </web-resource-collection>
  <auth-constraint>
    <role-name>JBossAdmin</role-name>
  </auth-constraint>
</security-constraint>
  • The location, path or name of the users and roles configuration files i.e. jmx-console-users.properties or jmx-console-roles.properties can be changed by editing $JBOSS_HOME/server/all/conf/login-config.xml file. Sample configuration is given below.
<application-policy name=”jmx-console”>
  <authentication>
    <login-module code=“org.jboss.security.auth.spi.UsersRolesLoginModule” flag=”required”>
      <module-option name=”usersProperties”>props/jmx-console-users.properties</module-option>
      <module-option name=”rolesProperties”>props/jmx-console-roles.properties</module-option>
    </login-module>
  </authentication>
</application-policy>
  • Edit $JBOSS_HOME/server/all/deploy/management/console-mgr.sar/ web-console.war/WEB-INF/jboss-web.xml file and remove the comment of the security domain as shown below.
<jboss-web>
  <security-domain>java:/jaas/web-console</security-domain>
  <depends>jboss.admin:service=PluginManager</depends>
</jboss-web>
  • Edit $JBOSS_HOME/server/all/deploy/management/console-mgr.sar/ web-console.war/WEB-INF/web.xml file and remove the comment of the security constraint as shown below.
<security-constraint>
  <web-resource-collection>
    <web-resource-name>HtmlAdaptor</web-resource-name>
      <description>An example security config that only allows users with the role JBossAdmin to access the HTML JMX console web application
      </description>
      <url-pattern>/*</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
  </web-resource-collection>
  <auth-constraint>
  <role-name>JBossAdmin</role-name>
</auth-constraint>
</security-constraint>
  • Finally, let protect JBoss web service console…
  • Edit $JBOSS_HOME/server/all/deploy/jbossws.sar/jbossws-context.war/WEB-INF/jboss-web.xml file and remove the comment of the security domain as shown below.
<jboss-web>
  <!-- A security domain that restricts access -->
  <security-domain>java:/jaas/JBossWS</security-domain>
  <context-root>jbossws</context-root>
</jboss-web>
  • Edit $JBOSS_HOME/server/all/deploy/jbossws.sar/jbossws-context.war/WEB-INF/web.xml file and remove the comment of the security constraint as shown below.
   <security-constraint>
     <web-resource-collection>
       <web-resource-name>ContextServlet</web-resource-name>
       <description>An example security config that only allows users with the
         role 'friend' to access the JBossWS console web application
       </description>
       <url-pattern>/*</url-pattern>
       <http-method>GET</http-method>
       <http-method>POST</http-method>
     </web-resource-collection>
     <auth-constraint>
       <role-name>friend</role-name>
     </auth-constraint>
   </security-constraint>
  • The location, path or name of the users and roles configuration files i.e. jbossws-users.properties or jbossws-roles.properties can be changed by editing $JBOSS_HOME/server/all/conf/login-config.xml file. Sample configuration is given below.
    <application-policy name="JBossWS">
      <authentication>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
          flag="required">
          <module-option name="usersProperties">props/jbossws-users.properties</module-option>
          <module-option name="rolesProperties">props/jbossws-roles.properties</module-option>
          <!-- module-option name="unauthenticatedIdentity">anonymous</module-option -->
        </login-module>
      </authentication>
    </application-policy>
  • Restart JBOSS.

Note: this post is result from cut/copy/insert/modify from some others posts provided from jboss community; it belongs to us. Thanks all!

    Insert date value in PreparedStatement


    06 Apr

    A simple table script in Oracle database.

    CREATE TABLE DBUSER (
      USER_ID       NUMBER (5)    NOT NULL,
      USERNAME      VARCHAR2 (20)  NOT NULL,
      CREATED_BY    VARCHAR2 (20)  NOT NULL,
      CREATED_DATE  DATE          NOT NULL,
      PRIMARY KEY ( USER_ID )
     )

    No idea how to insert current date value, e.g. “04/04/2011” into “CREATED_DATE” field, via JDBC PreparedStatement.

    String insertTableSQL = "INSERT INTO DBUSER"
    		+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
    		+ "(?,?,?,?)";
    preparedStatement = dbConnection.prepareStatement(insertTableSQL);
    preparedStatement.setDate(4, ???);

    Solution

    The “preparedStatement.setDate()” method is accept a java.sql.Date parameter, so, you have to convert from java.util.Date to java.sql.Date.

    For example, create a method to return current date, and convert it java.sql.Date :

    private static java.sql.Date getCurrentDate() {
        java.util.Date today = new java.util.Date();
        return new java.sql.Date(today.getTime());
    }

    And set the returned date via preparedStatement.setDate().

    String insertTableSQL = "INSERT INTO DBUSER"
    	+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
    	+ "(?,?,?,?)";
    preparedStatement = dbConnection.prepareStatement(insertTableSQL);
    preparedStatement.setDate(4, getCurrentDate());

    Done.

     

    JDBC PrepareStatement example – Create a table


    05 Apr

    Here’s an example to show you how to create a table in database via JDBC PrepareStatement. To issue a create statement, calls the PrepareStatement.executeUpdate() method like this :

    PreparedStatement preparedStatement = dbConnection.prepareStatement(createTableSQL);
    // execute CREATE SQL stetement
    preparedStatement.executeUpdate();

    Full example…

    package br.com.ziben.jdbc;
    
    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class JDBCPreparedStatementCreateExample {
    
    	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
    	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:ZIBEN";
    	private static final String DB_USER = "user";
    	private static final String DB_PASSWORD = "password";
    
    	public static void main(String[] argv) {
    		try {
    			createTable();
    		} catch (SQLException e) {
    			System.out.println(e.getMessage());
    		}
    	}
    	private static void createTable() throws SQLException {
    		Connection dbConnection = null;
    		PreparedStatement preparedStatement = null;
    
    		String createTableSQL = "CREATE TABLE DBUSER1("
    				+ "USER_ID NUMBER(5) NOT NULL, "
    				+ "USERNAME VARCHAR(20) NOT NULL, "
    				+ "CREATED_BY VARCHAR(20) NOT NULL, "
    				+ "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
    				+ ")";
    		try {
    			dbConnection = getDBConnection();
    			preparedStatement = dbConnection.prepareStatement(createTableSQL);
    
    			System.out.println(createTableSQL);
    
    			// execute create SQL stetement
    			preparedStatement.executeUpdate();
    
    			System.out.println("Table \"dbuser\" is created!");
    
    		} catch (SQLException e) {
    			System.out.println(e.getMessage());
    		} finally {
    			if (preparedStatement != null) {
    				preparedStatement.close();
    			}
    			if (dbConnection != null) {
    				dbConnection.close();
    			}
    		}
    	}
    
    	private static Connection getDBConnection() {
    		Connection dbConnection = null;
    
    		try {
    			Class.forName(DB_DRIVER);
    		} catch (ClassNotFoundException e) {
    			System.out.println(e.getMessage());
    		}
    
    		try {
    			dbConnection = DriverManager.getConnection(
                                DB_CONNECTION, DB_USER,DB_PASSWORD);
    			return dbConnection;
    		} catch (SQLException e) {
    			System.out.println(e.getMessage());
    		}
    		return dbConnection;
    	}
    }
    
    Result

    A table named “DBUSER” is created.

    CREATE TABLE DBUSER(
       USER_ID NUMBER(5) NOT NULL,
       USERNAME VARCHAR(20) NOT NULL,
       CREATED_BY VARCHAR(20) NOT NULL,
       CREATED_DATE DATE NOT NULL,
       PRIMARY KEY (USER_ID)
    )
    
    TABLE "dbuser" IS created!

     

    Connect to Oracle DB via JDBC driver – Java


    18 Jan

    Oracle JDBC example in Java.

    Download Oracle JDBC
    Get Oracle JDBC driver here – ojdbcxxx.jar
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection connection = null;
    connection = DriverManager.getConnection(
    	"jdbc:oracle:thin:@localhost:1521:ziben","username","password");
    connection.close();
    See a full example to show you how to connect to Oracle database via Oracle JDBC driver in Java.

    File : OracleJDBC.java

    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.SQLException;
     
    public class OracleJDBC {
     
    	public static void main(String[] argv) {
     
    		System.out.println("-------- Oracle JDBC Connection Testing ------------");
     
    		try {
     			Class.forName("oracle.jdbc.driver.OracleDriver");
     		} catch (ClassNotFoundException e) {
     			System.out.println("Where is your Oracle JDBC Driver?");
    			e.printStackTrace();
    			return;
    		}
     		System.out.println("Oracle JDBC Driver Registered!");
     
    		Connection connection = null;
     
    		try {
    			connection = DriverManager.getConnection(
    			    "jdbc:oracle:thin:@localhost:1521:ziben","username","password");
     
    		} catch (SQLException e) {
     
    			System.out.println("Connection Failed! Check output console");
    			e.printStackTrace();
    			return;
     		}
     
    		if (connection != null){
    			System.out.println("You made it, take control your database now!");
    		}else{
    			System.out.println("Failed to make connection!");
    		}
    	}
    }

    How to run it?

    Assume OracleJDBC.java is store in “/home/ziben/jdbc-test” folder, together with Oracle JDBC driver (ojdbc6.jar), then run following commands :

    /home/ziben/jdbc-test$ javac OracleJDBC.java
     
    /home/ziben/jdbc-test$ java -cp /home/ziben/jdbc-test/jdbc-test/ojdbc6.jar;/home/ziben/jdbc-test/jdbc-test OracleJDBC
    -------- Oracle JDBC Connection Testing ------------
    Oracle JDBC Driver Registered!
    You made it, take control your database now!
     
    /home/ziben/jdbc-test$

    Ziben IT Solutions

    Should be something about IT


    Switch to our mobile site