Wednesday, July 17, 2013

Mac: Mac OS X Screen capturing shortcuts, without using any application

As I am writing blog posts, articles, books and any kind of documents that requires a screen shots on Mac OS, you will find a tool to do that by default packaged with Mac, Greb and preview tools.

Screenshots can be taken by using the Grab application included with OS X. It is located at /Applications/Utilities/Grab.

Preview can also be used to take screenshots, by using the "Take Screen Shot" submenu in the File menu.

Instead of using the applications above, for the sake of productivity, Mac OS X provides a keyboard shortcuts to control the screen shot taking instead of programs, and they are as the following:
  1. Command-Shift-3:
    Take a screenshot of the screen, and save it as a file on the desktop

  2. Command-Shift-4:
    then select an area: Take a screenshot of an area and save it as a file on the desktop

  3. Command-Shift-4:
    then space, then click a window: Take a screenshot of a window and save it as a file on the desktop

  4. Command-Control-Shift-3:
    Take a screenshot of the screen, and save it to the clipboard

  5. Command-Control-Shift-4:
    then select an area: Take a screenshot of an area and save it to the clipboard

  6. Command-Control-Shift-4:
    then space, then click a window: Take a screenshot of a window and save it to the clipboard

  7. In Leopard and later,
    the following keys can be held down while selecting an area (via Command-Shift-4 or Command-Control-Shift-4):

    1. Space, to lock the size of the selected region and instead move it when the mouse moves
    2. Shift, to resize only one edge of the selected region
    3. Option, to resize the selected region with its center as the anchor point


Monday, July 8, 2013

Java SE 7: Refactoring your legacy java.io.File Code to elegant java.nio.file (NIO.2)


In my previous article, I have introduced all of the new functionalities, features and APIs, which are shipped with Java SE 7 release, and here we will see how to migrate or re-write your old IO to new NIO.2 code.

In my daily projects I am developing, I am depending extensively on I/O usage for exchanging files among my systems for integration, and there are a lot of boilerplate code, validations, exceptions checking and security related issues. Therefor I have decided to refactor my code especially critical one to Java SE 7 NIO.2 APIs.

In this article, I will show you a quick guide on how to refactor and map your legacy IO (Input/Output) code, which is prior to Java SE 7 ( java.io.File class was the only mechanism used for file I/O), to the new java.nio.file APIs which comes with rich and tremendous functionalities as part of Java SE 7 and above.

The Java 7 file I/O API JSR 203, has been completely re-architected in the Java SE 7 release; and because of that, you cannot swap one method for another method.

To use the rich functionality offered by the java.nio.file package, the easiest solution is to use the File.toPath method. If the previous statement is not sufficient for your needs, you must rewrite your file I/O code.

Before we dive into the mapping of the functionalities from legacy IO to the new one from Java 7 NIO, I have question to ask.

Why should I migrate from old IO to new NIO.2?

If you have developed more than a few applications based on java.io.File, then you should be familiar with not only its methods, but also its methods’ drawbacks.

For example, many of these methods do not throw exceptions when they fail, there is no real support for symbolic links, metadata access is inefficient, file renaming across platforms is inconsistent, and some methods do not scale, enhanced security and so on.

Let us begin the refactoring process:

The first milestone of refactoring java.io.File code may be considered the conversion of File objects into java.nio.file.Path objects through the java.io.File.toPath() method:


After conversion, you can exploit the Path features.

However, while this is the easiest solution, it may not always satisfy your needs.

Sometimes you will need to rewrite your file I/O code and align code to java.nio.file classes, and for this, you can use the one-by-one correspondence between the two APIs.

The following Table shows this correspondence; this table will make your code transition from Java 5 or 6 to Java 7 much easier:

Javadoc Description

java.io.File

java.nio.file

Class name correspondence

java.io.File

java.nio.file.Path

Tests this abstract pathname for equality with the given object

File.equals(Object)

Path.equals(Object)

Compares two abstract pathnames lexicographically

File.compareTo(File)

