<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>URL &#8211; Henry Poon&#039;s Blog</title>
	<atom:link href="https://blog.henrypoon.com/blog/tag/url/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.henrypoon.com</link>
	<description></description>
	<lastBuildDate>Tue, 04 Oct 2022 21:49:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
<site xmlns="com-wordpress:feed-additions:1">83044199</site>	<item>
		<title>Installing Seafile with Docker and Apache 2</title>
		<link>https://blog.henrypoon.com/blog/2019/06/12/installing-seafile-with-docker-and-apache-2/</link>
					<comments>https://blog.henrypoon.com/blog/2019/06/12/installing-seafile-with-docker-and-apache-2/#respond</comments>
		
		<dc:creator><![CDATA[hp]]></dc:creator>
		<pubDate>Wed, 12 Jun 2019 07:12:42 +0000</pubDate>
				<category><![CDATA[computer stuff]]></category>
		<category><![CDATA[engineering]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[9]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[apache 2]]></category>
		<category><![CDATA[Apache HTTP Server]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Chan]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[cloud storage]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Dia]]></category>
		<category><![CDATA[Docker]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[DROPBOX]]></category>
		<category><![CDATA[EAR]]></category>
		<category><![CDATA[Email]]></category>
		<category><![CDATA[File sharing]]></category>
		<category><![CDATA[Free software]]></category>
		<category><![CDATA[Gmail]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Gran]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IOS]]></category>
		<category><![CDATA[It]]></category>
		<category><![CDATA[Lie]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Matt]]></category>
		<category><![CDATA[Nap]]></category>
		<category><![CDATA[Net]]></category>
		<category><![CDATA[Opera]]></category>
		<category><![CDATA[OS-level virtualisation]]></category>
		<category><![CDATA[Page]]></category>
		<category><![CDATA[Password]]></category>
		<category><![CDATA[PATH]]></category>
		<category><![CDATA[Port]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[Run]]></category>
		<category><![CDATA[seafile]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[System software]]></category>
		<category><![CDATA[Systemd]]></category>
		<category><![CDATA[Thou]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[USR]]></category>
		<category><![CDATA[ypres]]></category>
		<category><![CDATA[Z]]></category>
		<guid isPermaLink="false">https://blog.henrypoon.com/?p=3509</guid>

					<description><![CDATA[Seafile is an open source file sharing software that allows its users to setup their own cloud storage at home. Think Dropbox, but self-hosted. This post is about deploying an instance of Seafile using Docker on a non-standard port (i.e. not 80 and 443). The reason to deploy the app on a non-standard port is [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><a rel="noreferrer noopener" aria-label="Seafile (opens in a new tab)" href="https://www.seafile.com" target="_blank">Seafile</a> is an open source file sharing software that allows its users to setup their own cloud storage at home.  Think Dropbox, but self-hosted.</p>



<p class="wp-block-paragraph">This post is about deploying an instance of Seafile using Docker on a non-standard port (i.e. not 80 and 443).  The reason to deploy the app on a non-standard port is usually because there is already another webserver running on that port (in my case Apache 2).  In such scenarios, it is necessary to set up a reverse proxy so the Seafile port can be exposed by Apache on ports 80/443.  Under typical circumstances, deploying Seafile on a standard port would mean that the app would host itself without the need for Apache 2 at all.  This post also assumes Ubuntu 16.04 as the operating system, but in theory should apply to other Linux OS&#8217;s.</p>



<p class="has-text-align-left wp-block-paragraph">The process can be split into multiple parts:</p>



<ol class="wp-block-list"><li>Setup Docker</li><li>Deploy Seafile</li><li>Configure Apache 2</li><li>Setup systemd</li><li>Setup e-mail (optional)</li><li>Backing up the image</li><li>Troubleshooting</li></ol>



<h2 class="wp-block-heading">Setup Docker</h2>



<p class="wp-block-paragraph">This guide won&#8217;t go into depth on how to setup Docker, but rather the setup guide and more information about what Docker is can be found here: <a rel="noreferrer noopener" aria-label="https://docs.docker.com/get-started/ (opens in a new tab)" href="https://docs.docker.com/get-started/" target="_blank">https://docs.docker.com/get-started/</a></p>



<h2 class="wp-block-heading">Deploy Seafile</h2>



<p class="wp-block-paragraph">The key page in the Seafile documentation for deploying Seafile within Docker can be found here: <a href="https://github.com/haiwen/seafile-docker" target="_blank" rel="noreferrer noopener">https://github.com/haiwen/seafile-docker</a>.  The command I used is as follows:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">docker run -d --name seafile \
  -e SEAFILE_SERVER_HOSTNAME=seafile.example.com \
  -e SEAFILE_ADMIN_EMAIL=me@example.com \
  -e SEAFILE_ADMIN_PASSWORD=a_very_secret_password \
  -v /opt/seafile-data:/shared \
  -p 8000:80 \
  seafileltd/seafile:latest</code></pre>



<p class="wp-block-paragraph">I recommend setting up Seafile with an actual secret password because it&#8217;s not easy to change once it&#8217;s set up.</p>



<p class="wp-block-paragraph">Note that the port argument shows 8000:80.  It means that Docker will use the host port 8000 and the container will use port 80 &#8211; meaning that using Docker will interpret requests from my host OS on port 8000 as requests on port 80 in the container.  8000 was used on my setup because port 80 was already used. </p>



<p class="wp-block-paragraph">Once the command is executed, the necessary files will be downloaded and the container will start and will be accessible on port 8000.</p>



<p class="wp-block-paragraph">There is also an option to setup Seafile with an SSL cert from <a rel="noreferrer noopener" aria-label="Let's Encrypt (opens in a new tab)" href="https://letsencrypt.org/" target="_blank">Let&#8217;s Encrypt</a>, but I didn&#8217;t do this because I already had a cert that I wanted to reuse.</p>



<p class="wp-block-paragraph">Once the server is up, navigate to <a href="#">https://seafile.example.com/sys/settings/</a> and change SERVICE_URL and FILE_SERVER_URL to match your domain name.</p>



<h2 class="wp-block-heading">Configure Apache 2</h2>



<p class="wp-block-paragraph">Adding a reverse proxy on Apache 2 will allow Apache 2 to route requests to port 8000, which will go to port 80 in the container.  The main reference for this section is this: <a href="https://manual.seafile.com/deploy/deploy_with_apache/" target="_blank" rel="noreferrer noopener">https://manual.seafile.com/deploy/deploy_with_apache/</a>.  This is done by adding a new site to Apache 2.  The following configuration assumes that a LetsEncrypt SSL certificate is used.</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">cd /etc/apache2/sites-available
sudo nano seafile.conf</code></pre>



<pre class="wp-block-code"><code lang="apacheconf" class="language-apacheconf">&lt;IfModule mod_ssl.c&gt;
&lt;VirtualHost *:443&gt;
    ServerName seafile.example.com
    ServerAdmin me@example.com

    RewriteEngine On

    # ModSecurity does not process requests.  There is a hard limit of 1 GB
    # with ModSecurity.
    SecRuleEngine Off

    # Whitelist internal IPs for mod_evasive
    DOSWhitelist 192.168.1.*

    &lt;Location /media&gt;
        Require all granted
    &lt;/Location&gt;

    # Stuff for seafile server
    ProxyPass /seafhttp http://127.0.0.1:8082
    ProxyPassReverse /seafhttp http://127.0.0.1:8082
    RewriteRule ^/seafhttp - [QSA,L]

    # Stuff for seahub
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8000/
    ProxyPassReverse / http://127.0.0.1:8000/

    ErrorLog ${APACHE_LOG_DIR}/seafile_error.log
    CustomLog ${APACHE_LOG_DIR}/seafile_access.log combined

    Include /etc/letsencrypt/options-ssl-apache.conf

    SSLCertificateFile /path/to/cert/file.pem
    SSLCertificateKeyFile /path/to/cert/key/file.pem
&lt;/VirtualHost&gt;
&lt;/IfModule&gt;
</code></pre>



<p class="wp-block-paragraph">I&#8217;ve added my local domain to the whitelist so that mod_evasive doesn&#8217;t think my local host is a threat.</p>



<p class="wp-block-paragraph">There are two sets of ProxyPass and ProxyPassReverse lines.  The reason for this is that Seafile is split up into Seahub and Seafile, where one uses port 8082 (by default), while the other uses 8000.  These two lines are essentially what allows Apache to read requests from port 443 and pass them on to the container.</p>



<p class="wp-block-paragraph">Once the file is saved, execute the following</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo a2ensite seafile.conf
sudo service apache2 reload</code></pre>



<p class="wp-block-paragraph">Navigating to the site at the Apache 2 defined port should now load Seafile without having to go to port 8000.</p>



<h2 class="wp-block-heading">Setup systemd</h2>



<p class="wp-block-paragraph">systemd allows the Docker container to be started up on boot, and be controlled like this:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo service seafile start/stop/restart</code></pre>



<p class="wp-block-paragraph">The configuration is as follows:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo nano /etc/systemd/system/seafile.service</code></pre>



<pre class="wp-block-code"><code lang="properties" class="language-properties">[Unit]
Description=Seafile Server
After=network.target mysql.service

[Service]
Type=oneshot
ExecStart=/usr/bin/docker container start seafile
ExecStop=/usr/bin/docker container stop seafile
ExecReload=/usr/bin/docker container restart seafile
RemainAfterExit=yes
User=root
Group=root

[Install]
WantedBy=multi-user.target</code></pre>



<p class="wp-block-paragraph">Once the configuration is saved, shut off the existing running instance of Seafile and then let systemd start it up for you.</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo systemctl daemon-reload
sudo service seafile start</code></pre>



<p class="wp-block-paragraph">At this point, Seafile should start automatically on boot, with Apache 2 doing a reverse proxy to the true Seafile port.</p>



<h2 class="wp-block-heading">Setup e-mail (optional)</h2>



<p class="wp-block-paragraph">Optionally, Seafile can be configured to send e-mails.  The reference is here: <a href="https://manual.seafile.com/config/sending_email/" target="_blank" rel="noreferrer noopener">https://manual.seafile.com/config/sending_email/</a>.  The config file should be under:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">/opt/seafile-data/seafile/conf/seahub_settings.py</code></pre>



<p class="wp-block-paragraph">I happen to be using Gmail SMTP, so at the end of the file I&#8217;ve added</p>



<pre class="wp-block-code"><code lang="properties" class="language-properties">EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'me@example.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER</code></pre>



<h2 class="wp-block-heading">Backing up the image</h2>



<p class="wp-block-paragraph">After setting everything up, you&#8217;ll probably want to backup the Docker image.  First, print out the list of running containers</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker ps</code></pre>



<p class="wp-block-paragraph">Then take a snapshot of the current running state:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">docker commit -p &lt;container ID&gt; &lt;whatever you want to call this snapshot&gt;</code></pre>



<p class="wp-block-paragraph">Running this command lists all the images and should show this newly saved image:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker images</code></pre>



<p class="wp-block-paragraph">I don&#8217;t have a private docker repository, so I saved the image to the disk and backed up the file by doing the below.  Just make sure to actually move the image to an actual backup location.</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker save -o &lt;whatever path you want&gt;/&lt;filename&gt;.tar &lt;the name used earlier&gt;</code></pre>



<p class="wp-block-paragraph">The image should be backed up now.  To restore the image, it&#8217;s a matter of running this:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker load -i &lt;path to the backup file&gt;</code></pre>



<p class="wp-block-paragraph">Listing the images as above should show that the image was successfully loaded.  Running this starts it back up again.</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker run &lt;container name&gt;</code></pre>



<h2 class="wp-block-heading">Troubleshooting</h2>



<p class="wp-block-paragraph">Seafile logs can be helpful if it doesn&#8217;t start up correctly.  These can be found at:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">/opt/seafile-data/logs/seafile</code></pre>



<p class="wp-block-paragraph">There may be a need to ssh into the Docker container.  The command for that is:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">sudo docker exec -it seafile /bin/bash</code></pre>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.henrypoon.com/blog/2019/06/12/installing-seafile-with-docker-and-apache-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3509</post-id>	</item>
		<item>
		<title>Jenkins pipeline for Spring with beta and prod stages and deployment rollback</title>
		<link>https://blog.henrypoon.com/blog/2017/03/09/jenkins-pipeline-for-spring-with-beta-and-prod-stages-and-deployment-rollback/</link>
					<comments>https://blog.henrypoon.com/blog/2017/03/09/jenkins-pipeline-for-spring-with-beta-and-prod-stages-and-deployment-rollback/#respond</comments>
		
		<dc:creator><![CDATA[hp]]></dc:creator>
		<pubDate>Thu, 09 Mar 2017 08:04:51 +0000</pubDate>
				<category><![CDATA[computer stuff]]></category>
		<category><![CDATA[9]]></category>
		<category><![CDATA[Apache Ant]]></category>
		<category><![CDATA[Apache Maven]]></category>
		<category><![CDATA[Build automation]]></category>
		<category><![CDATA[Chan]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Compiling tools]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Const]]></category>
		<category><![CDATA[Continuous integration]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Digital technology]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[EAR]]></category>
		<category><![CDATA[future]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[Hole]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IME]]></category>
		<category><![CDATA[It]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java enterprise platform]]></category>
		<category><![CDATA[Jenkins]]></category>
		<category><![CDATA[Levant]]></category>
		<category><![CDATA[Password]]></category>
		<category><![CDATA[PATH]]></category>
		<category><![CDATA[Plug]]></category>
		<category><![CDATA[Port]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[Rolling]]></category>
		<category><![CDATA[Run]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[STR]]></category>
		<category><![CDATA[Thou]]></category>
		<category><![CDATA[Time]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[Variable]]></category>
		<category><![CDATA[Z]]></category>
		<category><![CDATA[Zip]]></category>
		<guid isPermaLink="false">https://blog.henrypoon.com/?p=2614</guid>

					<description><![CDATA[In the past couple of days, I&#8217;ve been experimenting a bit with the Jenkins pipeline plugin to create a code deployment pipeline with independent beta and prod stages for a Spring Boot app. I even managed to add rolling back a deployment in case a prod deployment fails! It took me a bit of time [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In the past couple of days, I&#8217;ve been experimenting a bit with the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin" target="_blank" rel="noopener">Jenkins pipeline plugin</a> to create a code deployment pipeline with independent beta and prod stages for a Spring Boot app. I even managed to add rolling back a deployment in case a prod deployment fails! It took me a bit of time to Google my way through how to do everything, so I figure I just lay it all out here in case it helps other people do the same thing.</p>



<p class="wp-block-paragraph">The nice thing about all of this is that I can push a code change to git, and Jenkins can build it, run through all the tests and then deploy to production automatically.</p>



<h1 class="wp-block-heading">Layout of a pipeline script</h1>



<p class="wp-block-paragraph">Pipeline scripts are written in <a rel="noopener" href="http://www.groovy-lang.org/" target="_blank">Groovy</a>, which is a variant of Java. In general, a pipeline script is laid out like this:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">node {
    def SOME_CONSTANT = "whatever"
    ...

    stage('some stage name like Build') {
        // Stuff to do as a part of this stage
    }

    stage('another stage') {
        // More stuff
    }

    ...
}</code></pre>



<p class="wp-block-paragraph">Each stage represents a stage in the pipeline (e.g. building, beta deployment, prod deployment etc.)</p>



<h1 class="wp-block-heading">Defining some constants</h1>



<p class="wp-block-paragraph">First, a list of constants can be defined that can be used throughout the pipeline so that if the pipeline script gets reused somewhere, only these constants have to be changed. I&#8217;m not aware of anything that lets me reuse a pipeline in Jenkins without copying and pasting the code somewhere else so for now I&#8217;ll have to live with copying and pasting.</p>



<p class="wp-block-paragraph">My project uses Maven so I got Jenkins to download its own copy of Maven that it can use to execute builds and have defined it as a constant. The name I&#8217;ve given it in the Jenkins Global Tool Configuration is &#8220;Maven 3.3.9&#8221; exactly. My project also uses Tomcat so there are some Tomcat specific things in there that may or may not be relevant to your use case.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">def MAVEN_HOME = tool 'Maven 3.3.9'
    def WORKSPACE = pwd()

    def PROJECT_NAME = "name-of-project"
    def WAR_PATH_RELATIVE = "App/target/${PROJECT_NAME}.war"
    def WAR_PATH_FULL = "${WORKSPACE}/${WAR_PATH_RELATIVE}"
    def TOMCAT_CTX_PATH_BETA = "Tomcat-context-path-for-the-beta-stage"
    def TOMCAT_CTX_PATH_PROD = "Tomcat-context-path-for-the-prod-stage"
    def GIT_REPO_URL = "URL-to-git-repo-ending-in-.git"</code></pre>



<h1 class="wp-block-heading">Preparation Stage</h1>



<p class="wp-block-paragraph">First, the code has to be retrieved from the repository before it gets built. Jenkins allows storing username/password pairs so that they can be referenced without having to write out the password in plaintext. Jenkins uses a &#8220;credential ID&#8221; for this.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">    stage('Preparation') {
        git branch: "master",
        credentialsId: "credentials-ID-stored-in-Jenkins-that-can-access-the-git-repo",
        url: "${GIT_REPO_URL}"
    }</code></pre>



