Monday, October 27, 2014

Eclipse Cougaar Windows

Got "Hello World Demo" working on Win.

Following tutorial: http://cougaar.org/wp/documentation/tutorials/helloworlddemo/
Source: http://cougaar.org/build/ and http://sourceforge.net/projects/cougaar/

In run configuration set Main class to:
org.cougaar.bootstrap.Bootstrapper

Gotchas are: command line is: C:\Work\hello\run>cougaar -v %COUGAAR_SOCIETY_PATH%/configs/HelloWorldSociety.xml SingleNodeRuntime.xml
Note, misnamed 'hello' xml file.
To get running in Eclipse (without using the mentioned cougaar IDE) use the following Run configuration arguments: -Dorg.cougaar.society.xsl.param.template=single_node -Dorg.cougaar.core.logging.config.filename=logging.props -Dorg.cougaar.bootstrap.application=org.cougaar.core.node.Node -Dorg.cougaar.society.file=C:\Work\hello/configs/HelloWorldSociety.xml -Dorg.cougaar.runtime.file=SingleNodeRuntime.xml -Dorg.cougaar.node.name=Node1 -Dorg.cougaar.runtime.path=${env_var:COUGAAR_RUNTIME_PATH} -Dorg.cougaar.society.path=${env_var:COUGAAR_SOCIETY_PATH} -Dorg.cougaar.install.path=${env_var:COUGAAR_INSTALL_PATH} -Xbootclasspath/p:${env_var:COUGAAR_INSTALL_PATH}/lib/javaiopatch.jar -Dorg.cougaar.core.node.InitializationComponent=XML -Djava.class.path=${env_var:COUGAAR_INSTALL_PATH}/lib/bootstrap.jar

Note use of "env_var" -- these are OS environment variables not to be confused with those set in Eclipse Environment tab (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=170789)

Working directory per instructions is set to ${workspace_loc:hello/run}

Monday, September 22, 2014

FactoryBean Woes

Be careful with org.springframework.beans.factory.FactoryBean. I created a couple of them and used them with something like <bean id="mybean" class="pkg.myfactory" />
Everything seemed to work fine. Then as soon as I added a third and fourth, everything went haywire and started getting no end to circular dependency errors. So I had to switch to plain vanilla "factory-bean" beans in xml and everything was fine then!

Friday, August 29, 2014

Researching Hibernate for Queries

How to perform unions and/or one-to-one joins with multiple intermediate tables? Looks like there are no easy solutions. Best may be using SQL or creating numerous hibernate mappings for a legacy database.

Read:
http://hibernate-samples.blogspot.com/2011/10/one-to-one-association-using-join-table.html
 https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Web_Server/1.0/html/Hibernate_Core_Reference_Guide/assoc-bidirectional-join-121.html
 example of multiple intermediate join tables?
 named query: http://stackoverflow.com/questions/8399379/hibernate-named-query-join-3-tables
 with sql: http://jumpingbean.co.za/blogs/mark/hibernate
 http://stackoverflow.com/questions/18257757/how-to-execute-query-with-union-in-hibernate

Wednesday, July 9, 2014

Bit shift operators

Experimentation in Java Snippet Runner to learn about bit shift operator and binary operators based on http://stackoverflow.com/questions/2534116/how-to-convert-get-rgbx-y-integer-pixel-to-colorr-g-b-a-in-java. >>> shifts all bits to the right with the bits falling off the right and zero filling from the left (as opposed to >> which fills from left based on sign (in this case 1 ... 0xAABBCCDD = -1430532899).


