Executing Javascript through a Firefox Bookmark

In Firefox, you may open the bookmark menu by clicking on the downward triangle next to the star in the address bar.

ADD A NEW BOOKMARK

  • Go to http://www.google.com.
  • Open the bookmark menu.
  • Select “Bookmark This Page”.
  • In the Name: Field, enter “Hello World”.

CHANGE THE LOCATION TO INCLUDE JAVASCRIPT

  • Open the bookmark menu.
  • Right click the new “Hello World” bookmark and select Properties.
  • In the Location: Field, enter the following line:
    
    javascript:log=function(message){d=document.createElement("div");d.id="bmDiv";d.innerHTML=message;d.style.color="red";document.body.appendChild(d);};log('Hello%20World');
    
  • Hit Save.

Note: This code will create a div element, place the message within the div, style the div with red coloring and add the div with the message to the html (ie DOM).

USE THE NEW BOOKMARK TO EXECUTE JAVASCRIPT ON A PAGE

  • Open the bookmark menu.
  • Select the “Hello World” bookmark.

You should see new text on the bottom of the page, since a div element was added with the text “Hello World”.

MODIFY CODE TO EXECUTE JAVASCRIPT FROM A LOCAL SERVER
You can host javascript on a local instance of Tomcat and execute it on the page.

Step 1. Create the bookmark to execute the script from a server.

  • Create a new book mark named “Bookmark Script”.
  • Right click the “Bookmark Script” and select Properties.
  • In the Location: Field, enter the following line:
    
    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/BookmarkScript.js";document.body.appendChild(s);};void(addScript());
    
  • Hit Save.

Note: This code will create a script element, change the source of the div element to point to a script running on the local host (ie local Tomcat Server) and add the script to the html (ie DOM).

Step 2. Run the server and add the script to the server.

  • Start the Tomcat Server (see Step 11: Setup Tomcat on the Server to Host the Front End Display fromĀ https://scottizu.wordpress.com/2014/06/21/a-basic-dashboard/).
  • Add a file in the tomcat root directory named “BookmarkScript.js”.
  • Edit the javascript file “BookmarkScript.js” to include the following javascript:
    
    log=function(message){
      d=document.createElement("div");
      d.id="bmDiv";
      d.innerHTML=message;
      d.style.color="red";
      document.body.appendChild(d);
    };
    log('BookmarkScript');
    

Note: This code will create a div element, place the message within the div, style the div with red coloring and add the div with the message to the html (ie DOM).

USE THE NEW BOOKMARK TO EXECUTE JAVASCRIPT ON A PAGE FROM A LOCAL SERVER

  • Open the bookmark menu.
  • Select the “Bookmark Script” bookmark.

Note: In Firefox, you can right click and “Inspect element” which will give you access to the Console Tab, HTML Tab, etc. You can verify the html is being added by looking at the HTML Tab. To avoid getting an “Blocked loading mixed active content” error in the Console Tab, make sure you use http://www.google.com instead of https://www.google.com.

Using Javascript to Calculate Actual Rate of Return

When looking at deposits through the year, most companies do no accurately report earnings for individuals. One thing that I want to change is requiring institutions to be more transparent about individual profit. In other words, who cares how the markets are doing, what the fees are. Let’s focus on profit (after fees and other charges).

If we are not satisfied with profit, lets dig in deeper to see what the income or expenses are.

Here is code to calculate growth based on deposits:


<html>
<body>
<pre>
<script>
function logWrite(arg) {
  document.body.innerHTML = document.body.innerHTML + arg + '\n<br>';
}
function logClear() {
  document.body.innerHTML = '';
}

function parseDate(dateString) {
  var mdy = dateString.split('/')
  return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function yearsInBetweenDates(date1, date2) {
  return (date2-date1)/(1000*60*60*24*365);
}

function yearsInBetweenAssign(paymentArray, currentNetWorth) {
  for (var i = 0; i<paymentArray.length; i++) {
    paymentArray[i].years = yearsInBetweenDates(paymentArray[i].date, currentNetWorth.date);
  }
}

function findTotalPayments(paymentArray) {
  var total = 0;
  for (var i = 0; i<paymentArray.length; i++) {
    total = total + paymentArray[i].amount;
  }
  return total;
}

function findRateOfReturn(paymentArray, currentNetWorth, lowRate, highRate){
  yearsInBetweenAssign(paymentArray, currentNetWorth);
  while(highRate-lowRate > .0001) {
    var testRate = (lowRate + highRate)/2;
    var calculatedNetWorth = calculateNetWorth(paymentArray, testRate);
    if(calculatedNetWorth < currentNetWorth.amount) {
      lowRate = testRate;
    } else {
      highRate = testRate;
    }
  }
  return lowRate;
}

function calculateNetWorth(paymentArray, interestRate) {
  var total = 0;
  for (var i=0; i<paymentArray.length; i++) {
    var P = paymentArray[i].amount;
    var r = interestRate;
    var y = paymentArray[i].years;
    total = total + P*Math.pow((1+r), y);
  }
  return total;
}

function createTransaction(date, amount) {
  var object = new Object();
  object.date = parseDate(date);
  object.amount = amount;
  return object;
}

var currentNetWorth = createTransaction("10/25/2014", 111197.30);
var paymentArray = [
createTransaction("06/21/2013", 25000.00),
createTransaction("07/26/2013", 15101.06),
createTransaction("10/30/2013", 42084.34),
createTransaction("11/12/2013", 8541.71),
createTransaction("12/13/2013", 11000.00),
createTransaction("03/21/2014", 995.00),
createTransaction("04/21/2014", 995.00),
createTransaction("05/21/2014", 995.00),
createTransaction("06/20/2014", 995.00),
createTransaction("07/22/2014", 995.00),
createTransaction("08/19/2014", 995.00),
createTransaction("09/19/2014", 995.00),
createTransaction("10/21/2014", 995.00)
];
for (var i = 0; i<paymentArray.length; i++) {
  logWrite('DepositDate:'+paymentArray[i].date+' DespositAmount:'+paymentArray[i].amount);
}
var totalDeposits = findTotalPayments(paymentArray);
logWrite('Deposits:'+totalDeposits);
logWrite('Current:'+currentNetWorth.amount);
logWrite('Rate:'+findRateOfReturn(paymentArray, currentNetWorth, -1, 1));
logWrite('Growth:'+(currentNetWorth.amount-totalDeposits));

</script>
</pre>
</body>
</html>

Output:
DepositDate:Fri Jun 21 2013 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:25000
DepositDate:Fri Jul 26 2013 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:15101.06
DepositDate:Wed Oct 30 2013 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:42084.34
DepositDate:Tue Nov 12 2013 00:00:00 GMT-0800 (Pacific Standard Time) DespositAmount:8541.71
DepositDate:Fri Dec 13 2013 00:00:00 GMT-0800 (Pacific Standard Time) DespositAmount:11000
DepositDate:Fri Mar 21 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Mon Apr 21 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Wed May 21 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Fri Jun 20 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Tue Jul 22 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Tue Aug 19 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Fri Sep 19 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
DepositDate:Tue Oct 21 2014 00:00:00 GMT-0700 (Pacific Daylight Time) DespositAmount:995
Deposits:109687.10999999999
Current:111197.3
Rate:0.01318359375
Growth:1510.1900000000169

Converting a Maven Project to Create a Runnable JAR

See www.petrikainulainen.net for more information.

In my pom.xml file, I changed build tag to include the “Maven Assembly Plugin”.
Only had to edit the main class value, based on the package and class name.


	<build>
		<plugins>             <!-- The configuration of maven-assembly-plugin -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2.2</version>                 <!-- The configuration of the plugin -->
				<configuration>                     <!-- Specifies the configuration file of the assembly plugin -->
					<descriptors>
						<descriptor>src/main/assembly/assembly.xml</descriptor>
					</descriptors>
				</configuration>
			</plugin>             <!-- The configuration of maven-jar-plugin -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.3.1</version>                 <!-- The configuration of the plugin -->
				<configuration>                     <!-- Configuration of the archiver -->
					<archive>                         <!-- Manifest specific configuration -->
						<manifest>                             <!-- Classpath is added to the manifest of the created jar file. -->
							<addClasspath>true</addClasspath>                             <!-- Configures the classpath prefix. This configuration option is used to 
								specify that all needed libraries are found under lib/ directory. -->
							<classpathPrefix>lib/</classpathPrefix>                             <!-- Specifies the main class of the application -->
							<mainClass>com.main.SwingApp</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build> 

The main class was from this file:


package com.main;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SwingApp {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+
                SwingUtilities.isEventDispatchThread());
        JFrame f = new JFrame("Swing App");
        
        
        
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(250,250);
        f.setVisible(true);
    }

}

