Sunday, November 16, 2014

Java 8 - List conversion to List

OK,

So we all know how we would do this in Java 6 right... something similar to:

public class ConvertListType1 {

 public static void main(String[] args) {
  List<String> items1 = Arrays.asList("1111", "2222", "3333", "4444", "5555", "6666");
  List<Long> items2 = new ArrayList<Long>();
  for (String string : items1) {
   items2.add(Long.parseLong(string));
  }
 }
}

Now lets break it down a bit:

public class ConvertListType2 {

 public static void main(String[] args) {
  List<String> items1 = Arrays.asList("1111", "2222", "3333", "4444", "5555", "6666");
  List<Long> items2 = collectConvertedItems(items1);
 }

 protected static long function(String string) {
  return Long.parseLong(string);
 }

 protected static List<Long> collectConvertedItems(List<String> items1) {
  List<Long> items2 = new ArrayList<Long>();
  for (String string : items1) {
   items2.add(function(string));
  }
  return items2;
 }
}

Now this seems to make no sense in Java-6, but have great meaning with the usage of Streams in Java-8.

public class ConvertListType3 {

 public static void main(String[] args) {
  Function<String, Long> function = new Function<String ,Long>() {
   @Override
   public Long apply(String string) {
    return Long.parseLong(string);
   }
  };
  List<Long> items2 = Arrays.asList("1111", "2222", "3333", "4444", "5555", "6666").stream().map(function).collect(Collectors.toList());
 }
}

So what is going on?

Stream is a new entity in the later Java version, that allows functional manipulation of a collection of items(it does not make coffee just yet), so we take the list of strings and create a stream of it for further manipulation.

NOTE that function is now an anonymous type, assigned as a local variable that is passed to the mapping, which returns a new stream with the new generic type defined by the return type of the map Function... This is where the conversion really happens, they called it map (which also makes some sense, mapping from one type to another).

Later there is a call to collect, which in the most abstract description, wraps your new stream in a new wrapper, in our simple case just returns a list with the new type Long.
NOTE, collect can do much more than just make a list.

That is it. I was trying to keep it simple as I recall it was hard for me to get my head around the transition from Java-6 to Java-8, Hope I saved you a few minutes :).

Some Git Quick Command Line Action Reference

Create new repository:
git init

Add remote repository url:
git remote add origin [url-to-repository]

Set remote repository url:
git remote set-url origin [url-to-repository]

Get current remote repository url:
git config --get remote.origin.url

Be sure to know which one to use!!
git reset [--soft|--mixed|--hard|--merge|--keep]

Add Sub-Module/Sub-Repo:
git submodule add [url-to-repository]

Update Sub-Module/Sub-Repo:
git submodule update

Remove reference to a Sub-Module:
git rm -rf --cached [folder-name]

Creates a new local branch:
git checkout -b [branch-name]

Switch to branch:
git checkout [branch-name]

Delete local branch:
git branch -d [branch-name]

Delete local branch(FORCED):
git branch -D [branch-name]

Pushes the current branch, -u sets also the pull branch:
git push -u origin [branch-name]

See the list of your branches:
git branch

Add all new files:
git add -A

Commit changes:
git commit -m"[Your message here]"

Commit changes as someone else(blame - not really):
git commit -m"[Your message here]" --author="John Doe <john@doe.com>"

Push Commits:
git push

If when checking you git status you see "Head detached from xxxxx" using the following is the simplest solution:
git config --global push.default simple

Fetch remote commits:
git fetch

Update local copy:
git pull

Create Tag:
git tag your-tag-label

Push tag: (Use -f to override existing tags in the remote repo)
git push origin ["your tag label"] -f

I know there are far more commands, but as a starting point this is a good collection of actions.
If you have some common commands you use that I've left out, let me know.

Tuesday, April 1, 2014

Setup your Java 8 Eclipse Project

If the time had come and you can easily download and install Eclipse with Java 8 support, great... if not, try this out: Setup Eclipse with Java 8 and Lambda expressions