int argb = 0xAABBCCDD;
int r = (argb)&0xFF;
int g = (argb>>8)&0xFF;
int b = (argb>>16)&0xFF;
int a = (argb>>24)&0xFF;
int r_ = (argb)&0xFF;
int g_ = (argb>>8)&0xFF;
int b_ = (argb>>16)&0xFF;
int a_ = (argb>>24)&0xFF;
int r_1 = (argb)&0xFFFFFFFF;
int g_1 = (argb>>8)&0xFFFFFFFF;
int b_1 = (argb>>16)&0xFFFFFFFF;
int a_1 = (argb>>24)&0xFFFFFFFF;
System.out.println(Integer.toBinaryString(argb));
System.out.println(r + " red " + Integer.toBinaryString(r_) + "\n" + Integer.toBinaryString(r_1));
System.out.println(g + " green " + Integer.toBinaryString(g_) + "\n" + Integer.toBinaryString(g_1));
System.out.println(b + " blue " + Integer.toBinaryString(b_) + "\n" + Integer.toBinaryString(b_1));
System.out.println(a + " alpha " + Integer.toBinaryString(a_) + "\n" + Integer.toBinaryString(a_1));
System.out.println("righters");
System.out.println((argb>>8));
System.out.println((argb>>16));
System.out.println((argb>>24));

System.out.println(argb +"color methods");
   java.awt.Color c = new java.awt.Color(argb, true);
    System.out.println("red " + c.getRed());
    System.out.println("green " + c.getGreen());
    System.out.println("blue " + c.getBlue());
    System.out.println("alpha "  + c.getAlpha());

10101010101110111100110011011101
221 red 11011101
10101010101110111100110011011101
204 green 11001100
11111111101010101011101111001100
187 blue 10111011
11111111111111111010101010111011
170 alpha 10101010
11111111111111111111111110101010
righters
-5588020
-21829
-86
-1430532899color methods
red 187
green 204
blue 221
alpha 170

OK

Sunday, May 11, 2014

Send JMS Message

Followed the youtube Message Driven Bean EJB Glassfish Netbeans
I noticed that at the part where you Alt-Ins, "Send JMS Message..." and select "Message Driven Bean" the MBean I created did not show up.
I am using Glassfish 4/Netbeans 8, and evidently the "mappedName" was not added when creating the Message Driven Bean using the wizard. Had to add it to make it show in the dropdown. I submitted a bug report on this https://netbeans.org/bugzilla/show_bug.cgi?id=244428.
Also noticed that NetBeans 8 didn't generate the same code from the above wizard either. I manually rewrote the code per the youtube and it worked, because the generated code (the @JMSConnectionFactory injection, the abbreviated sendJMSMessageToDest method using only context.createProducer().send(..), while a noble effort by someone to be in-with-the-times simply did not work as promised, and at this time it's not my priority to find out why...)

Saturday, April 26, 2014

JSF CRUD Tutorial

Following instructions at https://netbeans.org/kb/docs/web/jsf20-crud.html
at end of "Creating the Web Application Project" was curious so in Libraries - GlassFish Server 4, expanded javax.servlet.jsp.jstl.jar - org.apache.taglibs.standard.tag.common.xml - ParseSupport.class it opened a generated source file. I noticed the button "Attach Sources"
I then used https://blogs.oracle.com/geertjan/entry/how_to_set_up_glassfish1 as a guide to download the sources. I did Team - Subversion -Checkout - Repository URL: https://svn.java.net/svn/jstl~svn and downloaded to a new folder java.net-src\jstl in the NetBeans projects folder. Then I clicked the "Attach Sources..." button and added the folder %USERPROFILE%\Documents\NetBeansProjects\java.net-src\jstl\javax.servlet.jsp.jstl-1.2.1\src\main\java.
Going back to the .class files under the javax.servlet.jsp.jstl.jar file I am now able to double-click one and see the source.

Wednesday, April 23, 2014

Standalone JAX-WS Lab

This question made me curious: http://stackoverflow.com/questions/5166269/what-happens-when-a-java-class-is-annotated-webservice?rq=1

Thus I created the standalone server per: http://stackoverflow.com/questions/1792737/in-process-soap-service-server-for-java

