AWG Blogs

Tuesday, March 20, 2018

Create keypair for Tomcat SSL and import same to Java keystore

Create the keypair:
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -keystore tomcat-keystore.jks -validity 730

Export the certificate:
keytool -export -alias tomcat -file tomcat-keystore.cer -keystore tomcat-keystore.jks

Import to Java keystore:
keytool -import -alias tomcat -file tomcat-keystore.cer -keystore C:\jdk1.7.0_51\jre\lib\security\cacerts

Add it to Tomcat's server.xml:

    <Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
disableUploadTimeout="true" enableLookups="false" maxThreads="25"
    port="8443" keystoreFile="/path/to/tomcat-keystore.jks" keystorePass="password"
    protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
    secure="true" sslProtocol="TLS" />

Now you can avoid errors in java programs like:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed...

References:
https://dzone.com/articles/setting-ssl-tomcat-5-minutes
https://stackoverflow.com/a/7812567/1714485

Wednesday, May 31, 2017

Creating a multi-column constraint where one column has nulls

To create a multi-column unique constraint on a table where the new column will have nulls initially
need to ensure that the index associated with the unique constraint is non-unique. This can be done
using 'DEFERRABLE' in the constraint command or by creating a non-unique index first and
referring to it with a USING INDEX __ in the constraint command:

select name from v$database;

Alter table MYSCHEMA.MY_TABLE add MY_COLUMN  varchar2(250);

comment on column MY_TABLE.MY_COLUMN is 'a column description';

ALTER TABLE MYSCHEMA.MY_TABLE ADD CONSTRAINT XYZ1_MY_TABLE UNIQUE (ANOTHER_COLUMN, MY_COLUMN) DEFERRABLE NOVALIDATE;

commit;

-- ROLLBACK
(paste the below rollback commands in sql developer worksheet run as script and click commit)
ALTER TABLE MYSCHEMA.MY_TABLE DROP CONSTRAINT XYZ1_MY_TABLE;

Alter table MYSCHEMA.MY_TABLE drop column MY_COLUMN;

--verify column, constraint and associated index is deleted:
select index_name,index_type, uniqueness, visibility from dba_indexes where table_name='MY_TABLE' order by index_name;

select * from dba_constraints where table_name='MY_TABLE';


Sunday, April 23, 2017

Git rebase interactive to move feature to release

The scenario was similar to http://stackoverflow.com/questions/6594881/git-merge-only-the-changes-made-on-the-branch?noredirect=1&lq=1
where dev/master was in the middle, getting merged into continuously be various teams and their feature branches. Periodically a release branch is created and devs are stuck with the dilemma of having to merge a feature branch into both dev and release.

          A release1
         /
    D---E---F---G development
            \
             H---I---J feature_for_release1

So, as a proof of concept what I have done is show how feature_for_release1 could be attached onto release1 without including F.

I first created a staging branch off release1:

 MINGW64 /c/Work/testing/my_try_git (release1)
$ git checkout -b stage-release1-feature
Switched to a new branch 'stage-release1-feature'

Then merged in feature-for-release1:
 git merge feature-for-release1

At this point I printed the log and did a rebase interactive:
 MINGW64 /c/Work/testing/my_try_git (stage-release1-feature)
$  git log --pretty=oneline --graph
* 14b50fed8999aa785e7333a239b532c3f1fe11e0 file added for release1
* b6a8a66b8bd64de49b666d0e627e68de76747ac4 files changed for release1
*   e3ee2edbbfbb2ef629170309d5e35cad6181f4d6 Merge pull request #1 from awgtek/feature-for-release2
|\
| * cd091e9f75d8580c34c9a73c0f30aef616816a7f adding changes for release 2
|/
* eb95ed7111130064272be69957644223212d9981 Remove 322
* fde83b085873139a22cef07f069b46e98eeb0fe9 asdflkasjf;dsak
* 7a5797b379afca819f1e5a92bc122e41bbed52ab add all the octa t filesfrom2
* 05d0d336001842e6b4fec2206e6616363b8d9dbe adding redoctober
* 485cdfcd1fdcd5106518a9f19406a1243c91c555 add all the octocat txt files
* 81d5a2cb15e40752c8bf7aba7ffde6728ebfbdb6 add cute octaot story