<h1 class="wp-block-heading">Build Stage</h1>



<p class="wp-block-paragraph">Next, the code must be built and unit tested. &#8220;mvn clean install&#8221; will do just that (depending on what you want, you can always put in a different maven goal). The junit command is just there to take the resulting XML that gets generated during the build process and posts a graph of how many tests were run for each build.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">    stage('Build') {
        sh "'${MAVEN_HOME}/bin/mvn' clean install"
        junit '**/target/surefire-reports/TEST-*.xml'
    }
</code></pre>



<h1 class="wp-block-heading">Beta Stage</h1>



<p class="wp-block-paragraph">Once the build succeeds, you&#8217;ll want to deploy it to a beta environment, so integration tests can happen. The following happens at this stage:</p>



<ol class="wp-block-list"><li>Get the right credentials to get permissions to Tomcat</li><li>Call the deploy method to deploy the war file in Tomcat (more on that later)</li><li>If the deployment fails for whatever reason, print out the deployment log for debugging and fail the build</li><li>If the deployment succeeds, run the integration tests (the command to do this may differ based on use case)</li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python">    stage('Beta') {
        withCredentials([[$class: 'UsernamePasswordMultiBinding',
            credentialsId: 'credential-id-for-tomcat',
            usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
                // Password is available as an env variable, but will be masked 
                // if you try to print it out any which way
                def output = deploy(WAR_PATH_FULL, TOMCAT_CTX_PATH_BETA,
                        env.USERNAME, env.PASSWORD)
                if (output.contains("FAIL - Deployed application at context path " + 
                        "/${TOMCAT_CTX_PATH_BETA} but context failed to start")) {
                    echo "----- Beta deployment log -----"
                    echo output
                    echo "-------------------------------"
                    currentBuild.result = 'FAILURE'
                    error "Beta stage deployment failure"
                }
            }

        echo "Running integration tests"
        sh "'${MAVEN_HOME}/bin/mvn' -Dtest=*IT test"
        junit '**/target/surefire-reports/TEST-*.xml'
    }</code></pre>



<p class="wp-block-paragraph">The deploy method is what takes care of the actual deployment to Tomcat, which is how the Jenkins build tells Tomcat about the newly built war file. The deploy method is below (be sure to change the server IP and port). Alternatively, I could have built my project as an embedded jar file, but that has a different challenge in figuring out how to get Jenkins to tell the OS to execute the newly built jar file as a particular user.</p>



<ol class="wp-block-list"><li>Based on the Tomcat context path, decide whether a beta or production deployment is happening</li><li>Make a copy of the build war file and add .prod or .beta to the end of it so as to keep the original</li><li>Set the Spring profile to use on the newly copied war file (more on that later)</li><li>Call the curl command to do the actual deployment to Tomcat (more on that later)</li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python">def deploy(warPathFull, tomcatCtxPath, username, password) {
    def envSuffix = ""
    def isBeta = tomcatCtxPath.contains("beta")
    if (isBeta) {
        envSuffix = "beta"
    } else {
        envSuffix = "prod"
    }
    sh script: "cp ${warPathFull} ${warPathFull}.${envSuffix}" 
    setSpringProfile(warPathFull, isBeta)
    def output = sh script: "curl --upload-file '${warPathFull}.${envSuffix}' " +
            "'http://${username}:${password}@localhost:8081/manager/text/deploy" + 
            "?path=/${tomcatCtxPath}&amp;update=true'", returnStdout: true
    return output
}</code></pre>



