Skip to main content

otaviojava's Blog

Knowing more about Easy-Cassandra Project

Posted by otaviojava on February 21, 2012 at 10:02 AM CST
   
 
 
    
    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")

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")
private Sex sex;

@EmbeddedValue
private Address address;
//getter and setter
}
Simple of annotations in a class
 
 
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);
}
}

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 1:32 PM CST

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 5:16 AM CST


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<Person> listAll() {
return persistence.findAll(Person.class);
}
 
 
@SuppressWarnings("unchecked")
public List<Person> 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 17, 2012 at 1:21 AM CST
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 9:47 AM CST

 
     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 2:34 AM CDT

 

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<MyObject> fila = new LinkedBlockingDeque<>();

ConcurrentMap<String, MyObject> map = new ConcurrentHashMap();

ConcurrentNavigableMap<String, MyObject> 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 3:13 AM CDT

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.

 

 

 

Welcome java 7 - Part 2 JSR 334 Coin

Posted by otaviojava on August 21, 2011 at 3:29 PM CDT

Given some information about Java 7, i will now show the imrovements to the latest version.In this article i use the netbeans version 7.0.1, for this you need to download the JDK 7 (the link is below the article). After downloading and installing Netbeans (but during the installation remember to select the JDK 7 path).

 
The first example will show switch with String, previously this functionality was only possible  with Enuns and integer values. In actual fact the JDK retrieves the hashcode for the String which is an integer. Below is an example of this feature.
String drink="coffee";
switch (drink){
case "coffee":
System.out.println("So you need milk");
break;
case "juice":
System.out.println("So you need sugar");
break;
case "refrigerate":
System.out.println("So you need ice");
break;
default:
System.out.println("unknown drink ");
break;
}
 
 
I will now show you the ARM, Automatic Resource management, you don't need to concern yourself with the resources that will be used in your program because it will automatically close when it exits the Try block. For this just implement the interface java.lang.AutoCloseable, the only method is the Close, The AutoCloseable is the better option than Closeable because an exception is not thrown when you close the resource, in the second picture we can see this.

 

public void copyFile(File original, File copy) throws FileNotFoundException, IOException {
try (
InputStream in = new FileInputStream(original);
OutputStream out = new FileOutputStream(copy)) {
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}// it is automatically close
}

 

 
The multi-try, for some people is the most important feature in this version, it now allows many exceptions inside the cacth block just separate with a “|” pipe.
 
ExemploARM arm=new ExemploARM();
try {
arm.copyFile(origem, destino);
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println("It's can't copy file");
}
using multy-try
 
 
 
In Java 7 there are some improvements to Generics and collections making it easy to make this type Object. Now it is possible to make generic collections easily with the  diamond operator “<>”
 
List<Object> diamond=new ArrayList<>(); // diamond
List<Drink> Drinks;
Map<String, List<Drink>> maps=new HashMap<>();
maps.put("diamond", drinks=new ArrayList<>() );
maps.put("other example", new ArrayList<Bebida>() );
maps.put("erro", new ArrayList<>() );
 
[/code] Picture 4: diamond
 
 
 
Talking more about generic collections there is the annotation @SafeVarargs for ensuring this method is safe.

 

 Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable-arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.

 

@SafeVarargs
static <T> List<T> asList (T... elements) {
System.out.println(elements);
return null;
}
@SafeVarargs
static void varags(List<String>... stringLists) {
Object[] array = stringLists;
List<Integer> tmpList = Arrays.asList(42);
array[0] = tmpList; //run with warning
String s = stringLists[0].get(0); // ClassCastException
}
@SafeVarargs
 
 
 
The digit separator allows for good understand when writing big numbers in java code, the only rule is you can't separate the last and the first number, now you can write separator numbers with the caracter “_” it is also possible to write Double values and Float values, for example, for the JDK is equals 22 and 2_2. There is also literal in binary, which is most important when programming in embedding devices,  just put “ob” (zero and b) in front of a number, this Features can also use the separator.
long longPrimitive=9_999_999_99;
Long longObjete=9__3234_300l;
double doublePrimitive=232_32.32_12d;
Double doubleObjeto=88_32.32_12d;
int binA=0b01_01;
int binB=0b0101_0111;
if(2222==22_22){
System.out.println("equals values");
}
if(binA==5){
System.out.println("equals binary values");
}
 
picture 5: using separator and literal binary.
 
 
Other feature interesting is try with resource now it possible instantiate one variable if it does not generate an exception.
 
