Monday, December 22, 2014

Generating XPATH from a Selenium WebDriver WebElement

Call the method below with 

generateXPATH(element, "");


The output will be something like:

/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[2]/div[1]/input[2]

METHOD
private String generateXPATH(WebElement childElement, String current) {
    String childTag = childElement.getTagName();
    if(childTag.equals("html")) {
        return "/html[1]"+current;
    }
    WebElement parentElement = childElement.findElement(By.xpath("..")); 
    List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
    int count = 0;
    for(int i=0;i<childrenElements.size(); i++) {
        WebElement childrenElement = childrenElements.get(i);
        String childrenElementTag = childrenElement.getTagName();
        if(childTag.equals(childrenElementTag)) {
            count++;
        }
        if(childElement.equals(childrenElement)) {
            return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
        }
    }
    return null;
}

Monday, December 15, 2014

An Introduction to JNI using a Bottom Up Approach: Prologue

The goal of this article is to allow Java developers to include C++ code in their programs. Related Pages: This tutorial is written such that:
  1. Each individual step represents a technology layer:
    • Step 1: C++ Low Level Function
    • Step 2: C++ Main Function
    • Step 3: C Main Function
    • Step 4: Java Main Function
  2. Each individual step is skippable:
    • This means you can start from any step and work your way forward, with some slight modifications.
    • Developers can decide to follow the steps backwards and use a top down approach (by commenting out access to the lower technology layer).
    • When developing new code, developers can decide not to include bottom technology layers (for instance, starting with Step 3 will mean you have no C++ code and are just using Java to run a C Program).
  3. Each individual step is testable:
    • New developers have less variables involved when stuff doesn't work.
    • Developers get immediate feedback regarding whether they are on the right track.
    • Developers can check a technology layer along with lower technology layers (by uncommmenting the main function are recompiling).
    • When debugging code, developers can decide not to include top technology layers (for instance, running the C main function will mean you are not running the Java code and are just checking the functionality of the C and C++ code).