Path.compareTo(Path)

Returns the absolute pathname string of this abstract pathname

File.getAbsolutePath()

Path.toAbsolutePath()

Returns the absolute form of this abstract pathname

File.getAbsoluteFile()

Path.toAbsolutePath()

Returns the canonical pathname string of this abstract pathname

File.getCanonicalPath()

Path.toRealPath(LinkOption...)

Path.normalize()

Returns the canonical form of this abstract pathname

File.getCanonicalFile()

Path.toRealPath(LinkOption...)

Path.normalize()

Constructs a file: URI that represents this abstract pathname

File.toURI()

Path.toUri()

Tests whether the file denoted by this abstract pathname is a normal file

File.isFile()

Files.isRegularFile(Path, LinkOption ...)

Tests whether the file denoted by this abstract pathname is a directory

File.isDirectory()

Files.isDirectory(Path, LinkOption...)

Tests whether the file named by this abstract pathname is a hidden file

File.isHidden()

Files.isHidden(Path)

Tests whether the application can read the file denoted by this abstract pathname

File.canRead()

Files.isReadable(Path)

Tests whether the application can modify the file denoted by this abstract pathname

File.canWrite()

Files.isWritable(Path)

Tests whether the application can execute the file denoted by this abstract pathname

File.canExecute()

Files.isExecutable(Path)

Tests whether the file or directory denoted by this abstract pathname exists

File.exists()

Files.exists(Path, LinkOption...)

Files.notExists(Path, LinkOption ...)

Creates the directory named by this abstract pathname

File.mkdir()

Files.createDirectory(Path,

FileAttribute<?> ...)

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories

File.mkdirs()

Files.createDirectories(Path,

FileAttribute<?> ...)

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist

File.createNewFile()

Files.createFile(Path, FileAttribute<?> ...)

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname

File.list()

File.listFiles()

Files.newDirectoryStream(Path)

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter

File.list(FilenameFilter)

File.listFiles(FileFilter)

File.listFiles(FilenameFilter)

Files.newDirectoryStream(Path, DirectoryStream.Filter<? super Path>)

Files.newDirectoryStream(Path, String)

The length of the file denoted by this abstract pathname

File.length()

Files.size(Path)

Deletes the file or directory denoted by this abstract pathname

File.delete()

Files.delete(Path)

Files.deleteIfExists(Path)

Renames the file denoted by this abstract pathname

File.renameTo(File)

Files.move(Path, Path, CopyOption)

Sets the owner or everybody’s execute permission for this abstract pathname

File.setExecutable(boolean, boolean)

Files.setAttribute(Path, String, Object, LinkOption...)

Sets the owner or everybody’s read permission for this abstract pathname

File.setReadable(boolean, boolean)

Files.setAttribute(Path, String, Object, LinkOption...)

Marks the file or directory named by this abstract pathname so that only read operations are allowed

File.setReadOnly()

Files.setAttribute(Path, String, Object, LinkOption...)

Sets the owner or everybody’s write permission for this abstract pathname

File.setWritable(boolean, boolean)

Files.setAttribute(Path, String, Object, LinkOption...)

Returns the time that the file denoted by this

abstract pathname was last modified

File.lastModified()

Files.getLastModifiedTime(Path path, LinkOption... options)

Sets the last-modified time of the file or directory named by this abstract pathname

File.setLastModified(long)

Files.setLastModifiedTime(Path, FileTime)

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name

File.createTempFile(String, String)

Files.createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)

Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name

File.createTempFile(String, String, File)

Files.createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)

Returns the size of the partition named by this abstract pathname

File.getTotalSpace()

FileStore.getTotalSpace()

Returns the number of unallocated bytes in the partition named by this abstract path name

File.getFreeSpace()

FileStore.getUnallocatedSpace()

Returns the number of bytes available to this

virtual machine on the partition named by this abstract pathname

File.getUsableSpace()

FilesStore.getUsableSpace()

Lists the available file system roots

File.listRoots()

FileSystem.getRootDirectories()