Setup a Java 8 project:
  • Create a Java project
  • Make sure you have a Java 8 JDK installed in Eclipse goto: window > preferences > Java > Installed JREs, and if not add it!
  • If you would like your entire workspace to be configured to work with Java 8 perform the flowing action in window > preferences. Otherwise perform these on the project properties.
  • You would have to make sure that your compiler compliance level match 1.8:
    **> Java Compiler, and make sure the compliance level is set to 1.8.
  • Make sure the Java library used in the project is the Java 8 JDK at: **> Java Build Path
  • Go to this link and this link, copy the classes as string(Yeah simply mark it all and copy it)

    And now...
  • Click on a package in your project and paste the text(Yeah simply paste the "text" onto the package in the Package Explorer!)
  • Poof... you have a two classes in that package(I just love Eclipse don't you!?).
  • It should compile and be executable.

Let me know if you had issues, so I can make this better!

Setup Eclipse with Java 8 and Lambda expressions

I thought this would be a walk in the park... but this was annoying as F***, I've spent a half a day searching Google only to find a pile of rubbish that lead to dead links and wrong instructions to download versions of Eclipse that don't do the trick or take over 3 hours to download(DEAR GOD 3 HOURS), and a bunch instruction about a pre-release Eclipse versions which does not work!

So... what does work:


Took exactly a couple of minutes to get it all set up...

Sunday, July 28, 2013

Check if the device has Internet

On many platform, and specifically on mobile devices, there is a constant need to know if there is a connection to the internet (or the outer world).

I've seen countless Android implementations, trying to figure and configure the network states, attempting to understand if the underline network can access the outer world or not, I've also wrote one... :(

Thing about all these implementations, they all fail the scenario where the device is connected to a network, which is not connected to the outer world, for example a router which is not connected to the wall...

Today, I bring you a very simple very easy way to perform this check:

private void checkWebConnectiity()
  throws IOException {
 Socket socket = null;
 try {
  socket = new Socket("your.domain.com", 80);
 } catch (IOException e) {
  throw e;
 } finally {
  if (socket != null)
   try {
    socket.close();
   } catch (IOException e) {
    logWarning("Ignoring...", e);
   }
 }
}

This covers most of the cases you would need, and is an absolute check, to whether or not you have access to the internet.

You can also return a boolean for your satisfaction, I required an exception to determine the cause of error...

Saturday, February 2, 2013

JavaFX in a Swing application

I've tried multiple libraries to play audio before settling with JavaFX, and they all sucked. These were not intuitive, and not easy to operate.

JavaFX on the other hand, is simple quick and does the work elegantly. There are a few issues I have with their design such as:

  • No exception throwing!!!
  • When playing media there are three threads been created and destroyed rapidly, for the entire duration of the playing. (WTH???)
In any case, I've needed a way to play my audio files but I didn't like this sort of API, so I've wrapped it with my own interfaces and all, but then I've learned that JavaFX needed to be initialized or it would throw:

java.lang.IllegalStateException: Toolkit not initialized

So... here is what you need to do:

 private void initJavaFX() {
  final CountDownLatch latch = new CountDownLatch(1);

  new Thread(new Runnable() {

   @Override
   public void run() {
    @SuppressWarnings("unused")
    JFXPanel p = new JFXPanel();
    latch.countDown();
   }
  }, "JavaFX-initializer").start();
  try {
   latch.await();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

This would initialize JavaFX framework, and allow you to play media...

Sunday, September 30, 2012

Licensing your projects using maven

Well, I have to admit I didn't expect that.

I didn't expect to bump into a Maven plugin that really actually does all the work, so far 100% safe, generic, adaptable, and in less then a day, I've licensed over 250 projects, with different licenses groups, it was very very simple, and straight forward.

I also got something extra in addition to my licensing, implementing it forced me to define my poms better so the groups would share parents, and so on to the top most Maven parent pom, that defines the licensing.

First this is for Java source projects, using the Eclipse IDE, and building projects with Maven, you could also have Java Android projects...

This is the Maven licensing plugin we would be working with.
This is the Maven remote resources plugin we would be working with..

If you would browse a bit in the comments of the first link you would see a comment about the remote-resources plugin, so I gave it a go, worked, like a charm...

Setup:

We would need a Maven License Artifact(project), for the remote resources plugin.
It's pom should look somewhat like this:


<project
 xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.nu.art.software</groupId>
 <artifactId>mm-project-licenser</artifactId>
 <version>0.0.1</version>
 <packaging>jar</packaging>

 <name>_MavenMM-Project-Licenser</name>
 <url>http://maven.apache.org</url>

 <properties>

 </properties>
 
 <build>
  <plugins>
   <plugin>
    <artifactId>maven-remote-resources-plugin</artifactId>
    <version>1.3</version>
    <executions>
     <execution>
      <goals>
       <goal>bundle</goal>
      </goals>
     </execution>
    </executions>
    <configuration>
     <includes>
      <include>nu-art-property-license-v1.0.txt</include>
      <include>mit-license.txt</include>
      <include>apache-license-v2.0.txt</include>
      <include>comment-style-license-header.xml</include>
     </includes>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
 </dependencies>
</project>


In the resources folder of that project I hold the licenses files... and the comment-style I wanted:


apache-license-v2.0.txt:

-----------------------------------------------------------------------------
 Copyright ${founded.year}-${current.year}, '${company}' AND/OR '${owner}' 
 
 For support you may email: <${email}>
   
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-----------------------------------------------------------------------------
 
 Last Builder: ${user.name}


comment-style-license-header.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<additionalHeaders>
    <javadoc_style>
        <firstLine>/*</firstLine>
        <beforeEachLine> * </beforeEachLine>
        <endLine> */</endLine>
        <!--skipLine></skipLine-->
        <firstLineDetectionPattern>(\s|\t)*/\*.*$</firstLineDetectionPattern>
        <lastLineDetectionPattern>.*\*/(\s|\t)*$</lastLineDetectionPattern>
        <allowBlankLines>false</allowBlankLines>
        <isMultiline>true</isMultiline>
    </javadoc_style>
</additionalHeaders>

Next is the licensed project pom, since the license plugin is defined in the top most parent pom, I would post snippets of it:
Some properties:
 <properties>
  <license.header>${license.nu-art}</license.header>
  <license.header.style>${license.header.style.comment}</license.header.style>
  <license.open-source.default>${license.open-source.apache2.0}</license.open-source.default>

  <license.header.style.comment>${project.build.directory}/maven-shared-archive-resources/comment-style-license-header.xml</license.header.style.comment>
  <license.open-source.apache2.0>${project.build.directory}/maven-shared-archive-resources/apache-license-v2.0.txt</license.open-source.apache2.0>
  <license.mit>${project.build.directory}/maven-shared-archive-resources/mit-license.txt</license.mit>
  <license.nu-art>${project.build.directory}/maven-shared-archive-resources/nu-art-property-license-v1.0.txt</license.nu-art>
 </properties>


And a licensing profile:
 <profile>
  <id>add-licenses</id>
  <build>
   <plugins>
    <plugin>
     <groupId>com.mycila.maven-license-plugin</groupId>
     <artifactId>maven-license-plugin</artifactId>
     <version>1.10.b1</version>
     <configuration>
      <basedir>${project.sourceDirectory}</basedir>
      <header>${license.header}</header>
      <failIfMissing>true</failIfMissing>
      <aggregate>true</aggregate>
      <strictCheck>true</strictCheck>
      <properties>
       <owner>${owner} AKA ${nickname}</owner>
       <company>${company.name}</company>
       <founded.year>${company.founded.year}</founded.year>
       <current.year>${current.year}</current.year>
       <email>${company.support}</email>
       <user.name>${user.name}</user.name>
       <timestamp>${maven.build.timestamp}</timestamp>
      </properties>
      <includes>
       <include>**/*.java</include>
      </includes>
      <excludes>
       <exclude>gen/**/R.java</exclude>
       <exclude>gen/**/BuildConfig.java</exclude>
      </excludes>
      <headerDefinitions>
       <headerDefinition>${license.header.style}</headerDefinition>
      </headerDefinitions>
     </configuration>
     <executions>
      <execution>
       <id>Verify-Licenses</id>
       <phase>verify</phase>
       <goals>
        <goal>check</goal>
       </goals>
      </execution>
      <execution>
       <id>Add-Licenses</id>
       <phase>generate-sources</phase>
       <goals>
        <goal>format</goal>
       </goals>
      </execution>
     </executions>
    </plugin>
   </plugins>
  </build>
 </profile>


And a Remote Resources plugin:
 <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-remote-resources-plugin</artifactId>
  <version>1.3</version>
  <configuration>
   <resourceBundles>
    <resourceBundle>com.nu.art.software:mm-project-licenser:0.0.1</resourceBundle>
   </resourceBundles>
   <attached>false</attached>
  </configuration>
  <executions>
   <execution>
    <phase>generate-sources</phase>
    <goals>
     <goal>process</goal>
    </goals>
   </execution>
  </executions>
 </plugin>

I don't think that there is more to it... if you understand a bit Maven you should be fine together with the links supplied.