<p class="wp-block-paragraph">In the case of my project, I&#8217;m building a single war file that does not have a Spring profile (beta/prod) defined. This means that I have to manually define this before I deploy the app to Tomcat since there are some things that differ between beta and prod like database URL&#8217;s. To do this, I wrote a method that opens the war file like a zip (jar/war files are zip files) and adds a line to my application.properties to define a Spring profile.</p>



<p class="wp-block-paragraph">Admittedly, doing this zip file manipulation seems kind of hacky. Alternatively, I could have defined my build such that I had a separate beta build and a prod build to avoid modifying the zip file, but the drawback is that I&#8217;d then have to build my code twice.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">def setSpringProfile(warPathFull, isBeta) {
    def zipFileFullPath = warPathFull + "." + (isBeta ? "beta" : "prod")
    def zipIn = new File(zipFileFullPath)
    def zip = new ZipFile(zipIn)
    def zipTemp = File.createTempFile("temp_${System.nanoTime()}", 'zip')
    zipTemp.deleteOnExit()
    def zos = new ZipOutputStream(new FileOutputStream(zipTemp))
    def toModify = "WEB-INF/classes/application.properties"

    for(e in zip.entries()) {
        if(!e.name.equalsIgnoreCase(toModify)) {
            zos.putNextEntry(e)
            zos &lt;&lt; zip.getInputStream(e).bytes
        } else {
            zos.putNextEntry(new ZipEntry(toModify))
            zos &lt;&lt; zip.getInputStream(e).bytes
            zos &lt;&lt; ("\nspring.profiles.active=" + (isBeta ? "beta" : "prod")).bytes
        }
        zos.closeEntry()
    }

    zos.close()
    zipIn.delete()
    zipTemp.renameTo(zipIn)
}</code></pre>



<p class="wp-block-paragraph">A curl command to Tomcat is what actually does the deployment. To deploy a file to Tomcat, do the following below. This will deploy the war file to Tomcat and instantly run it, thus it will be accessible at the given context path.</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">curl --upload-file 'path-to-war-file' http://username:password@server-address:port/manager/text/deploy?path=/tomcat-context-path&amp;update=true</code></pre>



<h1 class="wp-block-heading">Prod Stage</h1>



<p class="wp-block-paragraph">The same kind of stuff happens in the prod stage as in the beta stage with a few exceptions. The following happens at this stage:</p>



<ol class="wp-block-list"><li>Get the right credentials to get permissions to Tomcat</li><li>Call the deploy method to deploy the war file in Tomcat (except this time it is prod)</li><li>If the deployment fails for whatever reason, print out the deployment log for debugging and roll back the deployment</li><li>If the deployment succeeds, save the build files, and then the pipeline is finished. Alternatively, smoke tests can be run at this point, but I did not implement this in my project</li></ol>



<p class="wp-block-paragraph">Rollback is important because if the deployment fails, you don&#8217;t want to be stuck with a broken environment. Since build artifacts are saved on successful deployments, these same artifacts can be brought back if future deployments fail. This means they can be redeployed so that the code can be fixed before another deployment happens.</p>