MINGW64 /c/Work/testing/my_try_git (stage-release1-feature)
$ git rebase -i  eb95ed7111130064272be69957644223212d9981
In the editor was shown:

As can be seen, I am rebasing to eb95ed which corresponds to point E on the above diagram. I am also dropping cd091e9 from the replaying of this sequence of commits (top to bottom) onto the staging branch which is being rebased to the point just before eb95ed.

When I saved the file, it got an error:

error: could not apply b6a8a66... files changed for release1

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
Could not apply b6a8a66b8bd64de49b666d0e627e68de76747ac4... files changed for release1

This was because one of the files committed in the dropped commit was also changed in a subsequent kept commit. So I had to edit the offending file remove all the merge conflicts, do a git add, and a git rebase --continue. After which the rebase was completed.

 MINGW64 /c/Work/testing/my_try_git (stage-release1-feature)
$  git log --pretty=oneline --graph
* 752d1871b4e8632a1daf8fe7579884f08dfa0b17 file added for release1
* faa4e3ba142bc00015bdba7c2988e02319cbfaab files changed for release1
* eb95ed7111130064272be69957644223212d9981 Remove 322
* fde83b085873139a22cef07f069b46e98eeb0fe9 asdflkasjf;dsak
* 7a5797b379afca819f1e5a92bc122e41bbed52ab add all the octa t filesfrom2
* 05d0d336001842e6b4fec2206e6616363b8d9dbe adding redoctober
* 485cdfcd1fdcd5106518a9f19406a1243c91c555 add all the octocat txt files
* 81d5a2cb15e40752c8bf7aba7ffde6728ebfbdb6 add cute octaot story

I could  then push stage-release1-feature to github and merge it into release. see here.

Saturday, July 23, 2016

Enabling Debugging in Eclipse for Tomcat Installation

When using the option "Use Tomcat installation (takes control of Tomcat installation), to enable debugging from Eclipse, you may need to adjust the VM arguments of the launch configuration as follows:

Double click the Tomcat server in the Servers tab, then click "Open launch configuration"
In the Arguments tab append the following line to the VM arguments text box:
 -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n

Then restart the server.

Here is a screenshot:

Saturday, March 5, 2016

Two-way authentication with Tomcat

Start by creating a private key, cert, and keystore using openssl then convert to jks using Java's keytool so it can be used in Tomcat:
MyOwnPC+Joe@MyOwnPC ~/temp
$ openssl req -new -x509 -key serverprivatekey.pem -out servercert.pem -days 1095
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:.
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:myownpc
Email Address []:.

MyOwnPC+Joe@MyOwnPC ~/temp
$ ls
servercert.pem  serverprivatekey.pem

MyOwnPC+Joe@MyOwnPC ~/temp
$ openssl pkcs12 -export -out serverkeystore.pkcs12 -in servercert.pem -inkey serverprivatekey.pem -name myownpc -passout pass:changeit

MyOwnPC+Joe@MyOwnPC ~/temp
$ ls
servercert.pem  serverkeystore.pkcs12  serverprivatekey.pem

MyOwnPC+Joe@MyOwnPC ~/temp
$ keytool -importkeystore -alias myownpc -srckeystore serverkeystore.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS
Enter destination keystore password:  changeit
Re-enter new password: changeit
Enter source keystore password:  changeit

MyOwnPC+Joe@MyOwnPC ~/temp
$ ls
keystore.jks  servercert.pem  serverkeystore.pkcs12  serverprivatekey.pem

MyOwnPC+Joe@MyOwnPC ~/temp
$ cp keystore.jks ../certs
Add (or modify) so that Tomcat's conf/server.xml contains reference to the new keystore:
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
        keystoreFile="C:/cygwin64/home/Joe/certs/keystore.jks" keystorePass="changeit"
               clientAuth="false" sslProtocol="TLS" />
