Wednesday, November 26, 2014

Adding Keyboard Shortcuts in Eclipse

Adding keyboard shortcuts can help develop code much faster. For instance, when refactoring it is common practice to move multiple lines of code up, down , right, left. In Eclipse->Window->Preferences->General->Keys, change the following:
Bind "Shift Left" to Shift+Alt+Left
Bind "Shift Right" to Shift+Alt+Right
Also, you may want to show line numbers: In Eclipse->Window->Editors->Text Editors->Show line numbers

This post was reposted from http://scottizu.wordpress.com/2013/08/19/adding-keyboard-shortcuts-in-eclipse/, originally written on August 19th, 2013.

Working with Compressed Files on Windows

Files such as ".tar" are typically created on a Unix machine and represent Tarballs, created using the Tar archiving system, which is similar to the Zip archiving system on Windows.

To Extract Files from a Tar archive, you may go to 7 Zip, click Download for the 32 Bit 7 Zip 9.20.

Files such as ".7z" are actually created by 7 Zip, so need to be extracted using 7 Zip.

There are various compression schemes used with the Tar archiving system. For example, a ".tar.bz2" extension represents Tar archive and Bzip2 compression. If you know the appropriate command, you may be able to decompress the file directly from the Git command prompt:

tar -jxvf "/c/Users/Scott/Desktop/mscore-1.3.tar.bz2"


This post was reposted from http://scottizu.wordpress.com/2013/08/18/working-with-compressed-files-on-windows/, originally written on August 18th, 2013.

Monday, November 24, 2014

Executing Javascript on Various Web Pages

Option 1: Execute via Drag and Drop

  • Open a webpage in Google Chrome
  • Highlight the code below and drag it onto the Tab just opened:
    javascript:alert('Hello World');
Note: This method works well for a one click execution of your code. This allows demos directly from a tutorial or documentation page.
Note: This may not work in Firefox but depends on the browser configuration for javascript.
Note: This link may also be dragged into the Firefox Bookmarks Menu or the Google Chrome Bookmarks Toolbar.
Note: Instead of dragging the whole javascript code, you may also drag a hyperlink like this: Hello World Bookmark. This was created from the following html:
<a href="javascript:alert('Hello World');">Hello World Bookmark</a>

Option 2: Execute via Address Bar

  • Open a webpage in Google Chrome
  • Type the following into the address bar:
    javascript:alert('Hello World');
  • Press Enter
Note: This may not work in Firefox but depends on the browser configuration for javascript.
Note: When copying this code, make sure that the prefix "javascript:" is copied. In some cases, this will have to be manually typed.

Option 3: Execute via Console

  • Open a webpage in Google Chrome or Firefox
  • Right click the page, Inspect Element
  • Switch to the Console Tab
  • Type the following code:
    javascript:alert('Hello World');
  • Press Enter
Note: Accessing the console will vary depending on the browser and plugins. However, in most cases you need the previx "javascript:".

Option 4: Execute via Bookmark

  • Open a webpage in Google Chrome or Firefox
  • Go to the Bookmark Menu and select the Bookmark
Note: Option 1 above shows how to create a new bookmark via drag and drop. However, below are instructions on how to manually create a Bookmark which will execute javascript code.

Manually Creating a Bookmark

  • Open a webpage in Firefox
  • From the Bookmark Menu, Bookmark This Page
  • From the Bookmark Menu, Right Click the new Bookmark, Properties
  • Change the Name to "Hello World Bookmark"
  • Change the Location to "javascript:alert('Hello World');"
  • Save the bookmark
Note: Similar directions will work in Google Chrome.

Hosting Your Javascript Code

For more complicated javascript, I suggest hosting the main javascript code on a server. This requires a few pieces:
  • Executing the following javascript code through one of the options previously mentioned on this page:
    javascript:addScript=function(){s=document.getElementById("bmScript");if(s){document.body.removeChild(s);}s=document.createElement("script");s.id="bmScript";s.src="http://localhost:8080/HelloWorld.js";document.body.appendChild(s);};void(addScript());
  • Placing the javascript code on the server (for example, if using Tomcat as a server, the above javascript code assumes a file HelloWorld.js is placed in the ROOT Tomcat directory)
  • Running a server somewhere (for example, if using Tomcat as a server, the above javascript code assumes a Tomcat server is running on the same machine which is executing the code so that localhost:8080 is available)
Note: The javascript here, which will be executed on the page adds a script element to the page. When the script element is added, it will also be loaded. At this point, the src found on the server will be executed as well.

Sunday, November 23, 2014

An Introduction to Java Project Management

At this point, our project has the following, in order of importance:

Programming Language: Java