Random access file

java.io.RandomAccessFile

java.nio.channels.SeekableByteChannel

Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates

File.deleteOnExit()

Replaced by the DELETE_ON_CLOSE option

Combines two paths

new File(parent,"new_file")

parent.resolve("new_file")

Happy conversion, refactoring, mapping, and migrating IO from earlier JDKs to new JDK7 NIO2 :)

References:
  1. JDK7: Part 1- The power of java 7 NIO.2(JSR 203)(important concepts).
  2. File I/O(Featuring NIO.2).
  3. Package java.nio.file.
  4. Package java.io.
  5. File class.

JavaZone 2013: Javapocalypse, "Without Java you can't live :)"

"It's supposed to write once, run everywhere. But it's more like write once, ruin everything..."

http://www.javazone.no



Saturday, June 22, 2013

Git: The most commonly used git commands


On my daily bases working with git (DVCS), I found that the most common commands I am using every time are the following commands.

And I have made some aliases for some of them for eases of access and use; check this link on how to make aliases or shortcuts for your commands.

Command

Work description

add    

Add file contents to the index. When new or modified files are ready for the next commit, they must first be staged with the add command. Files can be staged one by one, by folder name, or by wildcard pattern.

bisect 

Find by binary search the change that introduced a bug

branch 

List, create, or delete branches

checkout

Checkout a branch or paths to the working tree

clone  

Clone a repository into a new directory

commit 

Once all desired files are added and staged, a commit command transactionally saves the pending additions to the local repository.

diff   

Show changes between commits, commit and working tree, etc

fetch  

Download objects and refs from another repository

grep   

Print lines matching a pattern

init

Create an empty Git repository or reinitialize an existing one

log    

Show commit logs

merge

Join two or more development histories together

mv

Move or rename a file, a directory, or a symlink

pull

Fetch from and merge with another repository or a local branch

push   

Update remote refs along with associated objects

rebase 

Rebasing is the rewinding of existing commits on a branch with the intent of moving the branch start point forward, then replaying the rewound commits. This allows developers to test their branch changes safely in isolation on their private branch just as if they were made on top of the mainline code, including any recent mainline bug fixes.

reset  

Reset current HEAD to the specified state

rm

Remove files from the working tree and from the index

show   

Show various types of objects

status 

Show the working tree status, and check the current status of a project’s local directories and files, such as modified, new, deleted, or untracked.

tag    

Git provides tagging to mark a specific commit in your timeline of changes, and serve as a useful identifier in history. A tag can be created for any commit in history by passing the commit hash. If no commit hash is provided, the most recent commit (i.e. HEAD) will be used by default.


For more information of each command and its related options, from command line on windows or terminal on Mac issue the following command

'git help ' to See more information on a specific command.

Friday, June 21, 2013

Mac: How to prevent your Mac from Sleeping !!!

While I am downloading, updating programs or even my Mac, after a while I found my Mac goes to sleep automatically even if it plugs to the power adapter.

The main problem here is that, the wireless network get interrupted and no more download in progress, unless I return it back from sleep mode.

There are 2 solutions for this issue:
  1. Changing the computer sleeping option from energy saving option under system preferences, as the following:
    From Mac general menu click on Mac icon → System preferences → Energy Saver → change your Computer sleep slider to “Never”, on battery and power adapter. (It doesn’t work for me). I will check and try other options I may miss.

  2. Use Caffeine program, it could be downloaded from Mac App store or from here, it's free application and very popular one.

I prefer the second option, mainly because there are times when I want my Mac book to sleep and don't want to keep changing the settings. Just one click of the coffee cup does it.
Caffeine

Caffeine is a tiny program that puts an icon in the right side of your menu bar. Click it to prevent your Mac from automatically going to sleep, dimming the screen or starting screen savers. Click it again to go back. Hold down the Command key while clicking to show the menu.

The menu now has a sub-menu for deactivating Caffeine automatically after a number of minutes.

Works just great. Computers need no sleep, people do.:)