Restart Tomcat. Then browse to https://myownpc:8443/someapp. Accept the certificate browser warnings and verify that the presented certificate's details contains 'myownpc' as the 'issued for'. Also you can check using the following keytool command to ensure 'myownpc' is an alias for the imported cert: keytool -list -v -keystore keystore.jks Now create a client certificate and add it to the keystore used by tomcat:

MyOwnPC+Joe@MyOwnPC ~/temp
$ openssl genrsa -out clientprivatekey.pem 2048                                 Generating RSA private key, 2048 bit long modulus
.......................+++
.............+++
e is 65537 (0x10001)

MyOwnPC+Joe@MyOwnPC ~/temp
$ openssl req -new -x509 -key clientprivatekey.pem -out clientcert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:.
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:.
Organization Name (eg, company) [Internet Widgits Pty Ltd]:.
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:joe
Email Address []:.

MyOwnPC+Joe@MyOwnPC ~/temp
$ ls
clientcert.pem        keystore.jks    serverkeystore.pkcs12
clientprivatekey.pem  servercert.pem  serverprivatekey.pem

MyOwnPC+Joe@MyOwnPC ~/temp
$ openssl pkcs12 -export -out clientkeystore.pkcs12 -in clientcert.pem -inkey clientprivatekey.pem -name joe -passout pass:changeit

MyOwnPC+Joe@MyOwnPC ~/temp
$ keytool -importkeystore -alias joe -srckeystore clientkeystore.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS
Enter destination keystore password:  changeit
Enter source keystore password:  changeit

MyOwnPC+Joe@MyOwnPC ~/temp
$ ls
clientcert.pem         keystore.jks           serverprivatekey.pem
clientkeystore.pkcs12  servercert.pem
clientprivatekey.pem   serverkeystore.pkcs12

MyOwnPC+Joe@MyOwnPC ~/temp
$ cp keystore.jks ../certs
Now modify the server.xml SSL connector, adding keyAlias, truststoreFile, and truststorePass attributes and set clientAuth to true:
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
        keystoreFile="C:/cygwin64/home/Joe/certs/keystore.jks" keystorePass="changeit"
               clientAuth="true" sslProtocol="TLS"
  keyAlias="myownpc" truststoreFile="C:/cygwin64/home/Joe/certs/keystore.jks"
  truststorePass="changeit"
 />
Restart Tomcat. Now loading the https page will give an error like
An error occurred during a connection to myownpc:8443. SSL peer cannot verify your certificate. (Error code: ssl_error_bad_cert_alert) 
So in Firefox, do Options, Advanced, View Certificates, Import and import the file clientkeystore.pkcs12 and enter the password when prompted. Try loading the page again and Firefox should present you with the option to use the certificate you imported; accept and load the page.

Refs: http://venkateshragi.blogspot.com/2013/04/two-way-ssl-authentication-on-tomcat.html main flow here. Correction, the truststoreFile was actually required for me.
http://www.cloudera.com/documentation/enterprise/5-3-x/topics/cm_sg_openssl_jks.html found correction to above blog, adding -name option to openssl exports.

Saturday, February 21, 2015

Eclipse Classpath Run Configurations being overwritten

Encountered a strange issue with eclipse (both Luna and Mars) on certain run configurations. What happened was when launching I would almost immediately (after some messages from loading classes) get "Error: Could not find or load [name of the class]" or in some other run configuration a java.lang.ClassNotFoundException and then a stack trace.

This would happen despite cleaning the project, recreating the run configuration, or running eclipse  with the -clean option. The project depended on another project to which I traced the unfound class. This told me that it was a classpath issue; however, the project was clearly listed in the Classpath tab of the run configuration. I even tried exporting the project to a jar and adding it to the local client project build path but that didn't work either.