There are many other programming languages such as JavaScript, C, C++, C#, Perl, Python. After you write a computer program, you will need a compiler (or interpreter) to run that program. In order to compile C/C++ code, for example, you might use gcc.exe/g++.exe, respectively.

Build Manager: Maven

Another common build manager is Ant. In order to facilitate creating a single executable program that people can actually install and use, you will need a build manager. Build managers also help to import libraries and manage other resources (files, images, etc). In order to build C/C++ code, for example, you might use cmake (Makefile).

Integrated Development Environment (IDE): Eclipse

Common IDEs include Netbeans and IntelliJ. A good IDE will help you to build programs quickly and have lots of shortcuts to perform common tasks like starting with a template for new classes or importing other classes. In order to develop C/C++ code, for example, you might use Visual Studio C++.

Automated Testing: JUnit

For Java, JUnit really is the standard for automated testing. Agile methodologies such as SCRUM and Extreme Programming took down 6 month development cycles to 1 month. This meant getting your services out to customers quicker.

Version Control: Git

Other version control programs include WinCVS, SubVersion and Perforce. After you have been developing for a while, you will want to release different versions of your program. It can be helpful to explore a source code repository to compare, for instance, your source code from version 1.0 to your source code from version 2.0. And here are some additional things to incorporate into your project:

Bug and Feature Tracking: JIRA

There are also tools like BugZilla. A good rule of thumb is to have a few Wow! features and then deliver 20 percent of the desired features. Tools like JIRA allow you to prioritize all the great things you want to deliver while allowing the capability to deliver a solid product by really focusing on what you need to deliver.

Collaboration Tool: Wiki

JIRA also comes with Confluence. A Wiki page gives people a voice! Wiki pages, like blogs are very easy to use to share ideas and keep the communication and creative juices flowing. They can document resources and tutorials. Any new programmer should be able to join a new team and be up and running in a day. This includes being able to configure their personal development environment and then download and verify code.

Continuous Integration Tool: Bamboo

There is also Jenkins. A Continuous integration tool allows multiple developers to work in parallel. Typically, when a new developer commits code to the code base, you want a new build to be created, deployed and tested. Then, you want immediate feedback to know if the new commit broke previously working features. A continuous integration tool helps you to do this and provides the capability to send e-mails in the case things aren't working correctly, all automated, of course.

Database: MySQL

Once you have a lot of data that you need to store, you will want to add Database support. This allows you to hold customer names, addresses, etc or any other data your program uses.

Application Server: Geronimo

Apache has a Web Server for web pages and also has Tomcat. If your program has a lot of services that are needed by a lot of clients, you will want to look into using an application server.

This post was reposted from http://scottizu.wordpress.com/2013/08/18/an-introduction-to-java-project-management/, originally written on August 18th, 2013.

Adding an external Jar to a Maven Project (JFugue)

In this article, we show how to manually download an external jar file and install it in your local Maven repository. It is possible to automatically download from a third party central Maven repository or from your own central Maven repository. We will use JFugue 4 to demonstrate. I googled "java program to play a middle c", clicked JFugue - Java Music Programming API, clicked www.jfugue.org, clicked Download, clicked jfugue-4.0.3.jar. I googled "JFugue 4.0.3 Maven Dependency" to find the following information about JFugue:
<dependency>
   <groupId>org</groupId>
   <artifactId>jfugue</artifactId>
   <version>4.0.3</version>
</dependency>
  1. Download JFugue 4.0.3 to your Desktop.
  2. Install the jar into your local Maven repository from the Windows Command Prompt (see maven.apache.org):
    "C:\apache-maven-3.1.0\bin\mvn" install:install-file -Dfile="C:\Users\Scott\Desktop\jfugue-4.0.3.jar" -Dpackaging=jar -DgroupId=org -DartifactId=jfugue -Dversion=4.0.3
  3. Add the dependency xml above to your project's pom.xml file (ie "C:\Users\Scott\workspace\myrepo\my-app\pom.xml"):
    ...
    <dependencies>
       <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
       </dependency>
       <dependency>
          <groupId>org</groupId>
          <artifactId>jfugue</artifactId>
          <version>4.0.3</version>
       </dependency>
    </dependencies>
    ...
  4. Recompile the new pom.xml file:
    cd "C:\Users\Scott\workspace\myrepo\my-app"
    mvn clean compile eclipse:eclipse
  5. In Eclipse, Project Explorer, right click on my-app->Refresh (F5).
  6. Add new code to your main function:
     public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
            Player player = new Player();
            Pattern pattern = new Pattern("C D E F G A B");
            player.play(pattern);
            System.exit(0);
        }
  7. Run As-Java Application.
