Skip to main content

otaviojava's Blog

Easy-Cassandra 1.0.9 Final : With annotations inheritance, jpa and JPQL

Posted by otaviojava on May 26, 2012 at 8:40 AM PDT

Release the newest version of the framework to persist objects in Apache Cassandra in easy way. Among improvement is the JPA annotations, also JPQL.

  JCassandra jCassandra=persistence.createJCassandra("select * from Person");
 List<Person> persons=jCassandra.getResultList();

table 1: sample using JPQL in Easy-Cassandra

This version has the improvements below:

    Supporting at jpa 2.0 annotation
    Query with objects
    Version to retrieve the timestamp of the object
    Using the JPQL
    now supported inheritance


Easy-Cassandra 1.0.8
Easy-Cassandra 1.0.9 (Com JPA anotação)
org.easycassandra.annotations.ColumnFamilyValue

javax.persistence.Entity
org.easycassandra.annotations.ColumnValue
javax.persistence.Column
org.easycassandra.annotations.EmbeddedValue
javax.persistence.Embedded
org.easycassandra.annotations.EnumeratedValue
javax.persistence.Enumerated
org.easycassandra.annotations.KeyValue
javax.persistence.Id
org.easycassandra.annotations.KeyValue equals
true
javax.persistence.GeneratedValue
org.easycassandra.annotations.IndexValue
org.easycassandra.annotations.Index

Also was added functionality for the @Version annotation, its objective is see the timestamp common between fields in objects.

@Entity(name = "autocount")

public class Count implements Serializable {



    private static final long serialVersionUID = 3L;

    

    @Id

    @GeneratedValue

    private BigInteger id;

    

  

    @Column(name = "name")

    private String name;

    

    @Version

    private Long timeStampLong;



    @Version

    private Date timeStampDate;

    

    @Version

    private Calendar timeStampCalendar;



//getter and setter

}

table 3: using the Version annotation

Also you can use inheritance for this you need the @MappedSuperclass annotations in father's class and the subclass allow persist the objects of the super class.

@MappedSuperclass
public class Worker implements Serializable {

private static final long serialVersionUID = -5568409094833637814L;

@Column
private String name;

@Column
private Double salary;
//getter and setter

@Entity
public class Engineer extends Worker {
@Id
private String nickName;

@Column
private String type;

@Column
private String especialization;

//getter and setter
}

Easy-Cassandra 1.0.9: With annotations jpa and JPQL

Posted by otaviojava on April 21, 2012 at 11:02 AM PDT

Release the newest version of the framework to persist objects in Apache Cassandra in easy way. Among improvement is the JPA annotations, also JPQL.

  JCassandra jCassandra=persistence.createJCassandra("select * from Person");
 List<Person> persons=jCassandra.getResultList();

table 1: sample using JPQL in Easy-Cassandra



Easy-Cassandra 1.0.8
Easy-Cassandra 1.0.9 (Com JPA anotação)
org.easycassandra.annotations.ColumnFamilyValue

javax.persistence.Entity
org.easycassandra.annotations.ColumnValue
javax.persistence.Column
org.easycassandra.annotations.EmbeddedValue
javax.persistence.Embedded
org.easycassandra.annotations.EnumeratedValue
javax.persistence.Enumerated
org.easycassandra.annotations.KeyValue
javax.persistence.Id
org.easycassandra.annotations.KeyValue equals
true
javax.persistence.GeneratedValue
org.easycassandra.annotations.IndexValue
org.easycassandra.annotations.Index

Also was added functionality for the @Version annotation, its objective is see the timestamp common between fields in objects.

@Entity(name = "autocount")

public class Count implements Serializable {



    private static final long serialVersionUID = 3L;

    

    @Id

    @GeneratedValue

    private BigInteger id;

    

  

    @Column(name = "name")

    private String name;

    

    @Version

    private Long timeStampLong;



    @Version

    private Date timeStampDate;

    

    @Version

    private Calendar timeStampCalendar;



//getter and setter

}

table 3: using the Version annotation

For show the new resources for framework will do an example with musical albuns that can call for any platform, this way, will use web services. For do this sample will use the Java EE 6 platform. After object modeling like show table 4.

@XmlRootElement
@Entity
public class Album implements Serializable{
   
    @Id
    private Long id;
   
    @Column(name="nameOfAlbum")
    private String name;
   
    @Column 
    private String style;
   
    @Column
    private Calendar release;
   
    @Column
    private Double price;
   
    @Embedded
    private Artist artist;
//getter and setter
    }
@XmlRootElement
public class Artist implements  Serializable{

    /**
     * name of the artist
     */
    @Column(name="nameOfArtist")
    private String name;
   
    /**
     * was born
     */
    @Column
    private String country;
   
    @Enumerated
    private Sex sex;
//getter and setter
}

@XmlRootElement
public enum Sex {
    MALE,FAMALE
}

table 4: class with jpa annotations for Easy-Cassandra

With the class done, now will do the JPQL the Jcassandra's interface extended javax.persistence.Query, so you may use the Query interface if you wat. But there are some method not implement yet.
Other thing important is the way how the Easy-Cassandra manager the classes. It no use xml. To manage use the method addFamilyObject in the EasyCassandraManager Class. You should add the Class before use in the jpql.

@ApplicationScoped
public class PersistenceManagement {
   
   @Produces
   private Persistence persistence;
     
  @Inject
    public void init(){
    persistence=EasyCassandraManager.getPersistence("javabahia", "localhost", 9160);
   
    EasyCassandraManager.addFamilyObject(Album.class);
    }    
}



@RequestScoped
public class PersistenceService {

@Inject   
private Persistence persistence;
  
    public List<Album> findAllAlbum() {
        Query query=persistence.createJCassandra(" select * from Album");
        return query.getResultList();
    }

    public Album findById(Long id) {
        Query query=persistence.createJCassandra(" select * from Album where id =:id");
        query.setParameter("id", id);
        return (Album) query.getSingleResult();
       
    }