I then decided to examine the running JVM process. I ran JConsole, attached to the failing process and opened the VM Summary tab. There were a huge number of VM arguments which I scrolled through to get to the Class path entry. The Class path entry had only one entry in it, a single jar file used by the application. There should have been more entries though. I then created a new run configuration using the reverse-engineered items from the output of wmic to get the full command line (see http://serverfault.com/questions/323795/display-complete-command-line-including-arguments-for-windows-process). I tried obtaining it from Process Explorer via save but it truncated it because it was very long I guess. The reverse configured run configuration also produced the same errors.

The I did a search for the single jar file that was assigned to the classpath in the long command line figuring it had to be set there somehow. Sure enough it was being assigned via the -Djava.class.path vm argument. Since the jar was already being loaded via the build path I removed the java.class.path argument -- and that resolved the error. Apparently, adding that argument was causing Eclipse to ignore the Classpath as shown in the Classpath tab of the run configuration. This would only happen though using that particular set of VM arguments. If I only added a few VM arguments in addition to the java.class.path argument Eclipse would run the config and no errors would result. Interestingly JConsole would show only the VM arguments other than java.class.path so apparently Eclipse cleans it up, perhaps recognizing whether the entry is needed or already is reflected in the run configuration classpath (update: this seems to indicate java.class.path is not settable; and I wasn't able to prove otherwise, i.e that it was settable, when using test projects and configurations with classpath tweaking by removing the default classpath and adding my own under "User entries").

My guess regarding the error is that the replacing of the run configuration classpath with the value added to java.class.path vm argument is due to either 1) the vm argument list I was using was too long or 2) the vm argument list was corrupted somehow. This cause would be in addition to an existing eclipse state -- most likely the state of the plugins installed. The reason why is that some eclipse installations worked given the same set of vm arguments and all else being equal while other eclipse installations failed. It did so happen that when I uninstalled one custom plugin that did custom run configurations and reinstalled an earlier version of the plugin this solved the issue. However repeating the steps did not solve the issue on other eclipse installations so I could not pinpoint it to the plugin. It therefore must be a combination of plugin installation or absence of and the above faulty set of vm arguments containing the java.class.path entry...


refs:
http://www.javahotchocolate.com/tutorials/bad-output-folder.html

Friday, February 13, 2015

Creating a sequence diagram from a stack trace

Install AmaterasUML:
- download AmaterasUML from http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=AmaterasUML
- unzip AmaterasUML_1.3.4.zip
- copy the three jars to eclipse plugin folder, e.g. D:\App\eclipse-jee-luna-R-win32-x86_64\eclipse\plugins
- install Graphical Editing Framework eclipse plugin. It was already installed in mine, maybe through a dependency on BPMN2 Modeler or something else.
- restart eclipse
Get the stack trace
- in Eclipse put a breakpoint in some method you want to analyze via sequence diagram
- start debug 
- in the debug view right-click the Daemon Thread and click Copy Stack
- paste into text editor
Fix up stack trace
- remove unwanted lines including lines that end with "line: 1" or start with "Daemon Thread" or "owns:" leaving only the lines that start with entities to be added to the sequence diagram
- save the file e.g. D:\work\AmaterasPrepWork\MyStackTrace.txt
- create a second text file and paste into it the following awk script:
{
str = $0;\
sub(/^\t/, "", str);\
sub(/\(.*\./,".",str);\
sub(/\$.*\./,".",str);\
match(str, /(.*)\./, arr);\
sub(/^/, "at ", str);\
#print str;\
sub(/\([^\)]*\)/, "(", str);\
sub(/ line: /, arr[1]".java:", str);\
sub(/$/, ")", str);\
sub(/\t\)$/, ")", str);\
print str}
- save the file as e.g. D:\work\AmaterasPrepWork\AmaterasPrepProg.txt
- download gawk and run file e.g. gawk-3.1.6-1-setup.exe
- open a command prompt and cd to e.g. D:\work\AmaterasPrepWork
- execute the following commands:
D:\AmaterasPrepWork>set path=%path%;D:\Program Files (x86)\GnuWin32\bin
D:\AmaterasPrepWork>echo awk -f AmaterasPrepProg.txt MyStackTrace.txt ^> out.txt > run.bat
D:\AmaterasPrepWork>run.bat
Make sequence diagram in eclipse
- Do Window, Show View, AmaterasUML, Stack Trace Sample, OK
- paste the contents of D:\AmaterasPrepWork\out.txt into the window
- click the 'i' (image of lower case 'i') button in upper right-hand corner of the Stack Trace Sample view
- select a folder in your project as the destination of new sequence
- refresh the folder in eclipse
- open sequence.sqd
- do finishing touches. It appears e.g. that some entities weren't added and need to be added?? will check on this...
- save the file as MySequence.sqd or save sequence.sqd and refactor to another name because AmaterasUML uses sequence.sqd as the target file name evidently.