<pre class="wp-block-code"><code lang="python" class="language-python">    stage('Prod') {
        withCredentials([[$class: 'UsernamePasswordMultiBinding',
            credentialsId: 'credential-id-for-tomcat',
            usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
                // Password is available as an env variable, but will be masked 
                // if you try to print it out any which way
                def output = deploy(WAR_PATH_FULL, TOMCAT_CTX_PATH_PROD, env.USERNAME, env.PASSWORD)
                if (output.contains("FAIL - Deployed application at context path " + 
                        "/${TOMCAT_CTX_PATH_PROD} but context failed to start")) {
                    echo "Prod stage deployment failure, rolling back deployment"
                    echo "----- Prod deployment log -----"
                    echo output
                    echo "-------------------------------"
                    step([$class: 'CopyArtifact',
                            filter: "${WAR_PATH_RELATIVE}",
                            fingerprintArtifacts: true,
                            projectName: "${PROJECT_NAME}",
                            target: "${WAR_PATH_RELATIVE}.rollback"])
                    deploy(WAR_PATH_FULL + ".rollback/" + WAR_PATH_RELATIVE,
                            TOMCAT_CTX_PATH_PROD, env.USERNAME, env.PASSWORD)
                    currentBuild.result = 'FAILURE'
                    error "Prod deployment rolled back"
                } else {
                    archiveArtifacts artifacts: "${WAR_PATH_RELATIVE}*", fingerprint: true
                }
            }
    }
</code></pre>



<p class="wp-block-paragraph">At the end you get to have something like this:</p>


<div class="wp-block-image">
<figure class="aligncenter"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="600" height="882" src="https://i0.wp.com/blog.henrypoon.com/wp-content/uploads/2017/03/JenkinsPipeline.png?resize=600%2C882&#038;ssl=1" alt="" class="wp-image-2638"/></figure>
</div>


<p class="wp-block-paragraph">That pretty much sums up the whole Jenkins pipeline that I&#8217;ve been using lately for Spring projects!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.henrypoon.com/blog/2017/03/09/jenkins-pipeline-for-spring-with-beta-and-prod-stages-and-deployment-rollback/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2614</post-id>	</item>
		<item>
		<title>Migrating a WordPress blog from WordPress.com to WordPress.org</title>
		<link>https://blog.henrypoon.com/blog/2015/04/03/migrating-a-wordpress-blog-from-wordpress-com-to-wordpress-org/</link>
					<comments>https://blog.henrypoon.com/blog/2015/04/03/migrating-a-wordpress-blog-from-wordpress-com-to-wordpress-org/#respond</comments>
		
		<dc:creator><![CDATA[hp]]></dc:creator>
		<pubDate>Fri, 03 Apr 2015 20:44:57 +0000</pubDate>
				<category><![CDATA[computer stuff]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Blog software]]></category>
		<category><![CDATA[Chan]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Digital media]]></category>
		<category><![CDATA[EAR]]></category>
		<category><![CDATA[followers]]></category>
		<category><![CDATA[Free software]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IME]]></category>
		<category><![CDATA[Installation]]></category>
		<category><![CDATA[It]]></category>
		<category><![CDATA[Link]]></category>
		<category><![CDATA[Matt]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[Net]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[Plug]]></category>
		<category><![CDATA[Port]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[site stats]]></category>
		<category><![CDATA[STR]]></category>
		<category><![CDATA[Time]]></category>
		<category><![CDATA[tuna]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[URL redirection]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress.com]]></category>
		<category><![CDATA[World Wide Web]]></category>
		<category><![CDATA[WP]]></category>
		<category><![CDATA[Z]]></category>
		<guid isPermaLink="false">https://www.henrypoon.com/blog/?p=2063</guid>

					<description><![CDATA[Since a few months ago, I migrated my blog from the previous free installation of WordPress that WordPress.com&#160;offered, to the self-hosted installation offered by WordPress.org&#160;(note that one is .org and the other is .com). &#160;Here are just a few of the key differences stated briefly: Self hosted installations allow greater control over what plugins the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Since a few months ago, I migrated my blog from the previous free installation of WordPress that <a href="http://www.wordpress.com" target="_blank" rel="noopener noreferrer">WordPress.com</a>&nbsp;offered, to the self-hosted installation offered by <a href="http://www.wordpress.org" target="_blank" rel="noopener noreferrer">WordPress.org</a>&nbsp;(note that one is .org and the other is .com). &nbsp;Here are just a few of the key differences stated briefly:</p>
<ul>
<li>Self hosted installations allow greater control over what plugins the blog uses, what domain name to use, monetization, among other things</li>
<li>The cost is the added time required to tweak to do the setup and customisation</li>
</ul>
<p>After I chose to switch to the self-hosted installation, I faced the problem of having to migrate all of my content, site&nbsp;stats, and followers. &nbsp;I also had to set up proper URL redirection to the new website. &nbsp;Most of the guides I read did answer how to migrate content, and set up URL redirects, but it was not so clear as to how to migrate my site&nbsp;stats and followers.</p>
<h1>Content Migration</h1>
<p>For migrating content, the WordPress.com blog allows exporting blog content into a file to be imported into the new WordPress installation. &nbsp;Steps 1 to 3 in this guide illustrate the process:&nbsp;<a href="http://www.wpbeginner.com/wp-tutorials/how-to-properly-move-your-blog-from-wordpress-com-to-wordpress-org/" target="_blank" rel="noopener noreferrer">http://www.wpbeginner.com/wp-tutorials/how-to-properly-move-your-blog-from-wordpress-com-to-wordpress-org/</a></p>
<h1>Migrating Site&nbsp;Stats and Followers</h1>
<p>Migrating site stats and followers requires installing the <a href="https://wordpress.org/plugins/jetpack/" target="_blank" rel="noopener noreferrer">Jetpack</a>&nbsp;addon and linking it to the WordPress.com account (so that the self-hosted WP and the existing WP blog are connected). &nbsp;Afterward, a support thread has to be made on WordPress.com to ask WP staff to do the rest of the migration (there seems to be no other way). &nbsp;I found the information on how to do this at this site: <a href="http://wordpress.stackexchange.com/questions/161633/migrating-stats-from-wordpress-com-blog-to-self-hosted-wordpress-org-blog" target="_blank" rel="noopener noreferrer">http://wordpress.stackexchange.com/questions/161633/migrating-stats-from-wordpress-com-blog-to-self-hosted-wordpress-org-blog</a>. &nbsp;The post I made for my own site migration is <a href="https://en.forums.wordpress.com/topic/transferring-stats-and-subscribers-from-wordpresscom-to-self-hosted-wordpress?replies=8" target="_blank" rel="noopener noreferrer">here</a>.</p>
<h1>Setting Up URL Redirection</h1>
<p>This part costs money unfortunately. &nbsp;I paid ~$17 CAD for this so that my own URL would be redirected for the new one. &nbsp;If redirection isn&#8217;t required, then there is no need to buy anything. &nbsp;The setup is pretty straight forward. &nbsp;After buying the redirect, it is just a matter of setting the destination WordPress site to go to. &nbsp;Reference link here:&nbsp;<a href="https://en.support.wordpress.com/site-redirect/" target="_blank" rel="noopener noreferrer">https://en.support.wordpress.com/site-redirect/</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.henrypoon.com/blog/2015/04/03/migrating-a-wordpress-blog-from-wordpress-com-to-wordpress-org/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2063</post-id>	</item>
		<item>
		<title>Really Handy LaTeX Commands</title>
		<link>https://blog.henrypoon.com/blog/2011/08/21/really-handy-latex-commands/</link>
					<comments>https://blog.henrypoon.com/blog/2011/08/21/really-handy-latex-commands/#respond</comments>
		
		<dc:creator><![CDATA[hp]]></dc:creator>
		<pubDate>Sun, 21 Aug 2011 22:39:08 +0000</pubDate>
				<category><![CDATA[computer stuff]]></category>
		<category><![CDATA[agra]]></category>
		<category><![CDATA[Assimilation]]></category>
		<category><![CDATA[Bullet]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Comment]]></category>
		<category><![CDATA[Contents]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Diaeresis]]></category>
		<category><![CDATA[EAR]]></category>
		<category><![CDATA[Find]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[HTML element]]></category>
		<category><![CDATA[Introduction]]></category>
		<category><![CDATA[It]]></category>
		<category><![CDATA[Link]]></category>
		<category><![CDATA[Literature]]></category>
		<category><![CDATA[Page]]></category>
		<category><![CDATA[Table of contents]]></category>
		<category><![CDATA[Thou]]></category>
		<category><![CDATA[Umlaut]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[Writing]]></category>
		<category><![CDATA[Z]]></category>
		<guid isPermaLink="false">http://henrypoon.mooo.com/blog/really-handy-latex-commands</guid>

					<description><![CDATA[I just started writing in LaTeX and all too often I find myself forgetting commands that I had looked up a few minutes ago.  Therefore, I thought it’d help if I compiled a list of these. Paragraph Spacing This goes in the preamble of the document (after the document class stuff, but before the begin [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">I just started writing in LaTeX and all too often I find myself forgetting commands that I had looked up a few minutes ago.  Therefore, I thought it’d help if I compiled a list of these.</p>



<h1 class="wp-block-heading">Paragraph Spacing</h1>



<pre class="wp-block-code"><code lang="" class="">setlength{parskip}{7pt}</code></pre>



<p class="wp-block-paragraph">This goes in the preamble of the document (after the document class stuff, but before the begin document line).</p>



<h1 class="wp-block-heading">Removing Page Numbers</h1>



<pre class="wp-block-code"><code class="">thispagestyle{empty}</code></pre>



<p class="wp-block-paragraph">This gets rid of page numbers for that particular page, but the numbering sequence continues on the next page.</p>



<h1 class="wp-block-heading">Adding Unnumbered Sections into the TOC</h1>



<pre class="wp-block-code"><code class="">section*{Introduction}
addcontentsline{toc}{section}{Introduction}</code></pre>



<p class="wp-block-paragraph">By default, unnumbered sections do not appear in the table of contents and therefore they must be added manually.</p>



<h1 class="wp-block-heading">Defining a New Style with fancyhdr</h1>



<pre class="wp-block-code"><code class="">fancypagestyle{plain}{%
fancyhf{}}% clear all header and footer fields</code></pre>



<p class="wp-block-paragraph">New style definitions should go before the very last curly brace.</p>



<h1 class="wp-block-heading">Unnumbered Sections Not Working with leftmark and rightmark</h1>



<pre class="wp-block-code"><code class="">section*{Introductionmarkboth{Introduction}{}}</code></pre>



<p class="wp-block-paragraph">For some reason, unnumbered sections don’t play nice with fancyhdr and don’t get treated as <em>real</em> sections when the leftmark and rightmark commands are used.&nbsp; By using markboth, it fixes the problem.&nbsp; Now my headers show the correct section name.</p>



<h1 class="wp-block-heading">Bulleted List</h1>



<pre class="wp-block-code"><code class="">begin{itemize}
item Here is a bullet.
item Here is another bullet.
end{itemize}</code></pre>



<h1 class="wp-block-heading">Numbered List</h1>



<pre class="wp-block-code"><code class="">begin{enumerate}
item Here is item one.
item Here is item two.
end{enumerate}</code></pre>



<h1 class="wp-block-heading">Referencing Sections by Name</h1>



<pre class="wp-block-code"><code class="">section{MyFirstSection} label{marker}
section{MySecondSection}
In section~nameref{marker} we defined...</code></pre>



<p class="wp-block-paragraph">Requires the <em>hyperref</em> package!  Put the line below in the preamble.</p>



<pre class="wp-block-code"><code class="">usepackage{hyperref}</code></pre>



<h1 class="wp-block-heading">Linking to a Website</h1>



<pre class="wp-block-code"><code class="">href{http://www.example.com}{Link}</code></pre>



<h1 class="wp-block-heading">Umlauts</h1>



<pre class="wp-block-code"><code class="">"{o}</code></pre>



<p class="wp-block-paragraph">That gives an o with an umlaut.&nbsp; Just replace the letter to get an umlaut on a different character.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.henrypoon.com/blog/2011/08/21/really-handy-latex-commands/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1224</post-id>	</item>
		<item>
		<title>Serial Communication in Java with Example Program</title>
		<link>https://blog.henrypoon.com/blog/2011/01/01/serial-communication-in-java-with-example-program/</link>
					<comments>https://blog.henrypoon.com/blog/2011/01/01/serial-communication-in-java-with-example-program/#comments</comments>
		
		<dc:creator><![CDATA[hp]]></dc:creator>
		<pubDate>Sun, 02 Jan 2011 01:46:37 +0000</pubDate>
				<category><![CDATA[computer stuff]]></category>
		<category><![CDATA[9]]></category>
		<category><![CDATA[All That]]></category>
		<category><![CDATA[APT]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Chan]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Comment]]></category>
		<category><![CDATA[Computer]]></category>
		<category><![CDATA[Computer languages]]></category>
		<category><![CDATA[Const]]></category>
		<category><![CDATA[Cookbook]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Dia]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[Drive]]></category>
		<category><![CDATA[EAR]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Final]]></category>
		<category><![CDATA[Find]]></category>
		<category><![CDATA[Flag]]></category>
		<category><![CDATA[Go]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Hole]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[IME]]></category>
		<category><![CDATA[Introduction]]></category>
		<category><![CDATA[IOS]]></category>
		<category><![CDATA[ise]]></category>
		<category><![CDATA[It]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Lag]]></category>
		<category><![CDATA[Lie]]></category>
		<category><![CDATA[Link]]></category>
		<category><![CDATA[Object]]></category>
		<category><![CDATA[Object-oriented programming languages]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Over]]></category>
		<category><![CDATA[Page]]></category>
		<category><![CDATA[Parameter]]></category>
		<category><![CDATA[PDF]]></category>
		<category><![CDATA[Plan]]></category>
		<category><![CDATA[Port]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming languages]]></category>
		<category><![CDATA[RAR]]></category>
		<category><![CDATA[Reference]]></category>
		<category><![CDATA[Rolling]]></category>
		<category><![CDATA[Run]]></category>
		<category><![CDATA[Serial]]></category>
		<category><![CDATA[Serial communication]]></category>
		<category><![CDATA[Software design patterns]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Speed]]></category>
		<category><![CDATA[STR]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Struct]]></category>
		<category><![CDATA[Swing]]></category>
		<category><![CDATA[Thou]]></category>
		<category><![CDATA[Time]]></category>
		<category><![CDATA[UNC]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[Variable]]></category>
		<category><![CDATA[Vol]]></category>
		<category><![CDATA[Wiki]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress.com]]></category>
		<category><![CDATA[Writing]]></category>
		<category><![CDATA[XBee]]></category>
		<category><![CDATA[Z]]></category>
		<category><![CDATA[Zip]]></category>
		<guid isPermaLink="false">http://henrypoon.mooo.com/blog/serial-communication-in-java-with-example-program</guid>

					<description><![CDATA[This is more of a follow-up to my previous post about serial programming in Java (here) and how to install the RXTX libraries (here).&#160; This post also assumes that Java is already properly set up with RXTX. Generally, communication with serial ports involves these steps (in no particular order): Searching for serial ports Connecting to [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is more of a follow-up to my previous post about serial programming in Java (<a title="Java Serial&nbsp;Programming" href="http://henrypoon.wordpress.com/2010/10/11/java-serial-programming/" target="_blank" rel="noopener">here</a>) and how to install the RXTX libraries (<a title="Installing RXTX for Serial Communication with&nbsp;Java" href="http://henrypoon.wordpress.com/2010/12/25/installing-rxtx-for-serial-communication-with-java/" target="_blank" rel="noopener">here</a>).&nbsp; This post also assumes that Java is already properly set up with RXTX.</p>



<p class="wp-block-paragraph">Generally, communication with serial ports involves these steps (in no particular order):</p>



<ul class="wp-block-list"><li>Searching for serial ports</li><li>Connecting to the serial port</li><li>Starting the input output streams</li><li>Adding an event listener to listen for incoming data</li><li>Disconnecting from the serial port</li><li>Sending Data</li><li>Receiving Data</li></ul>



<p class="wp-block-paragraph">I wrote an example program that includes all of those steps in it and are each in their own separate method within the class, but first I will go through my hardware set up.</p>



<h1 class="wp-block-heading">Hardware Setup</h1>



<p class="wp-block-paragraph">My current hardware setup is as follows:</p>



<ul class="wp-block-list"><li>PC connected to an XBee</li><li>Arduino connected to an XBee</li></ul>



<p class="wp-block-paragraph">User input is given from the PC through the a Java GUI that contains code for serial communication, which is the code presented here.</p>



<p class="wp-block-paragraph">The Arduino is responsible for reading this data.&nbsp; This set up is pretty much using my computer as a remote control for whatever device is on the Arduino end.&nbsp; It could be a motor control, on-off switch, etc.</p>



<h1 class="wp-block-heading">Existing Code</h1>



<p class="wp-block-paragraph">The purpose of this post is to discuss serial programming in Java, and not GUI’s.&nbsp; However, I did create a GUI for testing purposes.&nbsp; See the Code Downloads section for the actual files.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="300" height="136" src="https://i0.wp.com/blog.henrypoon.com/wp-content/uploads/2011/03/javagui.png?resize=300%2C136&#038;ssl=1" alt="" class="wp-image-933" srcset="https://i0.wp.com/blog.henrypoon.com/wp-content/uploads/2011/03/javagui.png?resize=300%2C136&amp;ssl=1 300w, https://i0.wp.com/blog.henrypoon.com/wp-content/uploads/2011/03/javagui.png?w=640&amp;ssl=1 640w" sizes="(max-width: 300px) 100vw, 300px" /></figure>
</div>


<p class="wp-block-paragraph">Above is the picture of the GUI complete with the buttons that I use to interact with the program.&nbsp; I also added key bindings which I can use to control the throttle.</p>



<p class="wp-block-paragraph">When the program is first started, none of the GUI elements will work except for the combo box and the connect button.&nbsp; Once a successful connection is made the controls are enabled.&nbsp; This is done through the use of the <em>setConnected(true)</em> and the <em>toggleControls()</em> methods shown in the example code that follows.</p>



<h1 class="wp-block-heading">Imports</h1>



<p class="wp-block-paragraph">The imports i used for this program were as follows:</p>



<pre class="wp-block-code"><code lang="java" class="language-java">import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;</code></pre>



<p class="wp-block-paragraph">Depending on the Java IDE it might already know to tell you to use these imports except for the first one.&nbsp; That first import is specific to RXTX, and all its library methods/classes are in there.</p>



<h1 class="wp-block-heading">Class Declaration</h1>



<p class="wp-block-paragraph">The code here reads:</p>



<pre class="wp-block-code"><code lang="java" class="language-java">public class Communicator implements SerialPortEventListener</code></pre>



<p class="wp-block-paragraph">I named my class <em>Communicator</em>, but the name is really up to the programmer.&nbsp; The name pretty much reflects its intended use.</p>



<p class="wp-block-paragraph">The class should also <em>implement</em> the <em>SerialPortEventListener</em> class.&nbsp; This is a class in RXTX and is required in order to receive incoming data.</p>



<p class="wp-block-paragraph">On some IDE’s this may generate a public void method called <em>serialEvent()</em>.&nbsp; This method will be defined later.</p>



<h1 class="wp-block-heading">Class Variables and Constants</h1>



<p class="wp-block-paragraph">Below are the variables and constants that I defined in my class.&nbsp; What the variables are for is in the comments but a more detailed explanation will follow.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //passed from main GUI
    GUI window = null;

    //for containing the ports that will be found
    private Enumeration ports = null;
    //map the port names to CommPortIdentifiers
    private HashMap portMap = new HashMap();

    //this is the object that contains the opened port
    private CommPortIdentifier selectedPortIdentifier = null;</code></pre>



<p class="wp-block-paragraph">I could have easily put the variable definitions in the constructor but it wouldn’t change anything.</p>



<p class="wp-block-paragraph">The <em>GUI</em> object is another class that I wrote separate from this one that contains all the GUI elements.&nbsp; The GUI class extends <em>javax.swing.JFrame</em>.</p>



<p class="wp-block-paragraph">The <em>HashMap</em> is for mapping each of the ports’ names to the actual object. What that means is that I can associate (<em>put()</em> method) the name of a serial port, say a string that says COM1, to an object in the code.&nbsp; Later, I can access the name COM1 from the <em>HashMap</em> by using the <em>get()</em> method and it will return the object that it was associated with previously.</p>



<p class="wp-block-paragraph">The <em>CommPortIdentifiers</em> object is needed to gather the list of ports that are available for connection. by using its <em>getPortIdentifiers()</em> method.</p>



<p class="wp-block-paragraph">The <em>SerialPort</em> object is for storing the data for the port once a successful connection is made.</p>



<p class="wp-block-paragraph">The <em>InputStream</em> and <em>OutputStream</em> is the object that is required for sending and receiving data.</p>



<p class="wp-block-paragraph">The Boolean variable <em>bConnected</em> is just a flag that I use for enabling and disabling elements on the GUI.</p>



<p class="wp-block-paragraph">The constant <em>TIMEOUT</em> is a number required when opening the port so that it knows how long to try for before stopping.</p>



<p class="wp-block-paragraph">The constants for the ASCII values are some values that I use to send through the output stream that act as delimiters for data.</p>



<p class="wp-block-paragraph">The string <em>logText</em> is basically what the comment says.&nbsp; When stuff happens in the program, the program stores a string in this variable and it will be appended to a text area in the GUI.</p>



<h1 class="wp-block-heading">Searching for Available Serial Ports</h1>



<p class="wp-block-paragraph">The method below is for searching for available serial ports on the computer.&nbsp; Code adapted from Discovering Available Comm Ports from the Reference Material.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //search for all the serial ports
    //pre style="font-size: 11px;": none
    //post: adds all the found ports to a combo box on the GUI
    void searchForPorts()
    {
        ports = CommPortIdentifier.getPortIdentifiers();

        &lt;span style="color: blue;"&gt;while (ports.hasMoreElements())
        {
            CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

            //get only serial ports
            &lt;span style="color: blue;"&gt;if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                window.cboxPorts.addItem(curPort.getName());
                portMap.put(curPort.getName(), curPort);
            }
        }
    }</code></pre>



<p class="wp-block-paragraph">The method <em>getPortIdentifiers()</em> returns an Enumeration of all the comm ports on the computer.&nbsp; The code can iterate through each element inside the Enumeration and determine whether or not it is a serial port.&nbsp; The method <em>getPortType()</em> can identify what kind of port it is.&nbsp; If it is a serial port, then the code will add its name to a combo box in the GUI (so that users can pick what port to connect to).&nbsp; The serial port that is found should also be mapped to the HashMap so we can identify the object later.&nbsp; This is helpful because the names listed in the combo box are the actual names of the object (COM1, COM2, etc), and so we can use these names to identify the actual object they are tied to.</p>



<h1 class="wp-block-heading">Connecting to the Serial Port</h1>



<p class="wp-block-paragraph">The method below is for connecting to the serial port once they have been found (see previous section).&nbsp; See How to Open A Serial Port in the Reference Material for more information.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">
    //connect to the selected port in the combo box
    //ports are already found by using the searchForPorts
    //method
    //post: the connected comm port is stored in commPort, otherwise,
    //an exception is generated
    public void connect()
    {
        String selectedPort = (String)window.cboxPorts.getSelectedItem();
        selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);

        CommPort commPort = null;

        try
        {
            //the method below returns an object of type CommPort
            commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
            //the CommPort object can be casted to a SerialPort object
            serialPort = (SerialPort)commPort;

            //for controlling GUI elements
            setConnected(true);

            //logging
            logText = selectedPort + " opened successfully.";
            window.txtLog.setForeground(Color.black);
            window.txtLog.append(logText + "n");

            //CODE ON SETTING BAUD RATE ETC OMITTED
            //XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY

            //enables the controls on the GUI if a successful connection is made
            window.keybindingController.toggleControls();
        }
        catch (PortInUseException e)
        {
            logText = selectedPort + " is in use. (" + e.toString() + ")";

            window.txtLog.setForeground(Color.RED);
            window.txtLog.append(logText + "n");
        }
        catch (Exception e)
        {
            logText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
            window.txtLog.append(logText + "n");
            window.txtLog.setForeground(Color.RED);
        }
    }</code></pre>