Prerequisites:
  • You need a Java compiler for Windows (ie, see Getting Started with Java's Hello World: Part I).
  • You need a C++ compiler for Windows (ie, download TDM-GCC at tdm-gcc.tdragon.net).
  • Choose a working directory for the C++/C code (ie, preferrably in your project's resources folder, "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls").
Continued at An Introduction to JNI using a Bottom Up Approach: Step 1.

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-introduction/, originally written on August 21st, 2013.

An Introduction to JNI using a Bottom Up Approach: Step 1

Continued from An Introduction to JNI using a Bottom Up Approach: Prologue.

Step 1: C++ Low Level Function

  1. In your working directory, add an empty file, named "PrintOpenWindows.h". This will make the functions available other C/C++ files.
    #ifndef _PRINT_OPEN_WINDOWS_H
    #define _PRINT_OPEN_WINDOWS_H

    #ifdef __cplusplus
            extern "C" {
    #endif
            void printOpenWindowsEntryPoint ();
    #ifdef __cplusplus
            }
    #endif

    #endif
  2. In your working directory, add the following code, in a file named "PrintOpenWindows.cpp":
    #include "PrintOpenWindows.h"
    #include <stdlib.h>
    #include <string.h>
    #include <tchar.h>
    #include <windows.h>
    #include <iostream>

    using namespace std;

    BOOL CALLBACK FindWindowBySubstr(HWND hwnd, LPARAM substring)
    {
        const DWORD TITLE_SIZE = 1024;
        TCHAR windowTitle[TITLE_SIZE];

        if (GetWindowText(hwnd, windowTitle, TITLE_SIZE))
        {
            _tprintf(TEXT("%s\n"), windowTitle);
            // Uncomment to print all windows being enumerated
            if (_tcsstr(windowTitle, LPCTSTR(substring)) != NULL)
            {
                // We found the window! Stop enumerating.
                return false;
            }
        }
        return true// Need to continue enumerating windows
    }

    void printOpenWindowsEntryPoint()
    {
        cout << "PRINT_OPEN_WINDOWS ENTRY START" << endl;
        const TCHAR substring[] = TEXT("Substring");
        EnumWindows(FindWindowBySubstr, (LPARAM)substring);
        cout << "PRINT_OPEN_WINDOWS ENTRY FINISH" << endl;
    }

    int main()
    {
        cout << "PRINT_OPEN_WINDOWS MAIN START" << endl;
        printOpenWindowsEntryPoint();
        cout << "PRINT_OPEN_WINDOWS MAIN FINISH" << endl;
    }
  3. Compile the code and run "PrintOpenWindows.exe", using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

    "C:\MinGW64\bin\g++.exe" -o PrintOpenWindows.exe PrintOpenWindows.cpp

    PrintOpenWindows.exe
Continued at An Introduction to JNI using a Bottom Up Approach: Step 2.

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-step-1/, originally written on August 21st, 2013.

An Introduction to JNI using a Bottom Up Approach: Step 2

Continued from An Introduction to JNI using a Bottom Up Approach: Step 1. Note: These steps may be followed without the first step below, if you remove the two references to PrintOpenWindows in the C++ code and remove "PrintOpenWindows.cpp" from the commands to compile and run "CPPHelper.exe".

Step 2: C++ Main Function

  1. Comment out the main function in "PrintOpenWindows.cpp".
    /*  Uncomment to compile and run PrintOpenWindows.exe 
    int main()
    {
        cout << "PRINT_OPEN_WINDOWS ENTRY START" << endl;
        printOpenWindowsEntryPoint();
        cout << "PRINT_OPEN_WINDOWS ENTRY FINISH" << endl;
    }
    */
  2. In your working directory, add an empty file, named "CPPHelper.h"
    #ifndef _CPP_HELPER_H
    #define _CPP_HELPER_H

    #ifdef __cplusplus
            extern "C" {
    #endif
            void cppHelperEntryPoint();
    #ifdef __cplusplus
            }
    #endif

    #endif
  3. In your working directory, add the following code, in a file named "CPPHelper.cpp":
    #include "CPPHelper.h"
    #include "PrintOpenWindows.h" // Comment to ignore PrintOpenWindows
    #include  <iostream>

    using namespace std;

    void cppHelperExitPoint()
    {
        cout << "CPP_HELPER EXIT START" << endl;
        printOpenWindowsEntryPoint(); // Comment to ignore PrintOpenWindows
        cout << "CPP_HELPER EXIT FINISH" << endl;
    }

    int main()
    {
        cout << "CPP_HELPER MAIN START" << endl;
        cppHelperExitPoint();
        cout << "CPP_HELPER MAIN FINISH" << endl;
    }

    void cppHelperEntryPoint()
    {
        cout << "CPP_HELPER ENTRY START" << endl;
        cppHelperExitPoint(); // Comment to ignore PrintOpenWindows
        cout << "CPP_HELPER ENTRY FINISH" << endl;
    }
  4. Compile the code and run "CPPHelper.exe", using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

    "C:\MinGW64\bin\g++.exe" -o CPPHelper.exe CPPHelper.cpp PrintOpenWindows.cpp

    CPPHelper.exe
Continued at An Introduction to JNI using a Bottom Up Approach: Step 3.

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-step-2/, originally written on August 21st, 2013.

An Introduction to JNI using a Bottom Up Approach: Step 3

Continued from An Introduction to JNI using a Bottom Up Approach: Step 2. Note: These steps may be followed without the first step below, if you remove the two references to CPPHelper in the C code and remove "CPPHelper.cpp" from the commands to compile and run "CToCPPHelper.exe".

Step 3: C Main Function

  1. Comment out the main function in "CPPHelper.cpp".
    /*  Uncomment to compile and run CPPHelper.exe  
    int main()
    {
     cout << "CPP_HELPER MAIN START" << endl;
     cppHelperEntryPoint();
     cout << "CPP_HELPER MAIN FINISH" << endl;
    }
    */
  2. In your working directory, add an empty file, named "CToCPPHelper.h"
  3. In your working directory, add the following code, in a file named "CToCPPHelper.cpp":
    #include "CToCPPHelper.h"
    #include "CPPHelper.h" // Comment to ignore CPPHelper
    #include <jni.h>
    #include <stdio.h>

    void cToCPPHelperExitPoint() {
        printf("C_TO_CPP_HELPER EXIT START\n");
        cppHelperEntryPoint(); // Comment to ignore CPPHelper
        printf("C_TO_CPP_HELPER EXIT FINISH\n");
    }

    int main()
    {
        printf("C_TO_CPP_HELPER MAIN START\n");
        cToCPPHelperExitPoint();
        printf("C_TO_CPP_HELPER MAIN FINISH\n");
    }

    JNIEXPORT void JNICALL Java_com_mycompany_myapp_JavaToCHelper_cToCPPHelperEntryPoint(JNIEnv *env, jobject thisObj)
    {
        printf("C_TO_CPP_HELPER ENTRY START\n");
        cToCPPHelperExitPoint(); // Comment to ignore CPPEntryPoint
        printf("C_TO_CPP_HELPER ENTRY FINISH\n");
    }
  4. Compile the code and run "CToCPPHelper.exe", using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

    "C:\MinGW64\bin\g++.exe" -I"C:\Program Files\Java\jdk1.6.0_26\include" -I"C:\Program Files\Java\jdk1.6.0_26\include\win32" -o CToCPPHelper.exe CToCPPHelper.c CPPHelper.cpp PrintOpenWindows.cpp

    CToCPPHelper.exe
Continued at An Introduction to JNI using a Bottom Up Approach: Step 4.

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-step-3/, originally written on August 21st, 2013.

An Introduction to JNI using a Bottom Up Approach: Step 4

Continued from An Introduction to JNI using a Bottom Up Approach: Step 3.

Step 4: Java Main Function

Run Java without the CToCPPHelper Entry Point

  1. Create the following Java Class:
    package com.mycompany.myapp;

    public class JavaToCHelper {
        public native void cToCPPHelperEntryPoint(); // Comment to ignore CToCPPHelper

        static // static initializer code
        {
    //        System.load(JavaToCHelper.class.getResource("/dlls/CToCPPHelper.dll").getPath()); // Comment to ignore CToCPPHelper
        }

        public void jToCHelperExitPoint() {
            System.out.println("JAVA_TO_C_HELPER EXIT START");
    //        cToCPPHelperEntryPoint(); // Comment to ignore CToCPPHelper
            System.out.println("JAVA_TO_C_HELPER EXIT FINISH");
        }

        public static void main(String[] args) {
            System.out.println("JAVA_TO_C_HELPER MAIN START");
            JavaToCHelper jToCHelper = new JavaToCHelper();
            jToCHelper.jToCHelperExitPoint();
            System.out.println("JAVA_TO_C_HELPER MAIN FINISH");
        }

        public void jToCHelperEntryPoint() {
            System.out.println("JAVA_TO_C_HELPER ENTRY START");
            jToCHelperExitPoint();
            System.out.println("JAVA_TO_C_HELPER ENTRY FINISH");
        }
    }
  2. Compile and run JavaToCHelper, using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\java"

    "C:\Program Files\Java\jdk1.6.0_26\bin\javac.exe" -classpath "." com\mycompany\myapp\JavaToCHelper.java

    "C:\Program Files\Java\jdk1.6.0_26\bin\java.exe" -classpath "." com.mycompany.myapp.JavaToCHelper

Run CToCPPHelper.exe with a Generated Header File

  1. Generate CToCPPHelper.h from JavaToCHelper.class, using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\java"
    "C:\Program Files\Java\jdk1.6.0_26\bin\javah.exe" -classpath "." com.mycompany.myapp.JavaToCHelper
    mv com_mycompany_myapp_JavaToCHelper.h "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls\CToCPPHelper.h"
  2. Verify the CToCPPHelper.h was generated in the same folder as CToCPPHelper.c:
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class com_mycompany_myapp_JavaToCHelper */

    #ifndef _Included_com_mycompany_myapp_JavaToCHelper
    #define _Included_com_mycompany_myapp_JavaToCHelper
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     com_mycompany_myapp_JavaToCHelper
     * Method:    cToCPPHelperEntryPoint
     * Signature: ()V
     */

    JNIEXPORT void JNICALL Java_com_mycompany_myapp_JavaToCHelper_cToCPPHelperEntryPoint
      (JNIEnv *, jobject);

    #ifdef __cplusplus
    }
    #endif
    #endif
  3. Compile the code and run "CToCPPHelper.exe" (see An Introduction to JNI using a Bottom Up Approach: Step 3).

Run JavaToCHelper with the New DLL

  1. Uncomment two lines of code:
     System.load(JavaToCHelper.class.getResource("/dlls/CToCPPHelper.dll").getPath()); // Comment to ignore CToCPPHelper
        cToCPPHelperEntryPoint(); // Comment to ignore CToCPPHelper
  2. Generate a 64 bit dll file (for 32 bit Java, remove "-m64") using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

    "C:\MinGW64\bin\g++.exe" -m64 -Wl,--add-stdcall-alias -shared -I"C:\Program Files\Java\jdk1.6.0_26\include" -I"C:\Program Files\Java\jdk1.6.0_26\include\win32" -o CToCPPHelper.dll CToCPPHelper.c CPPHelper.cpp PrintOpenWindows.cpp
  3. Compile and run JavaToCHelper (adding the new dll to the class path), using the following commands:
    cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\java"

    "C:\Program Files\Java\jdk1.6.0_26\bin\javac.exe" -classpath "." com\mycompany\myapp\JavaToCHelper.java

    "C:\Program Files\Java\jdk1.6.0_26\bin\java.exe" -classpath ".;../resources" com.mycompany.myapp.JavaToCHelper

Summary of commands

Anytime you change the JavaToCHelper.java, CToCPPHelper.c, CPPHelper.cpp or PrintOpenWindows.cpp, you can regenerate the appropriate files via:
REM Generate the New C Header File

cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\java"

"C:\Program Files\Java\jdk1.6.0_26\bin\javac.exe" -classpath "." com\mycompany\myapp\JavaToCHelper.java

"C:\Program Files\Java\jdk1.6.0_26\bin\javah.exe" -classpath "." com.mycompany.myapp.JavaToCHelper

mv com_mycompany_myapp_JavaToCHelper.h "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls\CToCPPHelper.h"


REM Generate the New DLL

cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\resources\dlls"

"C:\MinGW64\bin\g++.exe" -m64 -Wl,--add-stdcall-alias -shared -I"C:\Program Files\Java\jdk1.6.0_26\include" -I"C:\Program Files\Java\jdk1.6.0_26\include\win32" -o CToCPPHelper.dll CToCPPHelper.c CPPHelper.cpp PrintOpenWindows.cpp


REM Run Java

cd /D "C:\Users\Scott\workspace\myrepo\my-app\src\main\java"

"C:\Program Files\Java\jdk1.6.0_26\bin\java.exe" -classpath ".;../resources" com.mycompany.myapp.JavaToCHelper

A warning! If you followed these instructions and you received the error "Can't load this .dll (machine code=0xbd) on a AMD 64-bit platform", it may be because your project is a "Maven Project". You can "Disable Maven Nature" and try recompiling from the command line with the following command:

mvn eclipse:clean eclipse:eclipse clean compile test-compile

Also, you can run the JavaToCHelper by right clicking and "Run As Java Application" or executing this command.

mvn exec:java -Dexec.mainClass="com.mycompany.myapp.JavaToCHelper"

This assumes your src/main/resources folder will be copied to the target folder during the build phase.
    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
            </plugin>
        </plugins>
    </build>

This post was reposted from http://scottizu.wordpress.com/2013/08/21/an-introduction-to-jni-using-a-bottom-up-approach-step-4/, originally written on August 21st, 2013.

Your First C++ to List All Open Windows: Part I

To get a C++ compiler for Windows, see TDM-GCC at tdm-gcc.tdragon.net.

I googled "Get the Window Handle of an Externally Running Window" and went to stackoverflow.com to find the following piece of code:

#include "HelloWindows.h"
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <windows.h>
#include <iostream>
 
using namespace std;

BOOL CALLBACK FindWindowBySubstr(HWND hwnd, LPARAM substring)
{
    const DWORD TITLE_SIZE = 1024;
    TCHAR windowTitle[TITLE_SIZE];

    if (GetWindowText(hwnd, windowTitle, TITLE_SIZE))
    {
        _tprintf(TEXT("%s\n"), windowTitle);
        // Uncomment to print all windows being enumerated
        if (_tcsstr(windowTitle, LPCTSTR(substring)) != NULL)
        {
            // We found the window! Stop enumerating.
            return false;
        }
    }
    return true// Need to continue enumerating windows
}

int main()
{
 cout << "START" << endl;
    const TCHAR substring[] = TEXT("Substring");
    EnumWindows(FindWindowBySubstr, (LPARAM)substring);
}


I named the file HelloWindows.cpp and placed it at "C:\Users\Scott\CPrograms\HelloWindows.cpp".

I also created an empty file called HelloWindows.h in the same directory.

Then, I ran:



cd "C:\Users\Scott\CPrograms\"
"C:\MinGW64\bin\g++.exe" HelloWindows.cpp -o HelloWindows.exe"
HelloWindows.exe

This post was reposted from http://scottizu.wordpress.com/2013/08/20/your-first-c-to-list-all-open-windows-part-i/, originally written on August 20th, 2013.

Your first C++ program to List All Open Windows: Part II

This article shows how to have one C++ call another and then compile.
Change the code from Your first C++ program to List All Open Windows: Part I to (change "int main" to "void listWindows":
void listWindows()
{
    cout << "START" << endl;
    const TCHAR substring[] = TEXT("Substring");
    EnumWindows(FindWindowBySubstr, (LPARAM)substring);
}

Add one line to HelloWindows.h:
void listWindows()

Create a file called HelloWorldCPP.cpp which contains the following code:
#include "HelloWindows.h"
#include <iostream>

using namespace std;
 
void sayHelloCPP () {
    cout << "Hello World! CPP" << endl;
    return;


int main() 
{
    sayHelloCPP();
    listWindows();
}

Add the file HelloWorldCPP.h

Lastly, run:

cd "C:\Users\Scott\CPrograms\"
"C:\MinGW64\bin\g++.exe" HelloWindows.cpp -o HelloWindows.exe"
HelloWindows.exe
Note: You have to make sure the main function from HelloWindows.cpp is gone since the main function is defined in HelloWorldCPP.cpp.

Note: The header file defines the functions which can be used by other .cpp files.

This post was reposted from http://scottizu.wordpress.com/2013/08/20/your-first-c-program-to-list-all-open-windows/, originally written on August 20th, 2013.

Thursday, December 11, 2014

How to Fake Adding Piccolo's PCanvas to a JPanel

One issue with Piccolo is that typically the PCanvas, which is the main canvas used to draw items on the screen must be attached to the top level JFrame. This might be problematic if you want to have your top level JFrame include several Panels. For instance, you might want a JPanel on the left to be a control panel and the PCanvas to be to the right of that. This is like the popular Paint program in Windows.

Here's how to fake it:
  1. Add the PCanvas to the top level JFrame.
  2. Set the Bounds of the PCanvas to shadow that of a JPanel.
private MainFrame() {    
        JButton myButton = new JButton("My Button");
        JPanel panel2 = new JPanel();
        this.add(myButton);
        this.add(panel2);
        this.add(canvas);
        
        this.setLayout(new BorderLayout());
        this.add(myButton, BorderLayout.NORTH);
        this.add(panel2, BorderLayout.CENTER);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setVisible(true);

        canvas.setBounds(panel2.getX(), panel2.getY(), panel2.getWidth(), panel2.getHeight());
    }


This post was reposted from http://scottizu.wordpress.com/2013/08/20/how-to-fake-adding-piccolos-pcanvas-to-a-jpanel/, originally written on August 20th, 2010.

An Introduction to Piccolo

I googled "download piccolo.jar", selected Piccolo Home Page, www.piccolo2d.org, clicked Download, Compiled Source (2.9MB).

See www.piccolo2d.org for more information.

    <dependency>
      <groupId>org.piccolo2d</groupId>
      <artifactId>piccolo2d-core</artifactId>
      <version>1.3.1</version>
    </dependency>


mvn install:install-file -Dfile="C:\Users\Scott\Desktop\piccolo2d-1.3.1-bin\piccolo2d-core-1.3.1.jar" -Dpackaging=jar -DgroupId=org.piccolo2d -DartifactId=piccolo2d-core -Dversion=1.3.1


package com.mycompany.gui;

import javax.swing.JFrame;

import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.nodes.*;

public class MainFrame extends JFrame {
    private MainFrame() {
        final PCanvas canvas = new PCanvas();
        final PText text = new PText("Hello World");
        canvas.getLayer().addChild(text);
        add(canvas);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setVisible(true);
    }
    
    public static void main(String[] args) {
            new MainFrame();
    }

}


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

Install Notepad++ to Quickly View Files

I googled "Install Notepad++", clicked Download - Notepad++, clicked v6.4.5 - Current Version, clicked Notepad++ Installer.

Then, I installed Notepad++. After this, whenever I right click on files, I can Open With Notepad++.

This application is also open source, meaning you can download the source code via Notepad++ source code.

See Working with Compressed Files on Windows for how to deal with 7 Zip compressed files.

This post was reposted from http://scottizu.wordpress.com/2013/08/20/install-notepad-to-quickly-view-files/, originally written on August 8th, 2013.

Friday, December 5, 2014

Reading and Writing Files in Java

Here is code to read and write from a file in Java. You will have to change the output path and package appropriately.

package com.mycompany.app.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileHelper {
    
    public static void main(String[] args) {
        try {
            System.out.println("START");
            String outputPath = "/Users/Scott/workspace/myrepo/my-app/output/text.txt";
            FileHelper fileHelper = new FileHelper();
            fileHelper.write(new File(outputPath), "Hello World!
My First HTML Page!");
            String string = fileHelper.read(new File(outputPath));
            System.out.println("From FILE:"+string);
            System.out.println("FINISH");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public String read(File inputFile) throws Exception {
        // Initialization
        String string = "";
        String line;
        
        // Read from file
        FileReader fr = new FileReader(inputFile);
        BufferedReader br = new BufferedReader(fr);
        while ((line = br.readLine()) != null) {
            string = string + line;
        }
        br.close();
        fr.close();
        
        return string;
    }

    public void write(File outputFile, String string) throws Exception {
        // Initialization
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }

        // Write to file
        FileWriter fw = new FileWriter(outputFile);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(string);
        bw.close();
        fw.close();

    }
}


This post was reposted from http://scottizu.wordpress.com/2013/08/19/reading-and-writing-files-in-java/, originally written on August 19th, 2013.

Reading and Writing MusicXml Files with Java

Download JFugue with Music Xml Support from JFugue Downloads. Click on jfugue-4.0.3-with-musicxml.jar. Change your pom.xml file and run "mvn install" as described in Adding an external Jar to a Maven Project (JFugue). Then add the following code (and include the code found in Reading and Writing Files in Java):

package com.mycompany.app.util;

import java.io.File;
import org.jfugue.MusicStringParser;
import org.jfugue.MusicStringRenderer;
import org.jfugue.MusicXmlParser;
import org.jfugue.MusicXmlRenderer;
import org.jfugue.Pattern;
import org.jfugue.Player;

public class MusicXMLFileHelper {
    
    public static void main(String[] args) { 
        try {
            System.out.println("START");
            String outputFile = "/Users/Scott/workspace/myrepo/my-app/output/mxmlfhout.xml";
            Pattern pattern = new Pattern("KEmaj V0 E4i+B4i B3i E4i+B4i B3i E4i+B4i B3i E4i+B4i B3i V1 E1h E1i F#1i G#1i B1i");
        
            MusicXMLFileHelper fileHelper = new MusicXMLFileHelper(); 
            fileHelper.write(new File(outputFile), pattern);
            
            Player player = new Player();
            player.play(pattern);
            System.out.println("FINISH");
        } catch (Exception ex) {
            
        }
    }
    
    public void write(File outputFile, Pattern musicPattern) throws Exception {
        MusicXmlRenderer renderer = new MusicXmlRenderer();
        
        MusicStringParser parser = new MusicStringParser();
        parser.addParserListener(renderer);
        parser.parse(musicPattern);
        
        FileHelper fileHelper = new FileHelper();
        fileHelper.write(outputFile, renderer.getMusicXMLString());
    }
    
    public Pattern read(File inputFile) throws Exception{
        MusicStringRenderer renderer = new MusicStringRenderer();

        MusicXmlParser parser = new MusicXmlParser();
            
        parser.addParserListener(renderer);
        parser.parse(inputFile);
        
        return renderer.getPattern();
    }
}


This post was reposted from http://scottizu.wordpress.com/2013/08/19/reading-and-writing-musicxml-files-with-java/, originally written on August 19, 2013.

Monday, December 1, 2014

Packaging All JARS with Maven Plugin

A description of the build lifecycle of Maven can be found at maven.apache.org.

When executing a command such as

call mvn -e deploy -DskipTests=true

You may want to include all the dependencies into the jar itself.

You may add this plugin to your pom.xml file in the <project><build><plugins> section (copied from stackoverflow.com).

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin>

If you do this, the maven-assemply-plugin will execute the jar-with-dependencies during the package phase. You should then see two jars in your Maven repository. One will have a suffix like '-jar-with-dependencies.jar'.