ref:

Sunday, November 2, 2014

Solving Sruts2 Core Jar File Conflict

I was adding a Struts2 application to an embedded Tomcat 6 instance by adding the context and assigning the path to the Struts2 application programmatically. The Struts2 application's WEB-INF/lib was empty similar to what's known as a "skinny war." When attempting to access a jsp page though I would get the error: "/struts-tags" not found.

This was solved by adding struts2-core-2.3.4.1.jar to the WEB-INF/lib. However then application would not load and I would get:
Bean type class com.opensymphony.xwork2.ObjectFactory with the name xwork has already been loaded by bean - jar:file:C:/MyCustomContainer/plugins/struts2-core-2.3.4.1.jar!/struts-default.xml:29:72 - bean - jar:file:/D:/temp/configs/pings/strutssd/WEB-INF/lib/struts2-core-2.3.4.1.jar!/struts-default.xml:29:72

So I removed struts2-core-2.3.4.1.jar from the plugins dir leaving only the copy in the WEB-INF/lib. This fixed the problem and the Struts2 application finally worked.

Note this could cause problems if I were to add another Struts2 application to the container although I haven't tried it.

Related problems with workarounds including removing struts-tags.tld and putting in WEB-INF, or adding Class-Path entries  to MANIFEST.MF:
http://stackoverflow.com/questions/19380836/skinny-war-libraries-in-ear-struts-tags-not-found-error
http://stackoverflow.com/questions/6339323/file-struts-tags-not-found-in-struts-1-3
http://stackoverflow.com/questions/19666413/what-is-the-right-way-to-package-struts2-jar-files
http://docs.codehaus.org/display/MAVENUSER/Solving+the+Skinny+Wars+problem

Saturday, March 8, 2014

Deploy Small Java App to OpenShift

This is the code deploy method. For deploying an existing WAR there are other methods will plenty of how-tos on the web.