<p class="wp-block-paragraph">Using the <em>HashMap</em> we can retrieve the <em>CommPortIdentifier</em> object from the string that was mapped earlier.&nbsp; This is achieved through the <em>HashMap’s</em> <em>get()</em> method.&nbsp; The object must also be casted as a <em>CommPortIdentifier</em> because the <em>get()</em> method has a return type of <em>Object</em>.</p>



<p class="wp-block-paragraph">The <em>setConnected </em>method just changes a boolean flag so that the program can store whether or not it is connected to a serial port or not.</p>



<p class="wp-block-paragraph">The <em>CommPort</em> must also be initialized because the port object will be stored here once a successful connection is made.</p>



<p class="wp-block-paragraph">The main method of interest here is the <em>open()</em> method.&nbsp; This instructs the program to open the port, and this method will return the object for the opened port, which I store in in the previously initialized <em>CommPort </em>object.&nbsp; I then cast this object as a <em>SerialPort</em> and store it as well.&nbsp; This is helpful for accessing the methods and variables specific to the <em>SerialPort</em> class.</p>



<p class="wp-block-paragraph">It should also be noted that the <em>open()</em> method requires the use of a try-catch block.&nbsp; So applying that, I catch two different exceptions.&nbsp; The <em>PortInUseException</em> is what the name says.&nbsp; If the port is in use, then this exception is thrown.&nbsp; The next catch block is just for the generic exceptions that occur.&nbsp; I never came across that during testing, nor do I know how to replicate that.</p>



