Pokazywanie postów oznaczonych etykietą Java 7. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą Java 7. Pokaż wszystkie posty

sobota, 13 kwietnia 2013

Project Coin - Java 7 features


Version 7 of Java implements few very useful features known as a part of a project coin. I agree, we need them and but changes to the language are pretty cosmetic. Closures is the thing which all Java developers around the world expected, we have to be patient, It will come up in version 8. But this is another story.
In this post I want to show you what the direct language changes in Java 7 are.

1.   STRINGS IN SWITCH



  (number) {
              case "One":
                     logger.info("Your number is 1");
                     break;
              case "Two":
                     logger.info("Your number is 2");
                     break;
              case "Three":
                     logger.info("Your number is 3");
                     break;
              case "Four":
                     logger.info("Your number is 4");
                     break;
              default:
                     logger.info("Error: wrong number");
                     break;
          }


2.   BINARY LITERALS



  int x = Integer.parseInt("1100110", 2);

  int x1 = 0b1100110;


3.   UNDERSCORES IN NUMBERS



  long longNumber = 2_147_483_648L;
  int binaryNumber = 0b0001_1100__0011_0111__0010_1011__1010_0011;


4.   EXCEPTION HANDLING



              try {
                     ...
              } catch (FileNotFoundException | ParseException
                           | ConfigurationException e) {
                     System.err.println("Config file '" + fileName
                                  + "' is missing or malformed");
              }


5.   DIAMOND SYNTAX
Don't need to evaluate generic types like in Java 6 



  //JAVA 6
  HashMap<String, String> hm1 = new HashMap<String, String>();




  //JAVA 7
  HashMap<String, String> hm2 = new HashMap<>();


6.   TRY WITH RESOURCES



  try (FileInputStream fstream = new FileInputStream(fileName);
       DataInputStream in = new DataInputStream(fstream);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));) {

                     String strLine;
                     while ((strLine = br.readLine()) != null) {
                           lines.add(strLine);
                     }

              } catch (FileNotFoundException e) {
                     logger.error("FileNotFoundException", e);
              } catch (IOException e) {
                     logger.error("IOException", e);
              }


7.   GENERIC VARARGS WARN
This is small change but also important. Compiler warn us on the compile time that we are creating the array generic type which cannot be done type-safely.




  public static <T> Collection<T> doSomething(T... entries) {
              ...
       }




Now we can use new java annotation to let compiler not warn us any more in this place : @SafeVarargs


References:

The Well-Grounded Java Developer: Vital techniques of Java 7 and polyglot programming


piątek, 5 kwietnia 2013

Decode binary numbers text using Guava


I was browsing some job offers on one of polish popular portals and found something interesting. Job offer for the programmer in Gdansk. It was not common kind of offer. When the browser rendered page I was little confused



After few moments I realized that this job offer is awesome, it doesn’t matter that I completely don’t understand what all those numbers means in natural language. I just recognize it as very good idea, this employer looking for specific kind of people. I imagine it could be directed to me J.

What is more it gives me opportunity to write few funny lines of code, so I didn’t wait and start at once.
First I copied all those numbers to file ad putted it to my project and then implemented FileReader class.




package org.gkolpu.offer;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class FileReader {
       public static final Logger logger = Logger.getLogger(FileReader.class);

       public List<String> readLines(String fileName) {
              List<String> lines = new ArrayList<String>();

              try (  FileInputStream fstream = new FileInputStream(fileName);
                           DataInputStream in = new DataInputStream(fstream);
                           BufferedReader br = new BufferedReader(new
                                               InputStreamReader(in));
                           ) {
                    
                     String strLine;
                     while ((strLine = br.readLine()) != null) {
                           lines.add(strLine);
                     }

              } catch (FileNotFoundException e) {
                     logger.error("FileNotFoundException", e);
              } catch (IOException e) {
                     logger.error("IOException", e);
              }
              return lines;
       }
}


package org.gkolpu.offer;

import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;

public class FileReaderTest {

       private static final String FILE = "src/main/resources/offer.txt";

       @Test
       public void shouldReadFileandReturnListWithEachLines() {
              FileReader reader = new FileReader();
              List<String> lines = reader.readLines(FILE);
              assertNotNull(lines);
              }
       }


And the most interesting part. I used google guava to implement decoding and collection processing.


 package org.gkolpu.offer;

 import com.google.common.base.Function;
 import com.google.common.base.Joiner;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Iterables;

 public class Decoder {

       private static final String EMPTY_SIGN = "";

       public String decode(String s) {

        Iterable<String> splits= Splitter.on('').trimResults().omitEmptyStrings().split(s);

              Function<String, String> decodeBinaryNumber = new Function<String, String>() {
                       public String apply(String character) {
                             int code = Integer.parseInt(character,2);

                         return Character.toString((char)code);
                       }
                     };
             
              Iterable<String> chars = Iterables.transform(splits, decodeBinaryNumber);
                    
              return Joiner.on(EMPTY_SIGN).join(chars);
       }
  }




 package org.gkolpu.offer;

 import static org.junit.Assert.*;

 import org.apache.log4j.Logger;
 import org.junit.Test;

 public class DecoderTest {

       public static final Logger logger = Logger.getLogger(DecoderTest.class);

       private static final String SINGGLE_SIGN = "01001110 ";
       private static final String MULTIPLE_SIGN = 
                  "01001110 01100001 01110011 01111010    00100000 01001011 01101100";

       Decoder decoder = new Decoder();

       @Test
       public void shouldDecodeSign() {

              String sign = decoder.decode(SINGGLE_SIGN);
              assertNotNull(sign);
              logger.info(sign);
       }

       @Test
       public void shouldDecodeMultipleSigns() {
             
              String sign = decoder.decode(MULTIPLE_SIGN);
              assertNotNull(sign);
              logger.info(sign);
       }
 }



At the and one more quick test case to see what is exactly the content of this job offer  J. 



 package org.gkolpu.offer;

 import static org.junit.Assert.*;

 import org.apache.log4j.Logger;
 import org.junit.Test;

 public class DecodeFileTest {
       public static final Logger logger = Logger.getLogger(DecodeFileTest.class);

       private static final String JOB_OFFER = "src/main/resources/offer.txt";

       @Test
       public void shoulReadTextFromFileAndDecodeItToString() {
              Decoder decoder = new Decoder();
              for (String line : new FileReader().readLines(JOB_OFFER)) {
                     String decodedLine = decoder.decode(line);
                     System.out.println(decodedLine);
                     assertNotNull(decodedLine);
              }
       }
 }



Result is in Polish so I didn’t attach it here, but content unfortunately disappointed me…. It was offer for C++ Programmer J, so it’s not for me. I’ll stay near JVM.