basically set up the .java files per the answer and do:

C:\Work\Testing\java\webservices\standalone_ws>mkdir buildsvc

C:\Work\Testing\java\webservices\standalone_ws>javac -d buildsvc helloservice/endpoint/*java

C:\Work\Testing\java\webservices\standalone_ws>java -cp buildsvc helloservice.endpoint.Server
Starting Server
Server ready...

Then, create a client:

package simpleclient;

import helloservice.endpoint.*;
import javax.xml.ws.WebServiceRef;
import javax.xml.namespace.QName;

public class HelloClient {
  @WebServiceRef(wsdlLocation="http://localhost:9000/SoapContext/SoapPort?WSDL")
  static HelloService service;

  public static void main(String[] args) {
    try {
      HelloClient client = new HelloClient();
      client.doTest(args);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void doTest(String[] args) {
    try {
QName qname = new QName("http://endpoint.helloservice/", "HelloService");
HelloService service = new HelloService(null, qname);
      System.out.println("Retrieving the port from the following service: " + service);
      Hello port = service.getHelloPort();
      System.out.println("Invoking the sayHello operation    on the port.");

      String name;
      if (args.length > 0) {
        name = args[0];
      } else {
        name = "No Name";
      }

      String response = port.sayHello(name);
      System.out.println(response);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

Test:

mkdir build
wsimport -d build -keep -verbose http://localhost:9000/SoapContext/SoapPort?WSDL
javac -cp build simpleclient/HelloClient.java
java -cp build;. simpleclient.HelloClient bah

Then to make things interesting and to see the full stack trace to see how the WebService annotation is processed on the server or at least for clues, change the sayHello method:

  public String sayHello(String name) {
    return message + name + "." + (1/(1-1));
  }

to throw an ArithmeticException. Redo above steps and see the stacktrace coming from the cmd window for the running server:

Starting Server
Server ready...
Apr 23, 2014 10:42:41 PM com.sun.xml.internal.ws.server.sei.TieHandler createResponse
SEVERE: / by zero
java.lang.ArithmeticException: / by zero
        at helloservice.endpoint.Hello.sayHello(Hello.java:12)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sun.reflect.misc.Trampoline.invoke(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.sun.xml.internal.ws.api.server.MethodUtil.invoke(Unknown Source)
        at com.sun.xml.internal.ws.api.server.InstanceResolver$1.invoke(Unknown Source)
        at com.sun.xml.internal.ws.server.InvokerTube$2.invoke(Unknown Source)
        at com.sun.xml.internal.ws.server.sei.SEIInvokerTube.processRequest(Unknown Source)
        at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Unknown Source)
        at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Unknown Source)
        at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Unknown Source)
        at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Unknown Source)
        at com.sun.xml.internal.ws.server.WSEndpointImpl$2.process(Unknown Source)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter$HttpToolkit.handle(Unknown Source)
        at com.sun.xml.internal.ws.transport.http.HttpAdapter.handle(Unknown Source)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handleExchange(Unknown Source)
        at com.sun.xml.internal.ws.transport.http.server.WSHttpHandler.handle(Unknown Source)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
        at sun.net.httpserver.AuthFilter.doFilter(Unknown Source)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
        at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(Unknown Source)
        at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
        at sun.net.httpserver.ServerImpl$Exchange.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)


From there you can go look up these methods on grepcode for OpenJDK and see what's actually happening.



Tuesday, April 22, 2014

JAX-RS Labs

doing http://www.vogella.com/tutorials/REST/article.html

To view HTTP headers in Fiddler, add to vm arguments of run configuration

-DproxyHost=localhost
-DproxyPort=8888

then restart fiddler

Discovered that Jersey 1.x is deprecated in favor of Jersey 2 which uses Moxy instead of Jackson. The catch is that the latter don't play well with Tomcat, so I'll be abandoning tutorials on JAX-RS prior to 2011, and sticking to Glassfish.

Tuesday, April 8, 2014

Spring MVC Labs

http://saltnlight5.blogspot.com/2013/10/getting-started-with-annotation-based.html  -- gives an example of how to take advantage of Servlet 3/Tomcat 7 web.xml-free setup. To boot also shows how to use the http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/usage.html Tomcat 7 Maven plugin.
Alls I did was create a new Maven project in Eclipse Kepler EE version, naming the groupId mvcmvnsprng and the artifact id mvcmvn. Then created a source folder under Java Resources named "javasrc" in which I put the mentioned packages and java files. Also updated the pom.xml and right click project and click Validate. I suppose you could also Maven, download sources or just wait for it happen automatically. index.jsp was already there with hello world in it. then I changed to cmd to root folder of project containing the pom.xml and typed: mvn org.apache.tomcat.maven:tomcat7-maven-plugin:run
That downloaded the tomcat plugin and started the web server! Loading localhost:8080/mvcmvn/ I could see "Hello World!" it was that easy.
Also did the follow up which showed how to connect the same to embedded H2 database via jdbctemplate http://java.dzone.com/articles/getting-started-spring-jdbc

The next step was to add logging. Taking hints from several tutorials I ended up just right-clicking the project and choosing maven add dependency twice. Once by typing commons-logging and choosing 1.1.1. Then for log4j by typing "log4j" and choosing 1.2.17. It added a "bundle" element which cause errors so I deleted it. Then I added the log4j.properties copied from http://www.beingjavaguys.com/2013/05/logging-in-spring-framework-using-log4j_8.html  to src/main/resources (so its in root of a classpath). That was it. Didn't need to use Logger.getLogger or import org.apache.log4j.Logger because apparently it's plugged in automatically via spring and appache commons logging. So the LOG.info command in PingService.java worked; it outputed the message in the logingFile.log and to the batch output.

Word of caution: Don't even think of doing Spring MVC in JBoss. All indicators are that Spring was built with Tomcat in mind, JBoss was built with JEE in mind, and never the twain should cross paths (unless you want to spend all-nighters trying to fit a square peg (Spring MVC 3) in a round hole (JBoss 7) like I just did.

Saturday, April 5, 2014

JBoss EJB Lab

Followed: http://www.26miles.com/26miles/downloads/JBoss%205.0.1.GA/Simple%20Web%20Application%20using%20JBoss%20and%20Eclipse.doc

and http://www.26miles.com/26miles/downloads/JBoss%205.0.1.GA/Simple%20EJB%202.1%20Application%20using%20JBoss%20and%20Eclipse.doc
 in that order.

Used jboss-4.2.2.GA instead. and set up SimpleStandAloneClient per doc.

Once "SimpleSession" was working, copied target JAR to server\default\deploy

Changed string in context.lookup to match target ejb jndi (note if there's a jboss.xml in the jar as there was in this case, check it for actual jndi-name to use instead of ejb-name from ejb-jar.xml). Change properties passed to InitialContext as well.

Target's ejb-jar.xml contained an assembly-descriptor so need to configure security in client app.

Add:             System.setSecurityManager(new RMISecurityManager());
to top of of main right after opening of try block.

Instead of adding the credentials to the properties, use SecurityAssociation as follows (inserted before InitialContext context = new InitialContext(properties)

SecurityAssociation.setPrincipal(new SimplePrincipal("user"));
SecurityAssociation.setCredential("password");

Add roles.properties and user.properties files to server\default\conf containing security-role name corresponding to target ejb/method from ejb-jar.xml.

will need to execute it like java -Djava.security.policy=client.policy SimpleStandAloneClient
with client.policy containing e.g., for all permissions (ok only for lab):
grant {
permission java.security.AllPermission;
};


add server\default\deploy\oracle-ds.xml with security-domain info (see https://community.jboss.org/wiki/EncryptingDataSourcePasswords)
modify server\default\conf\login-config.xml
add ojdbc5.jar to server\default\lib

Sunday, March 23, 2014

JTA Tutorial

Following http://www.javacodegeeks.com/2013/07/spring-jta-multiple-resource-transactions-in-tomcat-with-atomikos-example.html

Installed MySQL and manually created the two databases/tables
When importing downloaded maven project to Eclipse Kepler (JEE) got error. Resolved using http://qussay.com/2013/09/13/solving-dynamic-web-module-3-0-requires-java-1-6-or-newer-in-maven-projects/ (need to right click project and do Maven Update Project.) Note: I also checked "Dynamic Web Module" under Project Facets

Added a run configuration with goal "package" per "Cimbom" - http://stackoverflow.com/questions/9665569/where-did-eclipses-run-as-maven-package-go - need to ensure JRE tab is set to JRE of 1.7 (or else get error: "javac: invalid flag: -s" --probably cuz I had workbench default JRE set to 1.5 duh.)
Ran it it produced springexample.war in target folder root.

Click Servers tab and add Tomcat 7, selected it and click start button. That loads the webapp but doesn't create a springexample under Apache not sure why. would need to start Apache manually (from bin dir) and copy the above war file to webapps.
Load localhost:8080/springexample/appServlet and confirm get "Both employees are inserted!" Verify items are added in MySQL Workbench. Test Rollback scenario per article.


Sunday, March 9, 2014

Tomcat OpenShift Projects

Create new Maven Project in Eclipse
On "Select an Archetype" screen, for filter type "webapp"
select "maven-archetype-webapp" under Artifact Id
Enter a group-id and artifact Id and click finish
Delete the project from Eclipse (but not from hard drive)
open command prompt and go to root of new project (where resides pom.xml)
enter: mvn eclipse:eclipse -Dwtpversion=2.0
Import project into eclipse (kepler java EE)
Open Project properties
under Project Facets change java version to match the system (i.e. 1.7)
Add a Tomcat Server to Eclipse
Under Server Locations ensure "use Tomcat installation" is checked
Set Server path to tomcat server e.g. c:\apache-tomcat-7.0.52
Set Deploy path to C:\apps\apache-tomcat-7.0.52\webapps
Open Modules tab and click Add Web Module
Choose the new project and click ok
Expand Servers and Tomcat v7.0 Server
open file tomcat-users.xml
Add to tomcat-users element:

 <role rolename="manager-gui"/>

<role rolename="admin-gui"/>
<user username="admin" password="admin" roles="admin-gui,manager-gui"/> 

click Debug - Tomcat v7.0 Server at localhost
Open localhost:8080 in the browser
click Manager App (and enter credentials)
scroll to your new web app and click it to show your site

Deploy to OpenShift
in command prompt in openshift app dir (with .openshift, deployments, src, etc.) enter:
 git rm -r src/
in xplorer2, select the src folder of the Eclipse maven project in the left pane and in the right pane have the openshift app dir
click copy to, when prompted allow to merge src.
back in cmd, enter 'git add .' then 'git commit -m "blah"' then git push
Load it in the browser e.g. http://jbossas-<your namespace>.rhcloud.com/<warName>/index.jsp
Now you can modify the eclipse project, e.g. add a main.jsp etc (see http://awgtek.blogspot.com/2014/03/deploy-small-java-app-to-openshift.html) and after each test in local tomcat do another Deploy to OpenShift.

Deploy Struts app to OpenShift? No problem. Set up StrutsExample per http://www.mkyong.com/struts/struts-hello-world-example/
follow same instructions as "Deploy to OpenShift" above, i.e. git delete src and copy src folder from the Struts eclipse tested app. THEN make a change to the pom.xml that exists in the openshift app dir copying over the two dependency elements from StrutsExample for org.apache.struts. git add/commit/push. OpenShift will download the dependencies per the maven pom.xml.