    public boolean save(Album album) {
      return  persistence.insert(album);
    }

    public void remove(Long id) {
        persistence.deleteByKeyValue(id, Album.class);
    }

    public String update(Long id, String name, String style, Double price,String nameOfArtis,String country) {
       StringBuilder query=new StringBuilder();
     AuxQuery auxQuery=new AuxQuery();
       String conecion="";
       query.append("update Album set ");
       if(!isnull(name)){
           query.append(conecion);
           query.append(" name =:name ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(style)){
       query.append(conecion);
           query.append(" style =:style ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(price)){
           query.append(conecion);
           query.append(" price =:price ");
           auxQuery.updatable=true;
       }
      
         if(!isnull(country)){
       query.append(conecion);
           query.append(" artist.country =:country ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(nameOfArtis)){
           query.append(conecion);
           query.append(" artist.name =:artist ");
           auxQuery.updatable=true;
       }
      
       query.append(" where id =:id ");
    
       if(!auxQuery.updatable){
            return "nothing is update";
       }
      
       Query jCassandra=persistence.createJCassandra(query.toString());
      
          if(!isnull(name)){
          jCassandra.setParameter("name", name);
       }
       if(!isnull(style)){
   
        jCassandra.setParameter("style", style);
       }
       if(!isnull(price)){
         jCassandra.setParameter("price", price);
       }
       if(!isnull(nameOfArtis)){
     
        jCassandra.setParameter("artist", nameOfArtis);
       }
       if(!isnull(country)){
         jCassandra.setParameter("country", country);
       }
     
       jCassandra.setParameter("id", id);
       return jCassandra.executeUpdate()==1?"executed with sucess":" error in update ";
    
    }
  
    class AuxQuery{
      boolean updatable=false;
   
    }
   
    private boolean isnull(Object object){
   
        return object==null;
    }
   
}

table 5: do jpql in Cassandra

Then, now will create the resource for restful's service like show the table 6.

@Path("/album")
@RequestScoped
public class AlbumResource {
  
    
@Inject   
private PersistenceService persistenceService;


@GET
@Produces(MediaType.TEXT_XML)
public List<Album> getProdutos() {
return persistenceService.findAllAlbum();
}

@Path("{id}")
@GET
@javax.ws.rs.Produces(MediaType.TEXT_XML)
public Album getAlbum(@PathParam("id") long id) {
    return persistenceService.findById(id);
}

@Path("update/{id}")
@GET
@javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
public String updateAlbum(@PathParam("id") Long id ,@QueryParam("name") String name,@QueryParam("style") String style,@QueryParam("price") Double price,@QueryParam("artist") String nameOfArtis,@QueryParam("country") String country) {

    return persistenceService.update(id,name,style,price,nameOfArtis,country);
}
   
   
@POST
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_PLAIN)
public String addAlbum(Album album) {
    boolean sucess=persistenceService.save(album);
    if(sucess){
    return album.getName() + " added!";
    }
   return album.getName() + " not added!";
}



@Path("{id}")
@DELETE
@Produces(MediaType.TEXT_PLAIN)
public String removeAlbum(@PathParam("id") Long id) {
    persistenceService.remove(id);
    return "Album removed.";
}
   

}
table 6: create rest service with JAX-RS

One way for test is using the poster, a plugin for firefox. With this plugin you able do test in all resources (post, get and remove), but just with browser you able test get methods.


list of album
Object album with id equals 1
Object album with id equals N
Insert or update an album wit id equals 12, with name equals Brasil, style eletronic, price 23 and artist me

table 7: sample with rest services.

With this has showed the improvements in new Easy-Cassandra version, the 1.0.9. Was showed the change with annotations, replacement now to jpa, and the jpql improvement that now supported in Easy-Cassandra.

Reference:
Sample rest service rest (AlbumServerRest.rar): https://github.com/otaviojava/Easy-Cassandra/downloads

Poster Plugin Firefox: https://addons.mozilla.org/en-US/firefox/addon/poster/
Easy-Cassandra: https://github.com/otaviojava/Easy-Cassandra/
Download for source and documentation to version 1.0.9 ( documento 03): https://github.com/otaviojava/Easy-Cassandra/downloads

Easy-Cassandra= java ORM for Cassandra, now run with Maven

Posted by otaviojava on March 17, 2012 at 4:55 AM PDT

 

Running the new version of the Easy-Cassandra framework it main objective is making it easy the communication between Apache Cassandra and your application in java. With it you able create, update, retrieve, delete the java's objects in easy way and simple, for this you must add some annotation in Class and fields.

 

Characteristics

 

 

  • An ORM easy to use in Cassandra

  • Need only use some Annotations in a class to persist

  • Persists many Java Objects in way extremely easy (e.g: all primitives types, java.Lang.String, java.lang.BigDecimal, java.io.File, see here for more details).

  • Read and Write in Cassandra with Level Consistency.

  • The first framework ORM in Cassandra to compatives with version above 0.8.0.

  • The first to use CQL

  • The first to use invokedynamic instead to reflection

  • In the apache version 2.0 license

     

 

improvement in 1.0.8

 
  • Make of the Column Family and secondary index  in real time
  • CQL 2.0 Support
  • Support call key with 'in' command

 

 

 

For show the new version, we will do a simple application. This application has the objective persist information about average income of Brazil group by CEP. The objective is show how much is generated in cash and number of commercial entities by street. This way will be persist around 640 thousands information for each survey. Each request has the information below:

 

 

  • Lote code

  • how may commercial entities in CEP

  • value in cash

  • cite

  • street

  • district

  • Cep

  • type of street

  • Province

  • acronym of Province

For amazing the data will use the Cassandra, its features are:

 

Cassandra

     

    Proven

    Cassandra is in for many companies. that have large, active data sets. The largest known Cassandra cluster has over 300 TB of data in over 400 machines.

     

    Fault Tolerant

    Data is automatically replicated to multiple nodes for fault-tolerance. Replication across multiple data centers is supported. Failed nodes can be replaced with no downtime.

     

    Decentralized

    There are no single points of failure. There are no network bottlenecks. Every node in the cluster is identical.

     

    You're in Control

    Choose between synchronous or asynchronous replication for each update. Highly available asynchronous operations are optimized with features like Hinted Handoff and Read Repair.

     

    Rich Data Model

    Allows efficient use for many applications beyond simple key/value.

     

    Elastic

    Read and write throughput both increase linearly as new machines are added, with no downtime or interruption to applications.

     

    Durable

    Cassandra is suitable for applications that can't afford to lose data, even when an entire data center goes down.

     

    Professionally Supported

    Cassandra support contracts and services are available from third parties.

font:http://cassandra.apache.org/

 

 

For get developing more easy will used the Easy-Cassandra, It works like a layer above of the Thrift, facilitating call for Cassandra, increasing more productivity and leaving code more clean. For use it is necessary download the framework and its dependencies. You can manage this libs using the maven, for this add the repository like table 1.

 

table1: add repository and call the Easy-Cassandra

 

Each request will a line in Cassandra which might vary in size line by line. This way the class with annotations was like show table 2.

 

 

 

@ColumnFamilyValue(name = "controle")
public class ControleRenda implements Serializable {
 
@KeyValue(auto = true)
private Long id;
@EmbeddedValue
private Endereco endereco;
@ColumnValue(name = "valor")
private Double valor;
@ColumnValue(name = "quantidade")
private Long quantidade;
//getter and setter
}
 
public class Endereco implements Serializable {
 
@ColumnValue(name="cidade")
private String cidade;
 
@ColumnValue(name="logradouro")
private String logradouro;
 
@ColumnValue(name="bairro")
private String bairro;
 
@IndexValue
@ColumnValue(name="cep")
private String cep;
 
@ColumnValue(name="tp_logradouro")
private String tp_logradouro;
 
@ColumnValue(name="estado")
private String estado;
 
@ColumnValue(name="sigla")
private String sigla;
// getter and setter
}
 

Table 2: Mapping class with Easy-Cassandra

 

When you see the table 2, will seen the Address class with an annotation @IndexValue in cep's field, this annotation does the field be a secondary index( The secondary index is other field for search information beyond the key row).

For run our sample application needs Cassandra is running and make the keystore. The column family and secondary index will be created in run time thanks improvement in this version.

 

 

 

[prettifyclass="western"]<span style="font-size: x-small; ">create keyspace renda;</span>[/prettify]

 

 

This way now only run the application and all information will persist in Cassandra. In this article was showed a practice example with 640 thousand requests. Was showed some improvements like create column family and secondary index in run time in this new version of the Easy-Cassandra.

 

 

References:

 

Easy-Cassandra: https://github.com/otaviojava/Easy-Cassandra

Documentation, lib e source (Maven_Example.rar): https://github.com/otaviojava/Easy-Cassandra/downloads

wiki: https://github.com/otaviojava/Easy-Cassandra/wiki

 

 

 

 

 

 

 

 

Comments

Can we use this in place of any relationl database ...

Can we use this in place of any relationl database ?

Regards
Javin

The NOSQL has something different than SQL and its objective ...

The NOSQL has something different than SQL and its objective is different.

See more in:
http://en.wikipedia.org/wiki/NoSQL

Knowing more about Easy-Cassandra Project

Posted by otaviojava on February 21, 2012 at 8:02 AM PST
   
 
 
    
    Easy-Cassandra is a framework ORM API and a high client for Apache Cassandra in java, with this is possible persist information from the Java Object in easy way. For this is only necessary add some annotations in some fields and your class. It works like an abstraction's tier in the Thrift, doing call for Cassandra.
The Easy-Cassandra uses the Thrift implementation and has like the main objective be one simple ORM (Object relational manager). It need the jdk 7 for run, because some parts in your code was replaced reflection for invoke dynamic. So will have a behavior faster than other framework. The Easy-Cassandra was the first framework compatible with Cassandra version above 0.8 and the first one to use CQL (Cassandra Query Language). For read a class, it use the invokedynamic, fifteen time faster than reflection.
 

Features

 

  • An ORM easy to use in Cassandra
  • Need only use some Annotations in a class to persist
  • Persists many Java Objects in way extremely easy (e.g: all primitives types, java.Lang.String, java.lang.BigDecimal, java.io.File, etc.).
  • Read and Write in Cassandra with Level Consistency.
  • The first framework ORM in Cassandra to compatives with version above 0.8.0.
  • The first to use CQL
  • compatible with CQL 2.0
  • The first to use invokedynamic instead to reflection
  • In the Apache version 2.0 license
 

Java Objects Supported

 
The Easy-Cassandra has support for the Object java bellow:
 
  • all primitives types (int, long, float, double, short, byte, boolean)
  • java.lang.Boolean
  • java.util.Date
  • java.lang.Double
  • java.lang.Float
  • java.lang.Integer
  • java.lang.Long
  • java.lang.String
  • java.lang.Boolean
  • java.lang.Byte
  • java.lang.Short
  • java.lang.Character
  • java.io.File
  • java.nio.file.Path

 

 About Versions

 

The current and stable version is 1.0.7

 

Version: 1.0.7
  • update cassandra-thrift to 1.0.7
Version: 1.0.6
  • Fixes bug with File
  • Support Calendar interface
Version: 1.0.5
  • Can now store files
  • Support java.io.File and java.nio.file.Path
Version: 1.0.4
  • more performance
  •  less memory
  •  now is supported all primitives types
  •  now is supported Byte, character, Short, BigInteger and BigDecimal
Version: 1.0.3
  • Fixes bug with result
  • update for Thrift 1.0.6
  • Log now using java.util.loggin
Version: 1.0.2
  • Fixes bug with Boolean's Object
  • Now the Cassandra's lib is supported this way is possible use every Cassandra above of the version 0.8.0
Version: 1.0.1
  • Allowed use ColumnValue and ColumnFamilyValue in default mode this way its get the field's name
  • Fixes bug in Reflection

 

 

 

Beyond version

 

  • Call exception when there are not neither Index Key nor Key Value in the class
  • Select Key from 'in'  CQL command
  • Create automatically the ColumnFamily in Run Time
  • Create automatically the IndexValue in Run Time
  • Suport with cql 2.0
  • Support with one and more Index
  • Feed Object with Cassandra Query Language

     Example: List<Person> persons= cassandraQuery.executeQuery("select * from Person").getResultList();

 

 

Simple Sample

 

For use this recourse is very simple like sample bellow:

 @ColumnFamilyValue(nome = "person")

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <b>class</b> Person <b>implements</b> <font color="#003399">Serializable <font color="#009900">{</font> </font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> <b>static</b> <b>final</b> <font color="#000066"><b>long</b> serialVersionUID <font color="#339933">=</font> 3L<font color="#339933">;</font></font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@KeyValue<font color="#009900">(auto<font color="#339933">=</font><font color="#000066"><b>false</b></font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> <font color="#003399">Long id<font color="#339933">;</font></font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@IndexValue</font></font>
<font color="#000000"><font size="2" style="font-size: 9pt">@ColumnValue<font color="#009900">(nome <font color="#339933">=</font> <font color="#0000ff">&quot;name&quot;</font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> <font color="#003399">String name<font color="#339933">;</font> </font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@ColumnValue<font color="#009900">(nome <font color="#339933">=</font> <font color="#0000ff">&quot;year&quot;</font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> <font color="#003399">Integer year<font color="#339933">;</font></font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@EnumeratedValue<font color="#009900">(nome<font color="#339933">=</font><font color="#0000ff">&quot;sex&quot;</font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> Sex sex<font color="#339933">;</font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@EmbeddedValue</font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> Address address<font color="#339933">;</font></font></font>
<font color="#666666"><font size="2" style="font-size: 9pt"><i>//getter and setter</i></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>
Simple of annotations in a class
 
 
<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <b>class</b> PersonDAO <font color="#009900">{</font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>private</b> Persistence persistence<font color="#339933">;</font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> PersonDAO<font color="#009900">() <font color="#009900">{</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt">persistence <font color="#339933">= EasyCassandraManager.<font color="#006633">getPersistence</font><font color="#009900">(</font><font color="#0000ff">&quot;javabahia&quot;</font>, <font color="#0000ff">&quot;localhost&quot;</font>, <font color="#cc66cc">9160</font><font color="#009900">)</font><font color="#339933">;</font></font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#000066"><b>void</b> create<font color="#009900">(</font>Person bean<font color="#009900">)</font> <font color="#009900">{</font></font></font></font>

<font color="#000000">   <font size="2" style="font-size: 9pt">persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">insert</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">bean</font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#000066"><b>void</b> remove<font color="#009900">(</font>Person bean<font color="#009900">)</font> <font color="#009900">{</font></font></font></font>
<font color="#000000">   <font size="2" style="font-size: 9pt">persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">delete</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">bean</font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#000066"><b>void</b> remove<font color="#009900">(</font><font color="#003399">Long</font> id<font color="#009900">){</font></font></font></font>
<font color="#000000">    <font size="2" style="font-size: 9pt">persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">deleteByKeyValue</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">id, Person.</font><font size="2" style="font-size: 9pt"><b>class</b></font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><font color="#009900">} </font></font></font>

<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#000066"><b>void</b> update<font color="#009900">(</font>Person bean<font color="#009900">)</font> <font color="#009900">{</font></font></font></font>

<font color="#000000">   <font size="2" style="font-size: 9pt">persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">update</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">bean</font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> Person retrieve<font color="#009900">(<font color="#003399">Object</font> id<font color="#009900">)</font> <font color="#009900">{</font></font></font></font>

<font color="#000000">   <font size="2" style="font-size: 9pt"><b>return</b></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">Person</font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font size="2" style="font-size: 9pt"> persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">findByKey</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">id, Person.</font><font size="2" style="font-size: 9pt"><b>class</b></font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>
<font color="#000000"><font size="2" style="font-size: 9pt">@SuppressWarnings<font color="#009900">(<font color="#0000ff">&quot;unchecked&quot;</font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#003399">List listAll<font color="#009900">()</font> <font color="#009900">{</font></font></font></font>

<font color="#000000">  <font size="2" style="font-size: 9pt"><b>return</b></font><font size="2" style="font-size: 9pt"> persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">findAll</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">Person.</font><font size="2" style="font-size: 9pt"><b>class</b></font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>

<font color="#000000"><font size="2" style="font-size: 9pt">@SuppressWarnings<font color="#009900">(<font color="#0000ff">&quot;unchecked&quot;</font><font color="#009900">)</font></font></font></font>
<font color="#000000"><font size="2" style="font-size: 9pt"><b>public</b> <font color="#003399">List listByIndex<font color="#009900">(</font><font color="#003399">Object</font> index<font color="#009900">)</font> <font color="#009900">{</font></font></font></font>
<font color="#000000">   <font size="2" style="font-size: 9pt"><b>return</b></font><font size="2" style="font-size: 9pt"> persistence.</font><font color="#006633"><font size="2" style="font-size: 9pt">findByIndex</font></font><font color="#009900"><font size="2" style="font-size: 9pt">(</font></font><font size="2" style="font-size: 9pt">index, Person.</font><font size="2" style="font-size: 9pt"><b>class</b></font><font color="#009900"><font size="2" style="font-size: 9pt">)</font></font><font color="#339933"><font size="2" style="font-size: 9pt">;</font></font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>
<font color="#009900"><font size="2" style="font-size: 9pt">}</font></font>

Sample of DAO performing call for the Cassandra 

More information

 
 

If you would like do question about, contribute, share experience, do anything for the project. Do part of Group in Google Groups: https://groups.google.com/group/easy-cassandra/ 

 

 

 

Persist document in Cassandra

Posted by otaviojava on February 1, 2012 at 11:32 AM PST

font:http://www.gerenciandoblog.com.br/2009/08/onde-hospedar-arquivos-para-seu-blog.html

 
 
Nowadays the Enterprise applications beyond persist String and number also can save file. Persist this information is very interesting, for example, a civil process there are information about the process (name of author, date, number of protocol) and the document which represents, or a twett with an image. In Apache Cassandra, you can save file, but for large file you should use a NOSQL Document Store.
 
For demonstrated this resource will made a little program, an album of photography, The picture will show from name. If I use “Paris” will show a picture was related to that name.
 
 
 
 
The program was made with java SE 7 platform, with Swing like GUI, and Easy-Cassandra framework, for this it's necessary download of Easy-Cassandra and its dependencies.
 
The object has two field:
The name of the photo, how this field must be unique it also will the key
The file of the photo
 
The table 1 show the object made.
 
 
@ColumnFamilyValue
public class Photo {
@KeyValue
private String name;
 
@ColumnValue
private File picture;
//getter and setter
}
Table 1: The Object made
 
 
public class PhotoDao {
private Persistence persistence;
public PhotoDao() {
persistence = EasyCassandraManager.getPersistence("exemplo", "localhost", 9160);
}
public void criar(Photo bean) {
persistence.insert(bean);
}
 
@SuppressWarnings("unchecked")
public List<Photo> listarTodos() {
return persistence.findAll(Photo.class,ConsistencyLevelCQL.ALL);
}
}
Table 2: The DAO
 
When the Cassandra is running the next step is create the KeyStore and Family Column, in Cassandra's Client mode execute the command in the table 3.
 
 

create keyspace exemplo; use exemplo;

create column family Photo

with comparator = UTF8Type;

Table 3; Command for run

 
 
 
 
 
This post presented the persistence of an document or file with a simple example. This resource is useful and easy of use. The Easy-Cassandra has support with java.io.File and all classes who implement java.nio.file.Path.
 
 

Reference:

Easy-Cassandra: https://github.com/otaviojava/Easy-Cassandra/
 Example program with Eclipse and Netbeans: https://github.com/otaviojava/Easy-Cassandra/downloads

 

 

Persisting information with Cassandra in java: Simple example

Posted by otaviojava on January 24, 2012 at 3:16 AM PST


This article has the main objective show a little example for persist information in Cassandra using java.

For demonstrated the persistence with Cassandra will used the Easy-Cassandra, a framework open source for use this SGBG in an easy mode.
 
@ColumnFamilyValue(nome = "person")//
public class Person implements Serializable {
 
private static final long serialVersionUID = 3L;
@KeyValue(auto=false)
private Long id;
@IndexValue
@ColumnValue(nome = "name")
private String name;
@ColumnValue(nome = "year")
private Integer year;
@EnumeratedValue(nome="sex") campo
private Sex sex;
@EmbeddedValue
private Address address;
//getter and setter
}
 
 
 
public class PersonDAO {
 
private Persistence persistence;
 
public PersonDAO() {
persistence = EasyCassandraManager.getPersistence("javabahia", "localhost", 9160);
}
 
public void create(Person bean) {
persistence.insert(bean);
}
 
 
public void remove(Person bean) {
persistence.delete(bean);
}
 
public void remove(Long id){
persistence.deleteByKeyValue(id, Person.class);
}
public void update(Person bean) {
 
persistence.update(bean);
 
}
 
public Person retrieve(Object id) {
return (Person) persistence.findByKey(id, Person.class);
}
 
@SuppressWarnings("unchecked")
public List listAll() {
return persistence.findAll(Person.class);
}
 
 
@SuppressWarnings("unchecked")
public List listByIndex(Object index) {
return persistence.findByIndex(index, Person.class);
}
 
}
 
 
The source can be downloaded in a link, in the end of article, when you are seeing the source can see the annotations bellow:
 
 
  • ColumnFamilyValue: annotations for identify the family column name
  • ColumnValue: for identify the column in the Family Column, the classes can be used are:
  • java.lang.Boolean
  • java.util.Date
  • java.lang.Double
  • java.lang.Float
  • java.lang.Integer
  • java.lang.Long
  • java.lang.String
  • EmbeddedValue: The class with this is annotation has fields with ColumnValue inside itself, but the persistence way continues in the same Family of the Column. This annotation is to do the object’s modeling easily.
  • EnumeratedValue: for be used in Enums
  • IndexValue: The field with this annotation is an index, can search and retrieve information from the row like KeyValue, need also use the ColumnValue together with this annotation.
  • KeyValue: The field with this annotation is an Key of the Row. If the auto value is true will generate auto increment, each new Key in the FamilyColumn there are a new value auto numeric.
 
The annotation ColumnFamilyValue, ColumnValue and EnumeratedValue if the value “name” be empty the value default is the Field's name.
 
After see the code let go that for run, so you need:
 
 
  • JDK 7 or above
For run the example follow this the steps:
 
  • Do download of the apache-cassandra in: Here
  • After that, unzip the file downloaded and enter it.
  • Execute the command when you stay in Cassandra home:
./bin/cassandra -f
  • For execute the client's mode, also in Cassandra'home execute the command bellow:
./bin/cassandra-cli -host localhost
 
  • In the Client's mode run the script bellow:
 
create keyspace javabahia; use javabahia; create column family person with comparator = UTF8Type and column_metadata = [   {column_name: name, validation_class: UTF8Type, index_type: KEYS} ];

 

  • Download and add in ClassPath of the Project, the Easy-Cassandra's lib:
  • You will have two choices of Download:
  • Only the Easy-Cassandra's lib
  • The Easy-Cassandra's lib with its dependencies (The Libs of the Thrift)
This article has like main objective show a little some persist of information in apache-Cassandra, for this was used a little example that is available in Netbeans and Eclipse IDE.

Reference:
 
Download of sources and libs
 
 
Wiki Easy-Cassandra:
 
 
home Easy-Cassandra:
 
 
 

 

Killing the myths about java

Posted by otaviojava on January 16, 2012 at 11:21 PM PST
From 1995, when was launched the first Java's version, to 2012 the Java evolute obtained seven versions, many improvements and fixes bugs. In 2011 the biggest “boom” in the java world was about the openjdk recently it's grew in exponential way, but there are some myths arount it, for example, some people know the openjdk like “poor brother” of SUN's JDK (actually Oracle). Many things changed through the time, think that is how believe Linux is the SO of black window. The post was made a quiz mode, for killing some myths about the java world.
 
 
1 – What is the openjdk ?
 
The openjdk is a project started by Sun Microsystems, nowadays care by many companies and the community for build a Java Development Kit absolutely in open source. The project was begun in 2006 and has how base the HotSpot ( the SUN's JVM).
The openjdk obtained popularity when was removed the temporary license of use of JDK Hostpot in Linux distributions by Sun, but the community don't lost the use proprietary software and yep they are winning the project strong, safe, stable, very fast and open.
 
2 – Are there other JDKs beyond Oracle's JDK ?
 
Off course and the openjdk is a good example.
There are also the BM J9, IcedTea, Hotspot (old Sun now Oracle), jRockit (da Oracle), Apache Harmony ,Hewlett Packard JVM, etc.
 
3 – Yep, there are too many JDK, so what is the reference ?
 
With the new Java 7, the reference implementation is the openjdk.
4 – what is the advantage for use the openjdk ?
 
  • The first advantage is because it's open source, so we can read, learn from its source.
  • With the java 7, it's implementation reference in other words if you want make a application for run in all JVM, if you use the openjdk is most safest than other JDK.
  • The java's community is very strong, maybe strongest in the world. The project for example has been undergoing improvements and for add some resource it's necesary test.
  • The Oracle donated the code ot JRockit and in the Java 8, scheduled for late 2013, the jvm will be integrated with HostSpot, in openjdk there will the better of two JVM in only one place.
  • Many company are in the project. The JVM has know-how may companies in the world. Companies like IBM, Apple, SAP, Mac, Azul, Intel, RedHat etc are in the project.
  • If Oracle forget the Java and don't the JVM. O openjdk don't will die because there are many companies have been donated time and work in the project also the community.
 
5 – The openjdk is only academic's use and can't be used in bigger application or production system.
 
Absolutely this is the biggest myth there is in java world. There time ago the Twitter replaced the Ruby by java, for get more performance and they are using the openjdk. The twitter has about 250 millions of the request or tweets each day, and is used around the world. The twitter now is in the openjdk project and is giving his experience with millions of the request for the JVM and in the future will help with self-tunning scheduled for java 9. In world stage the openjdk is the second more used ( behind of the hotSpot).
 
6 – What is difference between Oracle's JVM and openjdk ?
 
The main difference is addition some proprietary code also some modifications for the Oracle's JVM, but dissimilarity is only about 4% in the code.
 
7 – What code is this ?
 
Some code, for example, the engine for run Swing components.
 
8 – How is the work with openjdk ?
 
The project goes full steam ahead, there are many works fronts:
  • Integration between Jrockit and HotSpot
  • update code and libraries for the java 7
  • fixes bugs in java 7
  • works have been started in java 8
 
9 – When is schedule the new java 8 ?
 
In first time the java 8 would come in next year, but for a accession easy the update will come each two year, so in 2013.
With the news bellows:
  • Conclusion in integration beteween jRockit and HotSpot making the HotRockit
  • JSR 308: Annotations on Java Types
  • JSR 310: Date and Time API
  • JSR TBD: More Small Enhancements to the Java Programming Language
  • JSR 335: Lambda Expressions for the Java Programming Language
  • JSR TBD: Java Platform Module System
 
Also there are some plans for the java 9 like the self-tuning and the comunications with many languages inside the JVM.
 
10 – This separation of the java 7 in two part is it a good idea ?
 
 
In my opinion had big advantages
  • Come a new version for the Java, thing don't happened in six year.
  • Come new features without a big JDK.
  • periodic update in other word a constant update's cycle.
  • Large modifications like lambda and jigsaw will be more mature.

11 – With this release what happen with the 6 ?

There will are public updates at half 2012, after that if there is, for only security's update.
 
12 – And about the certifications ?
 
I not know, this is a Oracle's product, so the community has nothing to do with it.
 
13 – Then, is the java Core done only by Oracle ?
 
No, certifications and source of the java core are two different things, the certifications are of the Oracle. And java language, platform and virtual machine maintained for many companies like IBM, Apple, SAP, Mac, Azul, Intel, RedHat, Twitter, community, Oracle etc.
 
 
14 – When Oracle bought the SUN, java stated its dead, in other words learn java isn't good option.
 
It is not true, Oracle has been helped strong way, donated source from openjdk, joined all JUGs around world in the java 7 release party, did open source version for java FX, raised ME platform, etc.
About the java died, absolutely will have a long time, it is noteworthy nowadays java is the language most used in the world, a choice number one for developer and enterprise open source project, there are 9 millions java developers around earth. If the java stop there are too many java's projects, but it is lies because there are project from java 8 and beyond like for example, html 5, cloud computing etc.
 
15 – is Java run too slowly ?
 
When bi-nuclear processors were born and the evolution in java's project, it's gained more popularity about performance, proved to be faster than C and C++. development Leader of the Gmail, Paul Buchheit, in his blog did some tests, even with optimizations in GCC, the benchmark's code run faster in java then C also there are many article confirm that.
 
 
 
 
http://keithlea.com/javabench/data " alt="" />
 
 
16- What is made in 2011 and what will wait in future ?
 
This year there was some features for the java:
 
  • java 7 release
  • The openjdk is reference implementation
  • The java fx get a open source project
  • Planes for the java 8 and beyond
  • Java Me rise up and come back to work
  • Soujava and LondoJug do part in JCP
 
For the future...
 
  • More work in JVM
  • More integration between JUGs around orbit
  • More companies using and contribute the openjdk
  • The javafx run anywhere
  • More four updates in java 7
  • Last public version for java 6
  • Release Java ME 7
This article was told a few about the openjdk's project, what was did in 2011 and hope in the future. With expectations and periodic works 2012 gonna moving java forward.
 
 
Reference:
 
The Java is Faster than C++ and C++ Sucks Unbiased Benchmark
 
Paul Buchheit, java running faster than c

 

 

 

Comments

&nbsp;The references about Java performance are kinda out of ...

The references about Java performance are kinda out of date and inaccurate.

&nbsp; There are too much article around the internet ...

 

There are too much article around the internet talking about this ( myself, for example, did some tests between C and Java  7). I only used that article like main reference for two motive:
This article was the first was talking about that theme
The author works in Google with the Gmail, so he has many experience in process wich needs high performance.
But the java is faster then C in some things, mainly when it works with multi-thread,   occasions not in all.
Some links:
 
http://blog.cfelde.com/2010/06/c-vs-java-performance/
http://www.stefankrause.net/wp/?p=9
http://zi.fi/shootout/
 
Thank for your commentary 

 

 

 

 

Thanks for adding the point about the perfromance of java ...

Thanks for adding the point about the perfromance of java based applications.

Party 10 year with Eclipse, around the Brazil

Posted by otaviojava on November 26, 2011 at 7:47 AM PST

 
     Eclipse is famous IDE in em Java, follows the open source model. The Eclipse project was stated by IBM that does the first version, then donated like open source for the community. The begin costs was above 40 millions. Nowadays, the Eclipse is one of the most used worldwide. Has important feature how the SWT uses and not the Swing, there are too many plug-ins for several developers in different situations.
 
      On November month the Eclipse foundation promoted the party about the ten years old of Eclipse IDE, one of the most popular IDE worldwide. This event was around the world also in the Brazil,
 
 
    In Ceará, the event was organized by CEJUG, java user groups of Ceará. The event happened on November 17, Thursday, at night. And counted with the present of java enthusiasts also java user group member, there was cake and T-shirt for the participants. The the speakers talk about their experience and tricks for render programming in the IDE more easy.

 

 
In Bahia the javaBahia, java user group of the Bahia, did the event November 12, on Saturday in the morning. The event had speakers talked about the eclipse's history her features and improvements over the years also upon plug-in for developers to the web and the mobile devices. This day at afternoon there was a unreferenced about cloud computing was speaking the Eclipse Orion project, an IDE in the cloud made by Eclipse Foundation.
 
 
 
Certainly the eclipse IDE facilitated too much the life of the java programers, what is expected are new features, more time of life beyond each year more improvements.
 
 
References:
 
10 year eclipse line of time http://www.eclipse.org/10birthday
 
 
 
Photos JavaBahia
 
 
videos javaBahia:
Eclipse Web: 10 anos de amor e ódio http://vimeo.com/32249666
 
 
Unreferenced cloud camp
Potencial de Inovação da Nuvem: http://vimeo.com/32342592
Python nas nuvens: http://vimeo.com/32049594
 
 
videos CEJUG:
 

 

Moving o java forward part 4- JSR 166y: concurrent Package

Posted by otaviojava on October 26, 2011 at 12:34 AM PDT

 

Was added to his package to facilitate applications which needs scalable processes.

A feature is atomic variable. Variable atomic means that it cannot be divided -  it's like the S.O. with any resource (Driver CD, USB) cannot be divided but needs be used in many processes.

 

            static class AtomicCounter { 

         private AtomicInteger counter = new AtomicInteger(0);

         public void increment() {


             System.out.println(" couting " + contador.incrementAndGet());
         }

         public void decrement() {
             System.out.println("decrementing " + contador.decrementAndGet());

         }

         public int value() {
             return c.get();
         }
     }

     static class Producer implements Runnable {

         private AtomicCounter atomicCounter;

         public Producer(AtomicCounter counter) {
             this.atomicCounter = counter;


         }

         @Override
         public void run() {
             while (true) {

                 try {
                     Thread.sleep(2000);
                 } catch (InterruptedException ex) {
                     ex.printStackTrace();
                 }
                 atomicCounter.increment();


             }
         }
     }

     static class Consumer implements Runnable {

         private AtomicCounter atomicCounter;

         public Consumer(AtomicCounter counter) {
             this.atomicCounter = counter;


         }

         @Override
         public void run() {
             while (true) {

                 try {
                     Thread.sleep(4000);
                 } catch (InterruptedException ex) {
                     ex.printStackTrace();
                 }
                 atomicCounter.decrement();

             }
         }
     }

     public static void main(String[] args) {

         AtomicCounter atomicCounter = new AtomicCounter();
         Thread consumer = new Thread(new Consumer(atomicCounter));
         Thread producer = new Thread(new Producer(atomicCounter));
         consumidor.start();
         produtor.start();
         while (true) {
         }

     }

Picture 1: Simple example with consumer and producer

 

It's possible to create one Object and this object will be an atomic variable for this uses the interface java.io.Serializable.

 

     public static void main(String[] arg) { 
         AtomicReference<MYObject> myObject = new AtomicReference<>();
         System.out.println(meubojeto.get());
         myObject.set(new MYObject("value"));
         System.out.println(meubojeto.get().getAttribute());
         AtomicReferenceArray<MYObject> users = new AtomicReferenceArray(10);
       
         users.getAndSet(1, new MYObject("Setando objeto 1"));

     }

Picture 2: create atomic variable

 

In this new version there are more current collections.

 

BlockingDeque fila = new LinkedBlockingDeque<>();

ConcurrentMap map = new ConcurrentHashMap();

ConcurrentNavigableMap maps = new ConcurrentSkipListMap<>();

Picture 3: current  Collections

 

 

In concurrent process and you would like to lock any resources for other Threads -  don't use or access during that time - for this, only use the java.util.concurrent.locks.Lock.

The Executor has the main objective of realizing parallel processes and on a big scale. Now it's possible to use three new interfaces(Executor, ExecutorService, ScheduledExecutorService), These interfaces execute in the Thread pool, so the JVM manages parallel processes. Another improvement is Fork/Join, it helps in a better way for multiple processes and how it can be divided in the letter part and the recursive way.

 

 

Conclusion:

 

This article discusses improvements in the concurrent in java 7, the concurrent package.

Welcome java 7 part 3 -NIO 2 JSR 203

Posted by otaviojava on October 10, 2011 at 1:13 AM PDT

Welcome java 7 part 3 -NIO 2 JSR 203

 

So like the coin project, in the NIO 2 there aren't unprecedented features in this e -specification, but now it's possible do some easier work I/Os in java. With the class java.io.Files are possible to perform several operations in simple mode. For that it needs and uses the java.io.file.Path, this interface represents files and directories in the operating system.

 

Path path=Paths.get("file.txt");

Picture 1: Making a path, the String “file.txt” can be replace for any path in operating system, it's should directories, files, symbolic link and hard link.

 

 

    public static void moveFile(Path arquivoOrigem, Path arquivoDestino) throws Exception { 
         Files.move(arquivoOrigem, arquivoDestino, StandardCopyOption.REPLACE_EXISTING);
     }



     public static void copyFile(Path arquivoOrigem, Path arquivoDestino) throws Exception {
         Files.copy(arquivoOrigem, arquivoDestino, StandardCopyOption.REPLACE_EXISTING);
     }



     public static void deleteFile(Path arquivo) throws Exception {
         Files.delete(arquivo);
     }



     public static Path createFile(String arquivo) throws Exception {
         return Files.createFile(Paths.get(arquivo));
     }



     public static Path createDictory(String diretorio) throws Exception {
         return Files.createDirectories(Paths.get(diretorio));
     }



     public static void creatSymbolicLink(Path linkSimbolico, Path arquivo) throws Exception {
         Files.createSymbolicLink(linkSimbolico, arquivo);
     }



     public static void createLink(Path link, Path arquivo) throws Exception {
         Files.createLink(link, arquivo);
     }

Picture 2: I/O's operations using the java.nio.Files

 

It's possible retrieve information in java.io.Path in an easier way, and can get more about one path with six new interfaces.

     public static void propertiesPath(Path path) throws Exception { 
 
         System.out.println("size in  bytes " + Files.size(path));
         System.out.println("is directory ? " + Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS));
         System.out.println("is regular ? " + Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS));
         System.out.println("is hidden " + Files.isHidden(path));
         System.out.println("last modified " + Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS));
         System.out.println("owner " + Files.getOwner(path, LinkOption.NOFOLLOW_LINKS));
 
 
         System.out.println("\n \n \n Basic Files attributes \n \n \n ");
         BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
 
         System.out.println("creation time: " + attr.creationTime());
         System.out.println("last acess: " + attr.lastAccessTime());
         System.out.println("last modified: " + attr.lastModifiedTime());
 
         System.out.println("is directory " + attr.isDirectory());
         System.out.println("is other " + attr.isOther());
         System.out.println("is  regular: " + attr.isRegularFile());
         System.out.println("symbolic link: " + attr.isSymbolicLink());
         System.out.println("tamanho: " + attr.size());
 
         System.out.println("\n \n \n Dos atributes file \n \n \n ");
 
         DosFileAttributes dosAttr = Files.readAttributes(path, DosFileAttributes.class);
         System.out.println(" only read " + dosAttr.isReadOnly());
         System.out.println("hidden " + dosAttr.isHidden());
         System.out.println("file " + dosAttr.isArchive());
         System.out.println("system file " + dosAttr.isSystem());
//The other interfaces
//PosixFileAttributeView
//FileOwnerAttributeView
//AclFileAttributeView 
//UserDefinedFileAttributeView 
     }

Picture 3: get more with new interfaces

 

 

Now in NIO2 read and write in scalable manner is possible with the java.nio.channels.FileChannel, for example some big documents can use three Threads for reading and writing in quick mode.

 

 

     public static void acessoEscalavel(Path path) throws Exception { 
         String s = "I was here!\n";
         byte data[] = s.getBytes();
         ByteBuffer out = ByteBuffer.wrap(data);
 
         ByteBuffer copy = ByteBuffer.allocate(12);
 
         try (FileChannel fc = (FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE))) {
             //read 
             int nread;
             do {
                 nread = fc.read(copy);
                 byte[] bytearr = copy.array();
 
                 String ss = new String(bytearr);
                 System.out.println("lendo: " + ss);
 
             } while (nread != -1 && copy.hasRemaining());
 
             //write in the begin file
             fc.position(0);
             while (out.hasRemaining()) {
 
                 fc.write(out);
             }
 
             out.rewind();
 
            
             long length = fc.size();
             fc.position(length - 1);
             copy.flip();
             while (copy.hasRemaining()) {
                 fc.write(copy);
             }
             while (out.hasRemaining()) {
                 fc.write(out);
             }
         } catch (IOException x) {
             System.out.println("I/O Exception: " + x);
         }
 
 
 
     }

Picture 3: write and read from FileChannel

 

 

In Path it is also possible to read and write in a normal way like with the java.io.File.

 

     public static void readFile(Path arquivo) throws Exception { 
         Charset charset = Charset.forName("UTF-8");




         String strLine = null;
         try (BufferedReader reader = Files.newBufferedReader(arquivo, charset)) {


             while ((strLine = reader.readLine()) != null) {


                 System.out.println("file line  " + strLine);


             }

         } catch (IOException x) {
             System.err.format("IOException: %s%n", x);
         }



     }



     public static void writeFile(Path arquivo, String texto) throws Exception {


         Charset charset = Charset.forName("UTF-8");




         try (BufferedWriter writer = Files.newBufferedWriter(arquivo, charset)) {
             writer.write(texto, 0, texto.length());


         } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
         }



     }

Picture 4: Writing and reading with the Path interface


Conclusion:

This article discusses the package NIO2, showing big features for facilitating I/Os process.