<p class="wp-block-paragraph">I neglected to include any code for setting the baud rate and other settings on the XBee’s (see Hardware Configuration), because I already set those parameters previously using X-CTU (more on setting up XBee’s here).</p>



<h1 class="wp-block-heading">Initializing the Input and Output Streams</h1>



<p class="wp-block-paragraph">This method is pretty short and is pretty straightforward to read.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //open the input and output streams
    //pre style="font-size: 11px;": an open port
    //post: initialized input and output streams for use to communicate data
    public boolean initIOStream()
    {
        //return value for whether opening the streams is successful or not
        boolean successful = false;

        try {
            //
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            writeData(0, 0);

            successful = true;
            return successful;
        }
        catch (IOException e) {
            logText = "I/O Streams failed to open. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "n");
            return successful;
        }
    }</code></pre>



<p class="wp-block-paragraph">The streams are initialized by returning the input and output streams of the open serial port.&nbsp; In order for the serial port object to not be null, it must store the object for the open serial port.</p>



<p class="wp-block-paragraph">The <em>getInputStream()</em> and <em>getOutputStream()</em> methods both require a try-catch block.&nbsp; The important exception to catch here is the <em>IOException</em> to signify whether the streams failed to open or not.&nbsp; For more information see How to Open A Serial Port in the Reference Material.</p>



