Wednesday, January 14, 2015

Sample Code of Using Google Maps APIs

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <style type="text/css">
      #map-canvas { width: 400px; height: 400px; margin: 0; padding: 0; border:#555555 0px solid;}
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?v=3.exp">
    </script>
    <script type="text/javascript"
      src="jquery-1.7.2.min.js">
    </script>
    <script type="text/javascript">
      // Note: you need a Google account and a key to use Google Maps web service and JavaScript APIs
      var map;
   
      function searchByAddress() {
        var address = document.getElementById("txtAddress").value;
        if ( address != null && address.length > 0 ) {
          address = address.split(' ').join('+');
        }
        var city = document.getElementById("txtCity").value;
        var province = document.getElementById("txtProvince").value;
     
        // REST URI
        // Sample URI https://maps.googleapis.com/maps/api/geocode/json?address=somewhere&components=locality:city|administrative_area:province|country:CA&key=myKey
        var restURL = "https://maps.googleapis.com/maps/api/geocode/json";
        document.getElementById("txtURL").value = restURL;
        var geocoder = new google.maps.Geocoder();
        var foundLocation = null;
        var foundAddress = null;
        if (geocoder) {
          geocoder.geocode({ 'address': address + ', ' + city + ', ' + province }, function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            foundLocation = results[0].geometry.location
            document.getElementById("txtCoordinate").value = foundLocation;
            foundAddress = results[0].formatted_address
         
            // var lat = foundLocation['k'];
            // var lng = foundLocation['D'];
            // var latlong = new google.maps.LatLng(lat, lng);
            // add a custom marker
            var image = 'fclogo.png';
            var marker = new google.maps.Marker({ position: foundLocation,
                                                  title: foundAddress,
                                                  icon: image });
            marker.setMap(map);
       
            // refresh map
            var mapOptions = { center: foundLocation,
                               zoom: 15,
                               mapTypeId: google.maps.MapTypeId.ROADMAP};
            map.setOptions(mapOptions);
          }
          else {
            document.getElementById("txtCoordinate").value = "Geocoding failed: " + status;
          }
       
          });
        }  
      }
   
   
      function initialize() {
        var mapOptions = {
          center: { lat: 49.29514409999999, lng: -122.891689},
          zoom: 10
        };
        map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
  <b>Find a Location in Map - British Columbia, Canada</b><p/>
     Address: <input type="text" id="txtAddress" name="txtAddress" value="4710 Kingsway" />&nbsp;&nbsp
     City: <input type="text" id="txtCity" name="txtCity" value="Burnaby" />&nbsp;&nbsp;
     Province: <input type="text" id="txtProvince" name="txtProvince" value="BC" />&nbsp;&nbsp;
     <input type="button" name="btnSearch" value="Search" onclick="searchByAddress();"/><p/>
     <input type="hidden" size="100" id="txtURL" name="txtURL" value="" />
     Coordinates: <input type="text" size="100" id="txtCoordinate" name="txtCoordinate" value="" />
     <p/>
     <div id="map-canvas"></div>
  </body>
</html>

Friday, January 9, 2015

Sample Code of Using Microsoft Bing Maps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<html>
<head>
<title>Bing Map Demo</title>
<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0">
  <!-- parameters: v - version (v=7.0); s - SSL (s=0 or s=1); mkt - Locale (primary, secondary. e.g. mkt=en-us,fr-fr) -->
</script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
   var mapKey="NOTE: You need a key requested from https://www.bingmapsportal.com/application";
   var map = null;
   var currentLocation = null;
   function getBingMap() {
     var mapOptions = {
       credentials: mapKey,
       center: new Microsoft.Maps.Location(49.228073120117188,-122.99903106689453), // 45.5, -122.5
       mapTypeId: Microsoft.Maps.MapTypeId.road, // map type ids: road, arial, auto, birdseye and etc.
       zoom: 10};
     map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
   
     Microsoft.Maps.Events.addHandler(map, 'click', addBCHLogo);
   }
 
   function searchByAddressOrPostalCode() {
     // Structural REST URL - Canada
     // http://dev.virtualearth.net/REST/v1/Locations/CA/adminDistrict/postalCode/locality/addressLine?includeNeighborhood=includeNeighborhood&include=includeValue&maxResults=maxResults&key=BingMapsKey
     // Unstructural Query - Any country
     // http://dev.virtualearth.net/REST/v1/Locations?countryRegion=countryRegion&adminDistrict=adminDistrict&locality=locality&postalCode=postalCode&addressLine=addressLine&userLocation=userLocation&userIp=userIp&usermapView=usermapView&includeNeighborhood=includeNeighborhood&maxResults=maxResults&key=BingMapsKey
     var address = document.getElementById("txtAddress").value;
     if ( address != null && address.length > 0 ) {
       address = "/" + address;
     }
     var city = document.getElementById("txtCity").value;
     if ( city != null && city.length > 0 ) {
       city = "/" + city;
     }
     var postalCode = document.getElementById("txtPostalCode").value;
     if ( postalCode != null && postalCode.length > 0 ) {
       postalCode = "/" + postalCode;
     }
     // REST URI
     var restURL = "http://dev.virtualearth.net/REST/v1/Locations/CA/BC" + postalCode + city + address + "?key=" + mapKey;
     document.getElementById("txtURL").value = restURL;
   
     // AJAX call to get the location information from the above REST service. Note: jsonp is used for bypassing the cross-domain issue
     $.ajax( { url: restURL,
               dataType: 'jsonp',
               cache: false,
               data: {},
               jsonp: "jsonp",
               success: function( reply ) {
                 if ( reply != null && reply.resourceSets[0] != null ) {
                   var strResult = eval(reply);
                 
                   if ( strResult.resourceSets[0].estimatedTotal == 1 ) {
                     var coordinates = strResult.resourceSets[0].resources[0].point.coordinates;
                     var latitude = coordinates[0];
                     var longitude = coordinates[1];
                     document.getElementById("txtCoordinate").value = latitude + "," + longitude;
                     var location = new Microsoft.Maps.Location(latitude, longitude);
                   
                     // Change map options
                     map.setView({center: location, zoom: 12});
                   
                     var formattedAddress = strResult.resourceSets[0].resources[0].name;
                   
                     // Add a pushpin to the center of the map
                     var pin = new Microsoft.Maps.Pushpin(location, {text: 'A'});
                   
                   
                     var pinInfobox = new Microsoft.Maps.Infobox(pin.getLocation(),
                                                                 {title: formattedAddress,
                                                                  description: latitude + "," + longitude,
                                                                  visible: false,
                                                                  offset: new Microsoft.Maps.Point(1,20)});
                     Microsoft.Maps.Events.addHandler(pin, 'mouseover', showInfobox );
                     // Microsoft.Maps.Events.addHandler(pin, 'mouseout', hideInfobox );
                     map.entities.push(pinInfobox);
                   
                     pin.setOptions({infobox: pinInfobox});
                     map.entities.push(pin);
                   
                   
                     // Add a polygon to the map
                     // var vertices = new Array(new Microsoft.Maps.Location(20,-20), new Microsoft.Maps.Location(20,20), new Microsoft.Maps.Location(-20,20), new Microsoft.Maps.Location(-20,-20), new Microsoft.Maps.Location(20,-20));
                     // var polygoncolor = new Microsoft.Maps.Color(100,100,0,100);
                     // var polygon = new Microsoft.Maps.Polygon(vertices,{fillColor: polygoncolor, strokeColor: polygoncolor});
                     // map.entities.push(polygon);
                   
                   }
                 }
               }
             } );
   }
 
   function addBCHLogo(e) {
     if (e.targetType == "map") {
     var point = new Microsoft.Maps.Point(e.getX(), e.getY());
     var location = e.target.tryPixelToLocation(point);
     // add a pushpin
     var pin = new Microsoft.Maps.Pushpin(location, {icon: 'fclogo.png', width: 24, height: 18, draggable: true});
     document.getElementById("txtCoordinate").value = location.latitude + ", " + location.longitude;
     map.entities.push(pin);
     }
   }
 
   function showInfobox( e ) {
     if (e.targetType == "pushpin") {
       var infoBox = e.target._infobox;
       infoBox.setOptions({visible:true});
     }
   }
 
   function hideInfobox( e ) {
     if (e.targetType == "pushpin") {
       var infoBox = e.target._infobox;
       infoBox.setOptions({visible:false});
     }
   }
 
</script>

<style>
.mapStyle {
   position: absolute;
   top: 20;
   left: 10;
   width: 400px;
   height: 400px;
   border:#555555 2px solid;
}
</style>
</head>
<body onload="getBingMap()">
<b>Find a Location in Map - British Columbia, Canada</b><p/>
Address: <input type="text" id="txtAddress" name="txtAddress" value="4710 Kingsway" />&nbsp;&nbsp;
City: <input type="text" id="txtCity" name="txtCity" value="Burnaby" />&nbsp;&nbsp;
Postal Code: <input type="text" id="txtPostalCode" name="txtPostalCode" value="V5H4M2" />&nbsp;&nbsp;
<input type="button" name="btnSearch" value="Search" onclick="searchByAddressOrPostalCode();"/><p/>
<input type="hidden" size="100" id="txtURL" name="txtURL" value="" />
Coordinates: <input type="text" size="100" id="txtCoordinate" name="txtCoordinate" value="" />
<p/>
<div id='mapDiv' class="mapStyle"></div>
</body>
</html>

Tuesday, April 10, 2012

Maven Starter Guide

  • Enviroment
SET M2_HOME=%DEVAPPS_HOME%/apache-maven-3.0.3
SET PATH=%JAVA_HOME%/bin;%M2_HOME%/bin;
SET MAVEN_CLASSPATH=%M2_HOME%/lib/maven-core-3.0.3.jar;%M2_HOME%/lib/maven-model-3.0.3.jar;%M2_HOME%/lib/maven-plugin-api-3.0.3.jar;%M2_HOME%/lib/maven-repository-metadata-3.0.3.jar;%M2_HOME%/lib/maven-artifact-3.0.3.jar;

  • Project Creation
c:\> mvn archetype:generate
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 186:
Choose org.apache.maven.archetypes:maven-archetype-quickstart version:
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1
Define value for property 'groupId' (package name): : org.freecode.demo
Define value for property 'artifactId' (project name): :Demo1
Define value for property 'version':  1.0-SNAPSHOT: :1.0
Define value for property 'package':  org.freecode.demo: :
Confirm properties configuration:
groupId: org.freecode.demo
artifactId: Demo1
version: 1.0
package: org.freecode.demo
 Y: :



    a Project file of Maven (pom.xml) is generated.

      <groupId>org.freecode.demo</groupId>
      <artifactId>Demo1</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
      <name>Demo1</name>
      <url>http://maven.apache.org</url>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>4.11</junit.version>
      </properties>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>${junit.version}</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>
    
  • Structure of Maven Project
  • Demo1
    |-- pom.xml
    |-- src
    |   |-- main
    |   |   |-- assembly
    |   |   |-- config
    |   |   |-- filters
    |   |   |-- java
    |   |   |   `-- org
    |   |   |       `-- freecode
    |   |   |           `-- demo
    |   |   |               `-- App.java
    |   |   |-- resources
    |   |   `-- webapp
    |   |       |-- index.jsp
    |   |       `-- WEB-INF
    |   |           |-- web.xml
    |   |           `-- classes
    |   |               `-- org
    |   |                   `-- freecode
    |   |                       `-- demo
    |   |                           `-- App.class   
    |   `-- test
    |   |   `-- java
    |   |       `-- org
    |   |           `-- freecode
    |   |               `-- demo
    |   |                   `-- AppTest.java
    |   `-- site
    |
    `-- target


  • Manually Add Dependencies
C:\> call mvn install:install-file -Dfile=ojdbc5.jar -DgroupId=com.oracle -DartifactId=ojdbc -Dversion=5.0 -Dpackaging=jar
Update pom.xml by adding the custom dependencies
e.g.
<dependencies> …
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc</artifactId>
        <version>5.0</version>
    </dependency>
</dependencies>

  • Project Compile, Build, Package
to clean a project, use:
  c:\Demo1> mvn clean
to package a project:
  c:\Demo1> mvn package

  • Build Plugin - Compiler
<build>
    <finalName>war file name</finalName>
    <resources>…</resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
             <configuration>
                 <source>1.7</source>
                 <target>1.7</target>
             </configuration>
        </plugin>
        … …
    </plugins>
</build>

  • Build Plugin - WAR Package (for JBoss/Wildfly)
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <webResources>
                    <resource>
                        <filtering>true</filtering>
                        <directory>src/main/webapp/WEB-INF</directory>
                        <includes>    <include>jboss-web.xml</include>   </includes>
                        <targetPath>/WEB-INF</targetPath>
                    </resource>
                </webResources>
                <outputDirectory>c:/jbossas-8.1.0.Final/standalone/deployments</outputDirectory>
            </configuration>
        </plugin>
    </plugins>
</build>

  • Profiles per Environment
    <profiles>
        <profile>
        <id>dev</id>
        <properties>
            <application.environment>Development</application.environment>
            <environment.id>dev</environment.id>
            <context.path.name>/dev</context.path.name>
            <jta.data.source.poweron>PoweronDEV</jta.data.source.poweron>
            … …
        </properties>
    </profile>

    run command: C:\> mvn clean package –P dev
  • Project Deployment (Glassfish)
to deploy a project to Glassfish server, you need to add Glassfish plugin and some dependencies into pom.xml.

to find a dependency or plugin, you can search from http://mvnrepositorycom/

- change package type to war
<packaging>war</packaging>

 
- Servlet 2.5
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
</dependency>


- build section with war file and Glassfish plugins
<build>
  <finalName>XProjectDemo</finalName>
  <!-- <directory>C:/EclipseWork/XProjectDemo/target</directory> -->
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
     <source>1.6</source>
     <target>1.6</target>
    </configuration>
   </plugin>
   <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1.1</version>
   </plugin>
   <plugin>
    <groupId>org.glassfish.maven.plugin</groupId>
    <artifactId>maven-glassfish-plugin</artifactId>
    <version>2.1</version>
    <configuration>
     <debug>true</debug>
     <echo>true</echo>
     <user>your Glassfish admin user</user>
     <adminPassword>your Glassfish admin password</adminPassword>
     <glassfishDirectory>C:/DevApps/glassfish3</glassfishDirectory>
     <components>
      <component>
       <name>${project.artifactId}</name>
       <artifact>${project.build.directory}/${project.build.finalName}.war</artifact>
      </component>
     </components>
     <domain>
      <name>${project.artifactId}</name>
      <adminPort>4848</adminPort>
      <httpPort>8989</httpPort>
      <httpsPort>8181</httpsPort>
     </domain>
    </configuration>
   </plugin>
  </plugins>
 </build>


- Maven-Glassfish commands (http://maven-glassfish-plugin.java.net/)
  • glassfish:create-domain Create a new Glassfish domain. (Creating an existing domain will cause it to be deleted and recreated.)
  • glassfish:start-domain Start an existing Glassfish domain. (Starting a non-existent domain will cause it to be created.)
  • glassfish:deploy Deploy JavaEE artifacts to a running domain. (Deploying to an inactive domain will cause it to be started and created if necessary.)
  • glassfish:redeploy Redeploy JavaEE artifacts to a running domain. (Cold redeployment by first calling undeploy and then deploy . Use deploy to effect a hot deployment.)
  • glassfish:undeploy Undeploy JavaEE components from a running domain.
  • glassfish:stop-domain Stop a running Glassfish domain.
  • glassfish:delete-domain Delete an existing Glassfish domain.