BufferedWriter writer=null;
try {
writer = Files.newBufferedWriter(arquivo, charset);
writer.write(s, 0, s.length());
 
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Picture 6: before was necessary create the variable
 
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
 
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Picture 7: after using try with resource in java 7

 

 

 

Comments

Thanx for the information, simple and clear. But can you ...

Thanx for the information, simple and clear. But can you please explain more about @SafeVarargs

Applying this annotation to a method or constructor ...

Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable-arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.

&nbsp;Java 7 is supported by IntelliJ for quite some time. ...

Java 7 is supported by IntelliJ for quite some time. The current Eclipse 3.8 supports it too and quite nicely.

thank you for this information.

thank you for this information.

Welcome java 7 - Part 1

Posted by otaviojava on August 11, 2011 at 5:52 AM CDT

After a long 5 year wait, finally comes the new version of Java,  jdk 7. The entire Java 7 project was divided into two sub-projects:

  • The coin project; which featured a few improvements to the language like switch with strings, mutil try etc.

  • Lamba's project containing some of the most innovative and complex features results in leaving the language a lot more dynamic.

 

In order to launch this new version, which will be used primarily to develop the coin project and lambda project scheduled for release in 2012 along with  java 8, constant updates have had to be made. These innovations are not only a welcome development for commercial applications, but also on other platforms, for example, in Java EE 7 which is being developed on top of this new jdk.

This version contains JSR 392 the, Da Vinci Machine project whose main objective is to introducenew  languages to the JVM (java virtual machine). The idea is to use external bytecodes in JVM (invoke Dynamic) so when future languages in the JVM are released, the existing languages will process a lot faster, the Jruby( Ruby version run in JVM) for example, will not need about two thousand classes. Some other cool information is the open jdk now is the reference implementation.

 

           

           

New Improvements to Java 7

 

JSR 292: The Da Vinci machine project of which the main objective is to cater for more languages in the JVM.

 

JSR 334: Little features in Java like switch with String which i will expand on below.

 

Some modifications have been made to the API class-loader to avoid deadlocks in non-hierarchical class-loader topologies.

 

JSR 166y: Updates in API's concurrency also in API's Collections.

 

Improvement to internationalization like upgrading to Unicode 6.0 java.util.Locale to suport IETF BCP 47 (Tags identifying languages) e UTR 35 (dates local Markup Language)

 

JSR 203: New APIs for filesystem access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams

 

A portable implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms, so that all Java applications can use ECC out-of-the-box.

 

Update to JDBC 4.1 Among its improvements is the automatic closing of connections and the RowSet 1.1 now can support all cand data supported by JDBC Driver.

 

New improvements to some graphics components like the new Java2D pipeline with base extensions Xrender X11, provides similar functionality to the modern GPU. Window graphics are well done, with translucent resources. Ther is also a new look and feel Nimbus theme of Swing component, and the new Jlayer decorator component allows you to apply many effects inside its border.

 

Updates for JAXP 1.4, JAXB 2.2a, e JAX-WS 2.2.

 

Improvement to MBeans com.sun.management which is important for reporting CPU processes about the JVM.

 

Month of java in Bahia

Posted by otaviojava on July 26, 2011 at 7:48 PM CDT

Beyond being merely a computer programming language, Java is the most widely used software platform in the entire world. There is a large number of various software solutions that were developed using this technology. Without many people being aware, Java is present in our daily lives in embedded technologies like blue-ray discs and a countless number of sites on the internet that were developed using this technology. Despite all the marketable qualities, the main advantages do not lie in the language or in the platform, but in strongly organized and reliable community around the world. The "Month of Java" takes place in July and is recognized in many places around the world. The objective is to talk about Java as a language aswell as a platform.

 
 
Soujava no TDC 2011
 
 
 

In Salvador, the event was organized by JavaBahia of the Bahia user group. The event took place on Saturday, July 16 at the FIB. The event was attended by Bruno Sousa (the javaman), and Roger Brinkley who is a member of the leadership of Java ME comunity.

The Java celebration event consisted of three lectures, the first talked about java 7 and the future of the language made by Roger Brinkley. Next the javaman spoke about Java in the cloud (also known as cloud computing), which is nowadays moving into the market . Last of all, Roger talked about Java fx 2.0.

Beyond the lectures there were some funny moments that took place with javali, for example the open jdk mascot, was talking about Java 7 and the open jdk reference implementation, and "the monkey code" involved, causing lots of laughter from the audience.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
  

At the end, shirts were delivered for all the participants of "The Month of Java". The event in Salvador was important because, besides bringing in some of the greatest speakers in the world, there was also the great presence of the Bahia's community.

 
Links:

Month do java:  http://vimeo.com/26574740

javali and code monkey: http://www.youtube.com/watch?v=Z7cG69Nr_3U