<p class="wp-block-paragraph">I also call a method called <em>writeData(0, 0)</em>.&nbsp; This is the method that encapsulates the code required to write serial data.&nbsp; More on that later.&nbsp; Right now it is just used to set variables on the microcontroller side to zero.</p>



<h1 class="wp-block-heading">Setting Up Event Listeners to Read Data</h1>



<p class="wp-block-paragraph">Once the port is open, the serial port must know whenever there is data to be read.&nbsp; This approach is event driven rather than by polling.&nbsp; When the event is hit, a special block of code will run.&nbsp; This is advantageous to polling because polling requires constantly asking if data is available.&nbsp; The code for the event driven approach is below.&nbsp; See Event Based Two Way Communication for more information.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //starts the event listener that knows whenever data is available to be read
    //pre style="font-size: 11px;": an open serial port
    //post: an event listener for the serial port that knows when data is received
    public void initListener()
    {
        try
        {
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        }
        catch (TooManyListenersException e)
        {
            logText = "Too many listeners. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "n");
        }
    }</code></pre>



<p class="wp-block-paragraph">The code here is pretty much the whole reason why this class implements <em>SerialPortEventListener</em>.&nbsp; The parameter for adding the event listener is just the object itself.&nbsp; The base class has a method called <em>serialEvent(event)</em> that should be overridden before the event code will work.&nbsp; Overriding that method defines what happens when the event is hit.</p>



<p class="wp-block-paragraph">The method <em>addEventListener(this)</em> is the event that is always checking for <em>SerialEvents</em>.&nbsp; It isn’t really important to know what the events actually are, just that the one we’re interested in is the one that tells us whenever data is received.&nbsp; Adding the event listener is complemented by the method <em>notifyOnDataAvailable(true)</em>, which definitely helps us achieve what I mentioned previously.</p>



<p class="wp-block-paragraph">This code requires a try-catch box.&nbsp; The exception here is that there may be too many event listeners.&nbsp; I only use one in the code, so this exception should never be hit.</p>



<h1 class="wp-block-heading">Disconnecting from the Serial Port</h1>



<p class="wp-block-paragraph">Once all the communication is completed, the serial port must be disconnected.&nbsp; In some instances, some ports stay stuck open, which isn’t exactly a good thing.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //disconnect the serial port
    //pre style="font-size: 11px;": an open serial port
    //post: closed serial port
    public void disconnect()
    {
        //close the serial port
        try
        {
            writeData(0, 0);

            serialPort.removeEventListener();
            serialPort.close();
            input.close();
            output.close();
            setConnected(false);
            window.keybindingController.toggleControls();

            logText = "Disconnected.";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "n");
        }
        catch (Exception e)
        {
            logText = "Failed to close " + serialPort.getName()
                              + "(" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "n");
        }
    }</code></pre>



<p class="wp-block-paragraph">The code here requires a try-catch block so there it is.&nbsp; The exception to catch here is pretty generic.</p>



<p class="wp-block-paragraph">Before closing the port, I reset the data on the microcontroller.&nbsp; That step is optional depending on the application.&nbsp; For example, if the value sent to the microcontroller is controlling the speed of a motor, I’d want the motor to turn off if I turn off the remote control.</p>



<p class="wp-block-paragraph">The event listener should be removed as it is no longer needed.</p>



<p class="wp-block-paragraph">The method to close the port is the <em>close()</em> method.</p>



<p class="wp-block-paragraph">The input and output streams should also be closed via the same method as above.</p>



<p class="wp-block-paragraph">See How to Close A Serial Port in the Reference section for more information.</p>



<h1 class="wp-block-heading">Reading Data – The <em>serialEvent</em> Method</h1>



<p class="wp-block-paragraph">This is a follow-up to the section on preparing to Read Data.&nbsp; It has information on how to process the data that the program reads.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //what happens when data is received
    //pre style="font-size: 11px;": serial event is triggered
    //post: processing on the data it reads
    public void serialEvent(SerialPortEvent evt) {
        if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
        {
            try
            {
                byte singleData = (byte)input.read();

                if (singleData != NEW_LINE_ASCII)
                {
                    logText = new String(new byte[] {singleData});
                    window.txtLog.append(logText);
                }
                else
                {
                    window.txtLog.append("n");
                }
            }
            catch (Exception e)
            {
                logText = "Failed to read data. (" + e.toString() + ")";
                window.txtLog.setForeground(Color.red);
                window.txtLog.append(logText + "n");
            }
        }
    }</code></pre>



<p class="wp-block-paragraph">Since we only want to read data if it exists, we test the condition in the if statement above.&nbsp; This could be redundant because we wouldn’t be in this method if the event never got triggered.</p>



<p class="wp-block-paragraph">Reading the data requires a try-catch block.&nbsp; The <em>read()</em> method returns an integer, but the value in it is actually a byte value so this is casted to a byte, in which I store in a variable called <em>singleData</em>.&nbsp; When I was testing this code before, I noticed that the data being read would always have random new line characters in it, and I never knew why this happened.&nbsp; I never wrote any new line characters.&nbsp; Since I don’t want these, I add an if condition saying that if it encounters that, don’t display that data on the screen.</p>



<p class="wp-block-paragraph">Java also has a nice way of converting bytes to a string.  A byte array can be used as a parameter when initializing a string, which is what I’ve done when I assign a value to <em>logText</em>.</p>



<p class="wp-block-paragraph">The exception here is just the usual generic one.</p>



<h1 class="wp-block-heading">Writing Data</h1>



<p class="wp-block-paragraph">Here is the method for writing data.&nbsp; In my application, I am writing two integers sequentially to my microcontroller.&nbsp; Data that is sent to the MCU can be used for such things such as controlling motor speeds, which is what I am trying to do here.&nbsp; I hope to use the data sent do control the PWM duty cycle of the motor for speed control.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">    //method that can be called to send data
    //pre style="font-size: 11px;": open serial port
    //post: data sent to the other device
    public void writeData(int leftThrottle, int rightThrottle)
    {
        try
        {
            output.write(leftThrottle);
            output.flush();
            //this is a delimiter for the data
            output.write(DASH_ASCII);
            output.flush();

            output.write(rightThrottle);
            output.flush();
            //will be read as a byte so it is a space key
            output.write(SPACE_ASCII);
            output.flush();
        }
        catch (Exception e)
        {
            logText = "Failed to write data. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "n");
        }
    }</code></pre>



<p class="wp-block-paragraph">The <em>write() </em>method here requires a try-catch block just like many of the other methods used for serial communication.&nbsp; Using the output stream, I call that method to write an integer value.&nbsp; I also write a dash and a space to separate the actual data being read.&nbsp; See the ASCII Table for the values of what these characters should be.&nbsp; This helps me differentiate the sets of data that is sent back and forth.&nbsp; The dash separates the two integers being sent and the space separates the entire set.&nbsp; On the Arduino end, four called to <em>read()</em> can separate the data without mixing things up.&nbsp; Example of that later.</p>



<h1 class="wp-block-heading">Putting All the Java Code Together</h1>



<p class="wp-block-paragraph">Once all these methods are setup, they need to be called somewhere in the program so we can put them to use.&nbsp; When the program starts, the code for searching for serial ports will run so that it can populate the combo box on the GUI.&nbsp; The GUI buttons also need to be disabled to reflect the fact they should be disabled when there is no connection to a port.&nbsp; When the connect button is pressed, the input and output streams are started and the event listener is added.&nbsp; The code for that is shown below.</p>



<pre class="wp-block-code"><code lang="java" class="language-java">        private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
            communicator.connect();
            if (communicator.getConnected() == true)
            {
                if (communicator.initIOStream() == true)
                {
                    communicator.initListener();
                }
            }
        }</code></pre>