- Create a JBoss Application Server 7 app preferably from the rhc client.
- Create a file TestBean.java under src\main\java\action and paste in the sample TestBean class from this tutorial on JSP actions: http://www.tutorialspoint.com/jsp/jsp_actions.htm
- Create a folder "classes" under src\main\webapp\WEB-INF (although I'm not sure this step is necessary)
- Create a file "main.jsp" under src\main\webapp and paste in the corresponding sample code from the above referenced tutorial
- Git add, commit, and push it up.
- Load it in the browser e.g. http://jbossas-<your namespace>.rhcloud.com/main.jsp

see also: http://awgjournal.blogspot.com/2014/03/tomcat-openshift-projects.html

Saturday, November 30, 2013

Create empty file with bcp

I wasn't sure if multiple statements (using semicolon as delimiter) could be passed to bcp, so I tried it, specifically prepending a DECLARE statement and it worked, in this case for creating an empty file:
DECLARE @FilePath VARCHAR(1000)
DECLARE @FileExists int
DECLARE @nulltable TABLE ( foo integer)
SET @FilePath = 'C:\my\path\somefile.csv'

exec master.dbo.xp_fileexist @FilePath, @FileExists OUTPUT
if not @FileExists = 1 
begin
declare @bcpCommand varchar(255), @Result int
set @bcpCommand = 'bcp "DECLARE @nulltable TABLE ( foo integer); Select * from @nulltable" queryout "' + @FilePath + '" -c -t, -T -S '
exec @Result = master..xp_cmdshell @bcpCommand  --, no_output
end

Wednesday, August 7, 2013

Get Value of Form Element

I had names to compare only (as they are generated from DB). I needed the value regardless of element type; most would try to detect type then get the value.

For now I will settle on a one liner expression, and see how it goes in testing:

 $("input[name='NameOfElement']:checked").val() || document['formName']['NameOfElement'].value || false

This should handle radio buttons and checkboxes first (if checked), then selects and inputs, then false. My use case doesn't require comparing values of textareas or multiselects, so I am not accounting for them for now.
Note: I found the above to cause "Do you want to continue running scripts on this page?" messages on old clients, namely IE 7 or 8 on single core Windows XP PCs. So I was forced to replace the above jQuery-reliant code with the following more verbose pure JavaScript:
if ( ! ( (document['Form1']['ItemFoo'].length && document['Form1']['ItemFoo'][0].type=="radio" && myGetSelectedRadioValueByName('ItemFoo')=="Yes") || (!document['Form1']['ItemFoo'].disabled && document['Form1']['ItemFoo'].type=="checkbox" && document['Form1']['ItemFoo'].checked==true && document['Form1']['ItemFoo'].value == "Yes") || (!document['Form1']['ItemFoo'].disabled && document['Form1']['ItemFoo'].type!="checkbox" && document['Form1']['ItemFoo'].value == "Yes"))){ var elems = document.getElementsByName('TargetShowHideElement'); for (var i = 0; i < elems.length; i++) { elems[i].disabled= false; } }


A side note about the above: It is a work in progress; the language-specific expressions are generated from a DSL (a table of variables and corresponding conditions), in a manner similar to a suggestion by "Doc Brown" at http://programmers.stackexchange.com/questions/182025/creating-huge-decision-tree

Friday, June 21, 2013

Disabling Siblings of Selected Radio Button

I couldn't find a "contains" selector that applied to html elements, hence the following hack less elegent (more verbose than it should be) method that functionally and stylistically disables all li containers that don't contain the radio button that's selected:
var enableOnlySelectedListItem = function(parentId, radioItemName) {
     $('#' + parentId + ' input:radio[name=' + radioItemName + ']')
         .on('click', null,"",function (event) {
            $(this).closest('ul')
                .find('input[name=' + radioItemName + ']')
                .not(this)
                .parent()
                .find(':input')
                .not('input[name=' + radioItemName + ']')
                .prop('disabled', true)
            .end()
            .end()
            .addClass('disabledtext');    
                
            $(this).closest('li')
                .find(':input')
                .prop('disabled', false)
            .end()
            .removeClass('disabledtext');    
                
             event.stopPropagation();
     });
};

Sunday, May 19, 2013

Installing Stunnel on CenOS 5

Download tar.gz file from http://www.stunnel.org/downloads.html?extra=/source.html
to ~/temp
did: 
gzip -dc stunnel-4.56.tar.gz | tar xvf -
cd stunnel-4.56
./configure
make
make install

vi /usr/local/etc/stunnel/stunnel.conf-sample
add the line
fips = no
change cert = line to read
cert = /usr/local/etc/stunnel/stunnel.pem
adjust service section, e.g. for forwarding smtp securely

cp /usr/local/etc/stunnel/stunnel.conf-sample /etc/stunnel/stunnel.conf
cp /etc/stunnel/stunnel.conf /usr/local/etc/stunnel/stunnel.conf
#this last one to satisfy stunnel from cmd line, the prior for the service
#perhaps should make them hard linked

cp /usr/local/share/doc/stunnel/examples/stunnel.init /etc/init.d/stunnel
cd /etc/init.d
chmod 755 stunnel

vi stunnel
modify top of file to read:
#! /bin/sh -e
# description: stunnel Start Stop Restart
# processname: stunnel
# chkconfig: 234 20 80

then in startdeamons() change the install line to read:
install -d -o nobody -g nobody /var/run/stunnel

save file
do:
echo "ENABLED=1" > /etc/default/stunnel

Disable sendmail
chkconfig sendmail off; service sendmail stop

Enable stunnel
chkconfig --add stunnel
In case tests are running:
pkill stunnel 
service stunnel start

References:


Sunday, May 5, 2013

Using vb2js

This is one of the only tools I've found to automatically convert VBA files to .js files. YMMV.

- Download via svn. see https://code.google.com/p/vb2js/source/checkout

- Download Guava (currently guava-14.0.1.jar)  - https://code.google.com/p/guava-libraries/; place downloaded file in 'src' folder of vb2js download

- Open a text editor and insert this code
package com.google.vb2js;
import java.util.*;
import java.io.*;

public class MyVbaJsConverter {
  public static void main(String[] args) throws FileNotFoundException, IOException {
    if (args.length == 2) {
   String entireFileText = new Scanner(new File(args[0]))
  .useDelimiter("\\A").next();
   FileWriter fstream = new FileWriter(args[1]);
   BufferedWriter out = new BufferedWriter(fstream);
   out.write(VbaJsConverter.convert(entireFileText));
   out.close();

    }
  }
}
- Save the file as "MyVbaJsConverter.java" in the same directory as the unpacked vb2js java files (e.g. in D:\temp\vb2js-read-only\src\com\google\vb2js) - Create a text file with the following content. Save it as ...\src\testInput.bas
Dim MyList As String
Dim MyNum As Integer
- Make sure JDK is installed and JDK bin folder is in path environment variable - Open a command prompt and change to src folder. - Execute the following commands:
d:\temp\vb2js-read-only\src>javac -cp guava-14.0.1.jar com\google\vb2js\*.java
D:\temp\vb2js-read-only\src>java -cp .;guava-14.0.1.jar com.google.vb2js.MyVbaJsConverter testInput.bas testOutput.js
- Open testOutput.js and verify that VBA was converted.

refs: http://abhinandanmk.blogspot.com/2012/05/java-how-to-read-complete-text-file.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

Thursday, April 18, 2013

Tomcat Hello World Servlet

Here's a no-IDE quick-start how-to. Create the following directories:

c:\users\John Smith\Documents\scratch\helloTomcat\src
c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF

open NotePad++ and create the following two files.

c:\users\John Smith\Documents\scratch\helloTomcat\dist\WEB-INF\web.xml

<!DOCTYPE web-app PUBLIC
  '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
  'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
  <servlet>
    <servlet-name>mihello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>mihello</servlet-name>
    <url-pattern>/mihello</url-pattern>
  </servlet-mapping>
</web-app>
c:\users\John Smith\Documents\scratch\helloTomcat\src\HelloServlet.java
import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
  public void doGet (HttpServletRequest req,
                                         HttpServletResponse res)
        throws ServletException, IOException
  {
        PrintWriter out = res.getWriter();
        out.println("Hello, You!");
        out.close();
  }
}
Open a command prompt
C:\Users\John Smith\Documents\scratch\helloTomcat\src>javac -cp "C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar" HelloServlet.java
C:\Users\John Smith\Documents\scratch\helloTomcat\src>mkdir ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>copy *.class ..\dist\WEB-INF\classes
C:\Users\John Smith\Documents\scratch\helloTomcat\src>cd ..\dist
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>jar cvf web-arc-test.war
Open a command prompt as Administrator
C:\Users\John Smith\Documents\scratch\helloTomcat\dist>copy web-arc-test.war "C
:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps"
open browser and browse to http://localhost:8085/web-arc-test/mihello
Note: change port to whatever tomcat is running on.
Refs:
http://keyboardsamurais.de/2004/01/15/tomcat_tutorial_helloworld_for_complete_fools_-_english/
http://stackoverflow.com/questions/7924687/compiling-a-simple-hello-world-servlet-into-a-war-for-tomcat
http://www.avajava.com/tutorials/lessons/how-do-i-create-a-war-file-using-the-jar-command.html