Then, added the default assembly file, creating a new source folder “src/main/assembly” and adding the “assembly.xml” file (reposted from www.petrikainulainen.net)


<assembly>
	<id>bin</id>     <!-- Generates a zip package containing the needed files -->
	<formats>
		<format>zip</format>
	</formats>       <!-- Adds dependencies to zip package under lib directory -->
	<dependencySets>
		<dependencySet>             <!-- Project artifact is not copied under library directory since it is added 
				to the root directory of the zip package. -->
			<useProjectArtifact>false</useProjectArtifact>
			<outputDirectory>lib</outputDirectory>
			<unpack>false</unpack>
		</dependencySet>
	</dependencySets>
	<fileSets>         <!-- Adds startup scripts to the root directory of zip package. The startup 
			scripts are located to src/main/scripts directory as stated by Maven conventions. -->
		<fileSet>
			<directory>${project.build.scriptSourceDirectory}</directory>
			<outputDirectory></outputDirectory>
			<includes>
				<include>startup.*</include>
			</includes>
		</fileSet>         <!-- adds jar package to the root directory of zip package -->
		<fileSet>
			<directory>${project.build.directory}</directory>
			<outputDirectory></outputDirectory>
			<includes>
				<include>*.jar</include>
			</includes>
		</fileSet>
	</fileSets>
</assembly> 

Then, after issuing ‘mvn package’ from Git Bash command prompt in the same directory as the pom.xml file, it created the target directory with a runnable jar. I double clicked the jar to test.

SWING
Help – Install New Software – Copy http://download.eclipse.org/releases/juno into field – Add
http://download.eclipse.org/windowbuilder/WB/integration/4.4/
Capture

Using Document Builder to Access an XML Tag Value

Imports…


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import java.io.StringReader;
import org.w3c.dom.Document;
import org.w3c.dom.CharacterData;

Method…


	private static String findXMLTagValueFromXML(String xml, String tag) throws Exception {
		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		InputSource is = new InputSource();
	    is.setCharacterStream(new StringReader(xml));
	    Document doc = db.parse(is);
	    CharacterData child = (CharacterData) doc.getElementsByTagName(tag).item(0).getFirstChild();
	    return child.getData();
	}