You can now add several different types of jars and reuse lots of existing code!

This post was reposted from http://scottizu.wordpress.com/2013/08/18/adding-an-external-jar-to-a-maven-project-jfugue/, originally written on August 18th, 2013.

An Introduction to Java Sound

This article talks about how to include sound into your project. We will assume you have a .wav file to input into your program. Sound files can be created and edited with Audacity. I googled Audacity, selected Audacity: Free Audio Editor and Recorder (Source Forge), Download, Audacity for Windows®, Audacity 2.0.3 installer. We will be adding to the project created in the previous posts. I have the following directory structure:
  • "C:\Users\Scott\workspace\myrepo" is a clone of the myrepo.git central repository.
  • "C:\Users\Scott\workspace\myrepo\my-app" is the project folder for my Maven/Java Project.
  1. Configure your input and output directories for your project.
    • In the my-app folder (project folder) add two new directories, input and output.
    • In the output folder create a .gitignore with the following two lines:
    • Note: To create the .gitignore file with Notepad, you can create a new Text Document, edit in Notepad, then File->Save As, and Enter File name: ".gitignore" (include the double quotes here) and Save as type: "All Files".
    • Note: Git doesn't track folders, just files. We want other developers to get the output folder when they clone the central repository but we don't want them to get all the files in the output folder. This setup ensures that they get only the output folder and the .gitignore file.
  2. Create input.wav using Audacity.
    • Install Audacity.
    • Launch Audacity.
    • Create a .wav file that is about ten seconds of continuous sound.
    • Name the .wav file input.wav and save the file to your input folder (ie "C:\Users\Scott\workspace\myrepo\my-app\input\input.wav").
    • Note: In Audacity, you can either open a file or record sound.
    • Note: In Audacity, you can use the Selection Tool and Trim Audio to extract a few seconds.
    • Note: In Audacity, you can File->Export and Enter Save as type: "WAV (Microsoft) signed 16 bit PCM.
  3. Create the WavFileHelper Class.
    • In Eclipse, Package Explorer, right click on src/main/java->New->Package, Enter "com.mycompany.app.util".
    • In Eclipse, Package Explorer, right click on the com.mycompany.app.util package->New->Class, Enter "WavFileHelper.
    • Add the following code:
      package com.mycompany.app.util;

      import java.io.*;
      import java.nio.ByteBuffer;
      import java.nio.ByteOrder;
      import java.util.LinkedHashMap;

      import javax.sound.sampled.*;

      /**
       * This class reads a .wav file and converts it to a bunch of byte arrays.
       * 
       * The info represented by these byte arrays is then printed out.
       * 
       * An example of playing these byte arrays with the speakers is used.
       * 
       * It also converts the byte arrays to a .wav file.
       * 
       * An extension of this concept can record from a microphone. In this case, some
       * values like sampling rate would need to be assumed.
       * 
       * See https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ for .wav file
       * spec
       * 
       * @author sizu
       */

      public class WavFileHelper {

          public static void main(String[] args) {
              final String NEWLINE = "\n";
              int recordingSampleRate = 22050;
              short recordingBitsPerSample = 16;
              short recordingNumChannels = 2;
              String inputPath = "/Users/Scott/workspace/myrepo/my-app/input/input.wav"// Place the wav file in the top level
                                                  // directory, ie S:/input.wav
              String outputPath = "/Users/Scott/workspace/myrepo/my-app/output/output.wav";
              String recordedPath = "/Users/Scott/workspace/myrepo/my-app/output/capture.wav";

              System.out.println("START");
              try {
                  if (!new File(inputPath).exists()) {
                      System.err.println("Error loading file:"
                              + new File(inputPath).getAbsolutePath());
                  }

                  WavFileHelper wavFileHelper = new WavFileHelper();

                  WavData wavRecordData = new WavData();
                  wavRecordData.put(WaveSection.SAMPLE_RATE, recordingSampleRate);
                  wavRecordData.put(WaveSection.BITS_PER_SAMPLE,
                          recordingBitsPerSample);
                  wavRecordData.put(WaveSection.NUM_CHANNELS, recordingNumChannels);

                  System.out.println(NEWLINE + "CONVERT WAV FILE TO BYTE ARRAY");
                  WavData wavInputData = wavFileHelper.read(new File(inputPath));

                  System.out.println(NEWLINE + "CONVERT BYTE ARRAY TO WAV FILE");
                  wavFileHelper.write(new File(outputPath), wavInputData);

                  System.out.println(NEWLINE
                          + "DISPLAY BYTE ARRAY INFORMATION FOR INPUT FILE");
                  wavInputData.printByteInfo();

                  System.out
                          .println(NEWLINE
                                  + "START RECORDING - You can connect the microphone to the speakers");
                  WavAudioRecorder recorder = new WavFileHelper.WavAudioRecorder(
                          wavRecordData);
                  recorder.startRecording();

                  System.out.println(NEWLINE
                          + "PLAY BYTE ARRAY (THIS WILL BE RECORDED)");
                  WavAudioPlayer player = new WavFileHelper.WavAudioPlayer(
                          wavInputData);
                  player.playAudio();

                  System.out.println(NEWLINE + "STOP RECORDING FOR RECORDING");
                  recorder.stopRecording();

                  System.out.println(NEWLINE + "DISPLAY BYTE ARRAY INFORMATION");
                  wavRecordData.printByteInfo();

                  System.out.println(NEWLINE + "SAVE RECORDING IN WAV FILE");
                  wavFileHelper.write(new File(recordedPath), wavRecordData);

              } catch (Exception ex) {
                  ex.printStackTrace();
              }
              System.out.println("FINISH");
          }

          public WavData read(File inputFile) throws Exception {
              WavData returnVal = new WavData();

              // Analyze redundant info
              int dataSize = (int) inputFile.length() - WavData.HEADER_SIZE;
              WaveSection.DATA.numBytes = dataSize; // Can't have two threads
                                                      // using this at the same
                                                      // time

              // Read from File
              DataInputStream inFile = new DataInputStream(new FileInputStream(
                      inputFile));

              for (WaveSection waveSection : WaveSection.values()) {
                  byte[] readBytes = new byte[waveSection.numBytes];
                  for (int i = 0; i < waveSection.numBytes; i++) {
                      readBytes[i] = inFile.readByte();
                  }
                  returnVal.put(waveSection, readBytes);
              }

              inFile.close();

              return returnVal;
          }

          public void write(File outputFile, WavData waveData) throws Exception {
              // Analyze redundant info
              int dataSize = waveData.get(WaveSection.DATA).length;
              waveData.put(WaveSection.CHUNK_SIZE, dataSize + 36);
              waveData.put(WaveSection.SUBCHUNK2_SIZE, dataSize);

              int byteRate = waveData.getInt(WaveSection.SAMPLE_RATE)
                      * waveData.getShort(WaveSection.BLOCK_ALIGN);
              waveData.put(WaveSection.BYTE_RATE, byteRate);

              // Write to File
              DataOutputStream dataOutputStream = new DataOutputStream(
                      new FileOutputStream(outputFile));

              for (WaveSection waveSection : WaveSection.values()) {
                  dataOutputStream.write(waveData.getBytes(waveSection));
              }

              dataOutputStream.close();
          }

          public static enum WaveSection {
              // 12 Bytes
              CHUNK_ID(4, ByteOrder.BIG_ENDIAN), CHUNK_SIZE(4,
                      ByteOrder.LITTLE_ENDIAN), FORMAT(4, ByteOrder.BIG_ENDIAN),

              // 24 Bytes
              SUBCHUNK1_ID(4, ByteOrder.BIG_ENDIAN), SUBCHUNK1_SIZE(4,
                      ByteOrder.LITTLE_ENDIAN), AUDIO_FORMAT(2,
                      ByteOrder.LITTLE_ENDIAN), NUM_CHANNELS(2,
                      ByteOrder.LITTLE_ENDIAN), SAMPLE_RATE(4,
                      ByteOrder.LITTLE_ENDIAN), BYTE_RATE(4, ByteOrder.LITTLE_ENDIAN), BLOCK_ALIGN(
                      2, ByteOrder.LITTLE_ENDIAN), BITS_PER_SAMPLE(2,
                      ByteOrder.LITTLE_ENDIAN),

              // 8 Bytes
              SUBCHUNK2_ID(4, ByteOrder.BIG_ENDIAN), SUBCHUNK2_SIZE(4,
                      ByteOrder.LITTLE_ENDIAN), DATA(0, ByteOrder.LITTLE_ENDIAN), ;

              private Integer numBytes;
              private ByteOrder endian;

              WaveSection(Integer numBytes, ByteOrder endian) {
                  this.numBytes = numBytes;
                  this.endian = endian;
              }
          }

          public static class WavData extends LinkedHashMap {
              static final long serialVersionUID = 1;
              static int HEADER_SIZE = 44; // There are 44 bits before the data
                                              // section
              static int DEFAULT_SUBCHUNK1_SIZE = 16;
              static short DEFAULT_AUDIO_FORMAT = 1;
              static short DEFAULT_BLOCK_ALIGN = 4;
              static String DEFAULT_CHUNK_ID = "RIFF";
              static String DEFAULT_FORMAT = "WAVE";
              static String DEFAULT_SUBCHUNK1_ID = "fmt ";
              static String DEFAULT_SUBCHUNK2_ID = "data";

              public WavData() {
                  this.put(WaveSection.CHUNK_ID, DEFAULT_CHUNK_ID);
                  this.put(WaveSection.FORMAT, DEFAULT_FORMAT);
                  this.put(WaveSection.SUBCHUNK1_ID, DEFAULT_SUBCHUNK1_ID);
                  this.put(WaveSection.SUBCHUNK1_SIZE, DEFAULT_SUBCHUNK1_SIZE);
                  this.put(WaveSection.AUDIO_FORMAT, DEFAULT_AUDIO_FORMAT);
                  this.put(WaveSection.BLOCK_ALIGN, DEFAULT_BLOCK_ALIGN);
                  this.put(WaveSection.SUBCHUNK2_ID, DEFAULT_SUBCHUNK2_ID);

                  this.put(WaveSection.CHUNK_SIZE, 0);
                  this.put(WaveSection.SUBCHUNK2_SIZE, 0);
                  this.put(WaveSection.BYTE_RATE, 0);
              }

              public void put(WaveSection waveSection, String value) {
                  byte[] bytes = value.getBytes();
                  this.put(waveSection, bytes);
              }

              public void put(WaveSection waveSection, int value) {
                  byte[] bytes = ByteBuffer.allocate(4)
                          .order(ByteOrder.LITTLE_ENDIAN).putInt(value).array();
                  this.put(waveSection, bytes);
              }

              public void put(WaveSection waveSection, short value) {
                  byte[] bytes = ByteBuffer.allocate(2)
                          .order(ByteOrder.LITTLE_ENDIAN).putShort(value).array();
                  this.put(waveSection, bytes);
              }

              public byte[] getBytes(WaveSection waveSection) {
                  return this.get(waveSection);
              }

              public String getString(WaveSection waveSection) {
                  byte[] bytes = this.get(waveSection);
                  return new String(bytes);
              }

              public int getInt(WaveSection waveSection) {
                  byte[] bytes = this.get(waveSection);
                  return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
                          .getInt();
              }

              public short getShort(WaveSection waveSection) {
                  byte[] bytes = this.get(waveSection);
                  return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
                          .getShort();
              }

              public void printByteInfo() {
                  for (WaveSection waveSection : WaveSection.values()) {
                      if (waveSection.numBytes == 4
                              && waveSection.endian == ByteOrder.BIG_ENDIAN) {
                          System.out.println("SECTION:" + waveSection + ":STRING:"
                                  + this.getString(waveSection));
                      } else if (waveSection.numBytes == 4
                              && waveSection.endian == ByteOrder.LITTLE_ENDIAN) {
                          System.out.println("SECTION:" + waveSection + ":INTEGER:"
                                  + this.getInt(waveSection));
                      } else if (waveSection.numBytes == 2
                              && waveSection.endian == ByteOrder.LITTLE_ENDIAN) {
                          System.out.println("SECTION:" + waveSection + ":SHORT:"
                                  + this.getShort(waveSection));
                      } else {
                          // Data Section
                      }
                  }
              }

              public AudioFormat createAudioFormat() {
                  boolean audioSignedSamples = true// Samples are signed
                  boolean audioBigEndian = false;
                  float sampleRate = (floatthis.getInt(WaveSection.SAMPLE_RATE);
                  int bitsPerSample = (intthis
                          .getShort(WaveSection.BITS_PER_SAMPLE);
                  int numChannels = (intthis.getShort(WaveSection.NUM_CHANNELS);
                  return new AudioFormat(sampleRate, bitsPerSample, numChannels,
                          audioSignedSamples, audioBigEndian);
              }
          }

          public static class WavAudioPlayer {
              WavData waveData = new WavData();

              public WavAudioPlayer(WavData waveData) {
                  this.waveData = waveData;
              }

              public void playAudio() throws Exception {
                  byte[] data = waveData.getBytes(WaveSection.DATA);

                  // Create an audio input stream from byte array
                  AudioFormat audioFormat = waveData.createAudioFormat();
                  InputStream byteArrayInputStream = new ByteArrayInputStream(data);
                  AudioInputStream audioInputStream = new AudioInputStream(
                          byteArrayInputStream, audioFormat, data.length
                                  / audioFormat.getFrameSize());

                  // Write audio input stream to speaker source data line
                  DataLine.Info dataLineInfo = new DataLine.Info(
                          SourceDataLine.class, audioFormat);
                  SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem
                          .getLine(dataLineInfo);
                  sourceDataLine.open(audioFormat);
                  sourceDataLine.start();

                  // Loop through input stream to write to source data line
                  byte[] tempBuffer = new byte[10000];
                  int cnt;
                  while ((cnt = audioInputStream.read(tempBuffer, 0,
                          tempBuffer.length)) != -1) {
                      sourceDataLine.write(tempBuffer, 0, cnt);
                  }

                  // Cleanup
                  sourceDataLine.drain();
                  sourceDataLine.close();
                  byteArrayInputStream.close();
              }
          }

          public static class WavAudioRecorder implements Runnable {
              WavData waveData = new WavData();
              boolean recording = true;
              Thread runningThread;
              ByteArrayOutputStream byteArrayOutputStream;

              public WavAudioRecorder(WavData waveData) {
                  this.waveData = waveData;
              }

              public void startRecording() {
                  this.recording = true;
                  this.runningThread = new Thread(this);
                  runningThread.start();
              }

              @SuppressWarnings("deprecation")
              public WavData stopRecording() throws Exception {
                  this.recording = false;
                  runningThread.stop();

                  waveData.put(WaveSection.DATA, byteArrayOutputStream.toByteArray());

                  return waveData;
              }

              public void run() {
                  try {
                      // Create an audio output stream for byte array
                      byteArrayOutputStream = new ByteArrayOutputStream();

                      // Write audio input stream to speaker source data line
                      AudioFormat audioFormat = waveData.createAudioFormat();
                      DataLine.Info info = new DataLine.Info(TargetDataLine.class,
                              audioFormat);
                      TargetDataLine targetDataLine = (TargetDataLine) AudioSystem
                              .getLine(info);
                      targetDataLine.open(audioFormat);
                      targetDataLine.start();

                      // Loop through target data line to write to output stream
                      int numBytesRead;
                      byte[] data = new byte[targetDataLine.getBufferSize() / 5];
                      while (recording) {
                          numBytesRead = targetDataLine.read(data, 0, data.length);
                          byteArrayOutputStream.write(data, 0, numBytesRead);
                      }

                      // Cleanup
                      targetDataLine.stop();
                      targetDataLine.close();
                      byteArrayOutputStream.close();
                  } catch (Exception ex) {
                      ex.printStackTrace();
                  }
              }
          }
      }
  4. Right click within WavFileHelper->Run As->Java Application.
    • You may also use the short cut: Alt+Shift+X, J.
    • Or from the Windows command prompt:
      "C:\Program Files\Java\jdk1.7.0_25\bin\javac.exe" "C:\Users\Scott\workspace\myrepo\my-app\src\main\java\com\mycompany\app\util\WavFileHelper.java"
      "C:\Program Files\Java\jdk1.7.0_25\bin\java.exe" -classpath "C:\Users\Scott\workspace\myrepo\my-app\src\main\java" com.mycompany.app.util.WavFileHelper
The recorded file may have either no sound or softer sound depending on your speakers and microphone setup. Also, if you have git setup, you should push these changes to your central repository as demonstrated in Step 7 of Adding Git Version Control to Your Project: Part I.

This post was reposted from http://scottizu.wordpress.com/2013/08/18/an-introduction-to-java-sound/, originally written on August 18th, 2013.

Wednesday, November 19, 2014

An Introduction to Branching with Git

This article covers branching in the case that more than one developer will be editing code. This discussion will show how to use the Git Gui to track changes amongst developers and will help to understand how branching works in Git. We start out with following assumptions:
  • Central Repository: "C:\Users\Scott\GitRepos\myrepo.git"
  • (created in the previous post) Ben's Local Repository: "C:\Users\Ben\workspace\myrepo"
  • (created below) Matt's Local Repository: "C:\Users\Matt\workspace\myrepo"
In Git, changes are always done within the current branch and do not affect other branches. Developers can work in their respective branches without breaking the master branch (you can have branches of branches, etc). When they are ready, they can push to the master branch. In this post, we will be using the following three tools below wherever you see "... Run Git Gui, View Git Branches and Check Status ...":
  1. The Git Gui Visualization to see how various git commands work (see Adding Git Version Control to Your Project for more information).
  2. The "git branch -a" command to list all the branches. Green marks the current branch (asterisk). White marks local branches. Red marks central branches.
  3. The "git status" command to see various changes we are making.
Now, to start...
  1. Clone the central repository for a second developer (ie Matt):
    mkdir /c/Users/Matt/workspace/
    cd /c/Users/Matt/workspace/
    git clone /c/Users/Scott/GitRepos/myrepo.git
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • The "git clone" command creates a local repository which is like a snapshot of the central repository.
    • You may make as many clones as you would like, allowing multiple people to push commits to the master branch.
  2. Create a local branch for the first developer (Ben) to work from:
    cd /c/Users/Ben/workspace/myrepo; git checkout master
    git branch dev_Ben
    ... Run Git Gui, View Git Branches and Check Status ...
    git checkout dev_Ben
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • The "git branch dev_Ben" command creates the local dev_Ben branch (green in Git Gui).
    • The "git checkout dev_Ben" command makes dev_Ben the current branch (green/asterisk in Git Branches).
    • The "git branch -d dev_Ben" command can be used to delete the local dev_Ben branch.
  3. Push the new local branch to the central repository:
    cd /c/Users/Ben/workspace/myrepo; git checkout dev_Ben
    git push origin dev_Ben
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • The "git push origin" command pushes the new branch to the central repository to create the central dev_Ben branch (brown in Git Gui).
    • The "git push origin --delete dev_Ben" command can be used to delete the central dev_Ben branch.
  4. Update the second developer's (Matt's) Git Gui visualization:
    cd /c/Users/Matt/workspace/myrepo; git checkout master
    git remote update
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • The "git remote" command updates the view of the central repository.
    • The "git remote" command will not pull in any commits from the central repository and therefore will not change any development being done by Matt. However, Matt can use this to see what has changed in the central repository by Ben.
    • Notice that Matt does not have a local dev_Ben branch since Matt has never checked out the dev_Ben branch. Typically, developers only checkout branches they work in.
  5. Create a local branch for the second developer (Matt) to work from:
    cd /c/Users/Matt/workspace/myrepo; git checkout master
    git branch dev_Matt
    git push origin dev_Matt
    git checkout dev_Matt
    ... Run Git Gui, View Git Branches and Check Status ...
    cd /c/Users/Ben/workspace/myrepo; git checkout dev_Ben
    git remote update
    ... Run Git Gui, View Git Branches and Check Status ...
  6. Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • Notice that Ben has a local master branch (green) and a local dev_Ben branch (green) but does not have a local dev_Matt branch.
    • This is nice because now we can identify whether the Git Gui Visualization belongs to Ben or Matt, respectively.
  7. Have the first developer (Ben) make changes in their branch (dev_Ben):
    cd /c/Users/Ben/workspace/myrepo; git checkout dev_Ben
    touch my-app-readme.txt
    ... Run Git Gui, View Git Branches and Check Status ...
    git add -A
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • The "touch" command just creates a new file.
    • The "git status" command shows the my-app-readme.txt file is untracked before the "git add" command.
    • The "git status" command shows the my-app-readme.txt file is staged for a commit after the "git add" command.
    • The "git reset --hard HEAD" can be used to unstage changes.
    • Notice that Matt cannot see any changes before Ben does a push to the central repository.
  8. Have the first developer (Ben) commit changes to their branch (dev_Ben):
    cd /c/Users/Ben/workspace/myrepo; git checkout dev_Ben
    git commit -m "Added the readme file"
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
  9. Have the first developer (Ben) push changes from their branch (dev_Ben) to the central repository:
    cd /c/Users/Ben/workspace/myrepo; git checkout dev_Ben
    git push origin dev_Ben
    ... Run Git Gui, View Git Branches and Check Status ...
    cd /c/Users/Matt/workspace/myrepo; git checkout dev_Matt
    git remote update
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • After the "git push" command, the central dev_Ben branch (brown in Git Gui) matches the local dev_Ben branch (green in Git Gui).
    • After the "git remote" command, the second developer (Matt) can see any commits made to the central repository.
  10. Pull the changes into the local master branch and then push the changes into the central master branch:
    cd /c/Users/Ben/workspace/myrepo
    git checkout master
    git pull origin dev_Ben
    ... Run Git Gui, View Git Branches and Check Status ...
    git push origin master
    ... Run Git Gui, View Git Branches and Check Status ...
    cd /c/Users/Matt/workspace/myrepo; git checkout dev_Matt
    git remote update
    ... Run Git Gui, View Git Branches and Check Status ...
    Ben's Git Gui Visualization: Matt's Git Gui Visualization:
    • After the "git pull" command, you will see the local master branch (green in Git Gui) matches the central dev_Ben branch (brown in Git Gui).
    • After the "git push" command, you will see the central master branch (brown in Git Gui) matches the local master branch (green in Git Gui).
    • The "git pull origin" command pulls commits from each central branch to the corresponding local branch.
    • The "git pull origin master" command pulls commits from the central master branch to the current local branch.
At this point, Matt will not have Ben's commits from the master branch in any of his local branches. In order to pull Ben's commits, Matt must make the appropriate local branch current via "git checkout" and then run "git pull origin master". If Matt had completed work is his local branch (dev_Matt) and wanted to pull Ben's commits from the master branch, I would suggest pushing that work to his central branch before merging:
cd /c/Users/Matt/workspace/myrepo; git checkout dev_Matt
git add -A
git commit -m "New Changes Before Merging"
git push origin dev_Matt
git pull origin master
After pulling Ben's commits, Matt may have to resolve some conflicts, commit the resolutions and then push them to his central branch:
cd /c/Users/Matt/workspace/myrepo; git checkout dev_Matt
"git commit -a"
... Enter a commit message ...
... Type Esc, Shift+Z, Shift+Z ...
git push origin dev_Matt


This post was reposted from http://scottizu.wordpress.com/2013/08/16/an-introduction-to-branching-with-git/, originally written on August 16th, 2013.

Tuesday, November 18, 2014

Adding Git Version Control to Your Project

Related Pages: http://kahthong.com/2012/05/how-use-google-drive-or-dropbox-host-your-private-git-repositories

Install Git

This section teaches you how to install Git 1.8.3. See feeding.cloud.geek.nz for more information. I googled "Download Git For Windows", selected Download Git for Windows - Git - Downloading Package (Git SCM).
  1. Download the installer to your Desktop.
  2. Select "Run Git from the Windows Command Prompt".
  3. Select "Checkout Windows-style, commit Unix-style line endings".
Now, we will create the central repository and start version control for a project.
  1. Open Git Bash.
  2. Run the following commands to configure Git:
    git config --global user.name "Scott Izu"
    git config --global user.email "scottizu@gmail.com"
    • The "git config" commands setup some common parameters.
    • Replace "Scott Izu" with your name and "scottizu@gmail.com" with your e-mail address.
    • These configurations are needed before you can commit changes and are used to identify who made a given commit.
  3. Run the following commands to create the central repository:
    mkdir /c/Users/Scott/GitRepos/myrepo.git 
    cd /c/Users/Scott/GitRepos/myrepo.git 
    git --bare init --shared
    • The "mkdir" command created a folder (ie "C:\Users\Scott\GitRepos\myrepo.git"). You will need to replace "/c/Users/Scott/GitRepos/myrepo.git" with your central repository folder.
    • The "git init" command turned the folder into a central repository.
    • The central repository is typically setup on a server.
  4. Run the following commands to create a local repository:
    mkdir /c/Users/Ben/workspace/myrepo
    cd /c/Users/Ben/workspace/myrepo
    git init
    git remote add origin /c/Users/Scott/GitRepos/myrepo.git
    git config branch.master.remote origin
    git config branch.master.merge refs/heads/master
    • The "mkdir" command created a folder (ie "C:\Users\Ben\workspace\myrepo"). You will need to replace "/c/Users/Ben/workspace/myrepo" with your local repository folder. Imagine Ben is one developer working on this project.
    • The "git init" command turned the folder into a local repository.
    • The "git remote" command sets the myrepo.git folder as the central repository for this local repository.
    • Origin will be used as a shortcut to reference the central repository.
    • Both the local repository and central repository have no commits yet (Git tracks commits).
  5. You can create a Git Gui Visualization for the local repository:
    • Open the Git Gui.
    • Select "Open Existing Repository".
    • Browse to the folder just created (ie "C:\Users\Ben\workspace\myrepo").
    • Open->Repository->Visualize All Branch History
    • After your first commit, you can reload this visualization by choosing File->Reload from the Git Gui (gitk).
  6. Add some files to the myrepo folder (ie Copy the "C:\Users\Scott\workspace\my-app" Java project folder from the previous post).
  7. Run the following commands to create a commit in the local repository and then push the commit to the central repository:
    cd /c/Users/Ben/workspace/myrepo
    git add -A
    git commit -m "Created the my-app project"
    ... Refresh Git Gui ...
    git push origin master
    ... Refresh Git Gui ...
    Before commit: After commit, before push: After push:
    • The "git add" command stages all changed files in the directory for a commit.
    • The "git commit" command creates a commit. After executing this command, you can ... and see that you have a local (green) branch named master.
    • The "git push" command moves the commit from the local repository to the central repository.
    • This local repository is not connected to a central repository so you should only see the local (green) master branch.
    • After the "git commmit" command, you can see that the commit exists on the local master branch (green).
    • After the "git push" command, you can see that the commit exists on the central master branch (brown).
You may try making some additional changes, commits and pushing those commits to the central repository.  In the future, you will be able to rollback to previous versions of the code by using the commit number.

This post was reposted from http://scottizu.wordpress.com/2013/08/15/adding-git-version-control-to-your-project-part-i/, originally written on August 15th, 2013.