Friday, April 5, 2013

Get Property by an Attribute Property Value using LINQ

//look up the attribute matching the listid using Reflection and LINQ
                Type dtoType = typeof(AppInitParamsDTO);
                PropertyInfo pi = dtoType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                            .Where(
                            x => typeof(AppInitParamsSettingsListNameAttribute)
                                .GetProperty("ListName")
                                .GetValue(Attribute.GetCustomAttribute(
x, typeof(AppInitParamsSettingsListNameAttribute)), null).ToString()
                                == listId).First();

Tuesday, March 26, 2013

JSONSelect Usage

For the simple use case of verifying the existence of a "record" in a JavaScript object, you typically need to iterate through all items. There is a one-liner approach though, thankfully.

Say you want to verify that an ID exists in
 "Body": {
  "GetListCollectionResponse": {
   "GetListCollectionResult": {
    "Lists": {
     "List": [
      {
       "ID": "{B8B000CC-EB90-4B3D-9A44-79B8A9CFCAAC}",
       "RequireCheckout": "False",
       "EnableMinorVersion": "False",
...
Verify existence with the following function:
ListExists = function(listGuid) { //search spsvcListColXmlJson for match
  var arr = JSONSelect.match(":has(:root > .ID:val(\""+listGuid+"\"))", 
   spsvcListColXmlJson.Body.GetListCollectionResponse.GetListCollectionResult.Lists);
  var retval = arr.length>0;
  return retval; 
 };
Test:
test('List Guid found in Lists collection', function() {
 ok(ListExists("{B8B000CC-EB90-4B3D-9A44-79B8A9CFCAAC}"),"list should exist");
});

Thursday, February 28, 2013

DB Access Account error when Adding WFE

If you get this error when attempting to add a WFE to a farm:

"SharePoint Products and Technologies Configuration Wizard"
"The username entered must be the same as the database access account for the server farm you wish to join. Either choose NT AUTHORITY\NETWORK SERVICE as the username or choose a different database name"

try changing the user account used for the Timer service and Central Admin app pool. Supposedly this is the account specified at installation AKA server farm account or AKA Database Access Account (as in the error message).

Confusing, I know.

This does the trick:

stsadm -o updatefarmcredentials -userlogin -password

iisreset /noforce

 http://technet.microsoft.com/en-us/library/cc288991(v=office.12).aspx

Note: you may also need to enable the SQL Server Browser service on the CA server.

Friday, February 15, 2013

Bind ViewModel Declaratively with Caliburn.Micro in Non-Caliburn.Micro App

I have an existing Silverlight App with Frame based navigation and the app is fairly stable. I wanted to look into logging interception of ViewModels and that is when I started testing Caliburn.Micro (per an answer to my question here). My aim is to gradually migrate pages over to the Caliburn.Micro framework, but not have CM take over the App at first (i.e. set the RootVisual). The closes discussion on the web I could find regarding this scenario was http://caliburnmicro.codeplex.com/discussions/260738. To do a proof-of-concept I simply combined the files from the Caliburn.Micro.ViewFirst sample project with a SL Nav template project:

- Create a new "Silverlight Navigation Application" project
-Add existing files from ViewFirst sample: IShell.cs, MefBootstrapper.cs, and ShellViewModel.cs (change namespaces if desired)
- Add necessary references to MEF and Caliburn.Micro
- In MefBootstrapper, remove the OnStartup override method, since we are not setting the rootvisual, but instead letting the App.xaml do that. Note I thought it was necessary to also override the constructor and set "base(false)" but it seems to work either way, so I left it out.
- Copy the StackPanel element and its content from ShellView.xaml into the ContentStackPanel of About.xaml
- For the declarative binding of VM, also add the following also to About.xaml:     cal:Bind.Model="Shell"  xmlns:cal="http://www.caliburnproject.org"
- At the top of the App constructor of App.xaml.cs add:             new MefBootstrapper();
- Press F5, click "About" and notice that you have a working Caliburn.Micro ViewModel View with Actions all wired up automatically!

Monday, February 11, 2013

IsolatedStorageException - "Initialization Failed"

I got this IsolatedStorageException - message: "Initialization Failed" - when using Enterprise Library. The line giving the error is in StorageAccessor.Silverlight.cs
            this.store = IsolatedStorageFile.GetUserStoreForApplication();
I've gotten this error before in other circumstances, and usually occur right after I delete the Isolated Storage for a particular URL and reopen the app.

Tried rebooting, recompiling, reinstalling Silverlight runtime. Finally what worked was deleting this folder: C:\Users\User.Name\AppData\LocalLow\Microsoft\Silverlight

Apparently there is some corrupted state left over in there. I also noted that around this time I was unable to delete other app stores.