<p class="wp-block-paragraph">The if statement is needed such that the code will not run if a successful connection was not made.&nbsp; This is the precondition for the <em>initIOStream() </em>and the <em>initLIstener() </em>methods.</p>



<p class="wp-block-paragraph">When the user decides to disconnect from the serial port, the user only needs to call the <em>disconnect()</em> method when the disconnect button is pressed.</p>



<p class="wp-block-paragraph">The up/down arrows on my GUI are set to write data to the serial port when they are pressed.&nbsp; When data is written to the Arduino, the MCU will send the data back to the Java program, which will signal the event listener to display that data back to the screen.</p>



<h1 class="wp-block-heading">Arduino Code</h1>



<p class="wp-block-paragraph">The Arduino code is pretty straight forward.&nbsp; There are just a few calls to the <em>read()</em> method.</p>



<p class="wp-block-paragraph">Update 6 May 2012: the syntax for the Arduino code has updated since the writing of this article. &nbsp;Apparently, the lines</p>



<pre class="wp-block-code"><code lang="c" class="language-c">Serial.print(separator, BYTE);
Serial.print(space, BYTE);</code></pre>



<p class="wp-block-paragraph">are no longer valid and have since been replaced by the following:</p>



<pre class="wp-block-code"><code lang="c" class="language-c">Serial.write(byte(separator));
Serial.write(byte(space));</code></pre>



<p class="wp-block-paragraph">The code below hasn&#8217;t been edited with this change, but basically the code required for writing a byte value through serial communication has changed.</p>



<pre class="wp-block-code"><code lang="c" class="language-c">
// this is where we will put our data
int left = 0;
int right = 0;
byte space = 0;
byte separator = 0;

void setup(){
  // Start up our serial port, we configured our XBEE devices for 38400 bps. 
  Serial.begin(9200);
}

void loop(){
  // handle serial data, if any
  if (Serial.available() &amp;gt;= 4){
    left = Serial.read();
    separator = Serial.read();
    right = Serial.read();
    space = Serial.read();
    Serial.flush();

    Serial.print(left);
    Serial.print(separator, BYTE);
    Serial.print(right);
    Serial.print(space, BYTE);
    Serial.print("n");
  }
}</code></pre>



<p class="wp-block-paragraph">I first declare four variables to reflect the fact that I’m writing four different variables to the serial port.</p>



<p class="wp-block-paragraph">In the loop method, I added a condition which will check whether there are four pieces of data available before reading them.&nbsp; This again reflects the fact I’m writing four values.</p>



<p class="wp-block-paragraph">The four variables initially declared store the values in the order that they are written, and then are just printed to the screen.</p>



<p class="wp-block-paragraph">The <em>print()</em> method is able to convert the byte value to an actual character by adding a second parameter called <em>BYTE</em>.&nbsp; The left and right variables don’t need it because the values written were integers to begin with, however, the dash and space characters were written as ASCII values.</p>



<p class="wp-block-paragraph">For more information about Arduino and Java, and Arduino’s Serial library, please refer to those in the Reference Section.</p>



<h1 class="wp-block-heading">Code Downloads</h1>



<p class="wp-block-paragraph">Here are the code downloads for the GUI, key bindings and the serial communication.&nbsp; WordPress doesn’t allow uploads of zip or java files so I uploaded it all to Megaupload.</p>



<p class="wp-block-paragraph">Link to download:&nbsp;<a href="http://www.mediafire.com/?z2l26ncypmzn20z" target="_blank" rel="noopener">http://www.mediafire.com/?z2l26ncypmzn20z</a></p>



<h1 class="wp-block-heading">Other Examples</h1>



<p class="wp-block-paragraph">There are also other sites I looked at which had example code for serial port communication in Java.&nbsp; The sites are Programming Serial and Parallel Ports and Serial Port Access Using RXTX in Java, which are both in the Reference section.</p>



<h1 class="wp-block-heading">Reference Material</h1>



<p class="wp-block-paragraph">Below are a bunch of links to reference sites that I used to find some of the information written here.&nbsp; I mostly referred to bits and pieces of each article to understand the serial code and to come up with the example I present here.&nbsp; The list is in the order that I referenced them.</p>



<h2 class="wp-block-heading">Discovering Available Comm Ports</h2>



<p class="wp-block-paragraph"><a href="http://rxtx.qbang.org/wiki/index.php/Discovering_available_comm_ports" target="_blank" rel="noopener">http://rxtx.qbang.org/wiki/index.php/Discovering_available_comm_ports</a></p>



<p class="wp-block-paragraph">The code on this page is pretty specific to the title of this heading, and the code is pretty easy to follow.</p>



<h2 class="wp-block-heading">How to Open A Serial Port</h2>



<p class="wp-block-paragraph"><a target="_blank" rel="noopener">http://embeddedfreak.wordpress.com/2008/08/08/how-to-open-serial-port-using-rxtx/</a></p>



<p class="wp-block-paragraph">This page provides a very concise and detailed explanation on what each line of code does in order to get a serial port open.&nbsp; Definitely work a look if you’re trying to understand the code.</p>



<h2 class="wp-block-heading">Event Based Two Way Communication</h2>



<p class="wp-block-paragraph"><a href="http://rxtx.qbang.org/wiki/index.php/Event_Based_Two_Way_Communication" target="_blank" rel="noopener">http://rxtx.qbang.org/wiki/index.php/Event_Based_Two_Way_Communication</a></p>



<p class="wp-block-paragraph">This page has example code on how to connect to a serial port and how to interact with it.&nbsp; The code here uses events, rather than polling, to send data back and forth, which means that whenever data is received, the event code is triggered.</p>



<h2 class="wp-block-heading">How to Close A Serial Port</h2>



<p class="wp-block-paragraph"><a target="_blank" rel="noopener">http://embeddedfreak.wordpress.com/2008/08/08/how-to-close-serial-port-in-rxtx/</a></p>



<p class="wp-block-paragraph">This article is written by the same author who wrote the article on how to open serial ports.  Good example code here.</p>



<h2 class="wp-block-heading">ASCII Table</h2>



<p class="wp-block-paragraph"><a href="http://www.asciitable.com/" target="_blank" rel="noopener">http://www.asciitable.com/</a></p>



<p class="wp-block-paragraph">Having the ASCII Table is quite handy for serial data because data being sent and written are bytes, so being able to know what byte values correspond to what character really helps.</p>



<h2 class="wp-block-heading">Arduino and Java</h2>



<p class="wp-block-paragraph"><a href="http://www.arduino.cc/playground/Interfacing/Java" target="_blank" rel="noopener">http://www.arduino.cc/playground/Interfacing/Java</a></p>



<p class="wp-block-paragraph">This article discusses how to use the serial port communication with Java and Arduino, which is exactly what I am after.&nbsp; It has example code on pretty much the entire process of serial port communication, but it may be too much to read since there is little explanation about the code.</p>



<h2 class="wp-block-heading">Arduino Serial Class</h2>



<p class="wp-block-paragraph"><a href="http://arduino.cc/en/Reference/Serial" target="_blank" rel="noopener">http://arduino.cc/en/Reference/Serial</a></p>



<p class="wp-block-paragraph">A good reference for Arduino’s Serial class methods.&nbsp; Also has example code to look at.</p>



<h2 class="wp-block-heading">Programming Serial and Parallel Ports</h2>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler wp-block-embed-embed-handler"><div class="wp-block-embed__wrapper">
https://docs.google.com/viewer?url=http%3A%2F%2Fjava.sun.com%2Fdeveloper%2FBooks%2Fjavaprogramming%2Fcookbook%2F11.pdf
</div></figure>



<p class="wp-block-paragraph">This article provides a brief introduction to programming serial ports and has information on the steps required to talk to the serial port.&nbsp; However, the code examples in there may be hard to follow for someone new to serial programming.</p>



<h2 class="wp-block-heading">Serial Port Access Using RXTX in Java</h2>



<p class="wp-block-paragraph"><a href="http://gomultidomain.blogspot.com/2008/06/serial-port-access-using-rxtx-in-java.html" target="_blank" rel="noopener">http://gomultidomain.blogspot.com/2008/06/serial-port-access-using-rxtx-in-java.html</a></p>



<p class="wp-block-paragraph">This page also has complete code for serial communication in Java, but what I was looking for here was how to use the write method to send serial data from Java.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.henrypoon.com/blog/2011/01/01/serial-communication-in-java-with-example-program/feed/</wfw:commentRss>
			<slash:comments>144</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">566</post-id>	</item>
	</channel>
</rss>
