MattPayne.org

Omaha, NE – Computer Programmer

Archive for the 'Java' Category

All things in the universe of java programming and programming that uses the JVM.

Scala

Posted by Payne on 18th July 2009

All the buzz about Scala in the popular press has gotten my attention. Hopefully, Scala will not disappoint.

From InfoQ: Roundup: Scala as the long term replacement for Java

“Scala has been receiving much attention lately as a possible candidate to replace Java in the future. James Strachan creator of Groovy advocates in favor of Scala as James Gosling, creator of Java and Charles Nutter JRuby Core Developer, have done in the past.”

Things I’m looking through include:

  1. Learning Scala
  2. Programming Scala from Ora.com seems to be online in HTML for free (for now)
  3. Ted Neward’s Busy Developers Guide to Scala series on Developerworks
  4. Scala By Example
  5. Scala on Google App Engine

I’m considering buying the book on Scala — Programming in Scala

Posted in Scala | No Comments »

JVM is the new UNIX

Posted by Payne on 13th February 2007

The Java Virtual Machine is the new UNIX. This has been happening for quite sometime and I’ve been rambling about it for a while. This post will expand upon the idea….. someday.

Posted in Java | No Comments »

JSch is easy to use!

Posted by Payne on 17th September 2006

JSch is a pure Java implementation of SSH2.” It’s great that the license is BSD style.

This package is easy to use and comes with some nice demo programs. I was able to quickly adapt their SSH tunnels demo so that before starting the real main in a jMatter.org application (which was being launched via Java Web Start) a SSH tunnel was established. Then the jMatter.org application makes a database connection to 127.0.0.1 which really goes through the SSH tunnel to the UNIX box with the database server on it. This way the database server’s TCP socket doesn’t have to be directly exposed to the Internet.

Still to do is tweaking things so each end user has a unique tunnel… maybe with ssh keys…

BTW It’s interesting that the top page returned by googling SSH tunnel is http://www.rzg.mpg.de/networking/tunnelling.html. There’s a nice picture there:

Posted in Crypto, Java, SSH, jMatter | No Comments »

VisualComplexity.com

Posted by Payne on 25th June 2006

I started listening to Manuel Lima’s
ITconversations.com podcast about his website
VisualComplexity.com where he collects different projects for Mapping Complex Networks.

Very interesting stuff! Reminds me that I want to learn the java side of Piccolo Toolkit.

Posted in Java, Semantic Web | No Comments »

XMLEncoder and XMLDecoder Reminder

Posted by Payne on 25th June 2006

 1  // From old blog post http://tinyurl.com/lo88j
 2  import java.beans.*;
 3  import java.io.*;
 4  /**
 5   * This shows that with J2SE 1.4.x's built in XMLEncoder class it's 
 6   * easy to serialize javabeans (POJOs) to XML files.
 7   * @see SimpleBean
 8   * 
 9   * Experiment based on 
10   * http://java.sun.com/products/jfc/tsc/articles/persistence4/index.html
11   * and 
12   * http://www-106.ibm.com/developerworks/java/library/j-mer0731/index.html
13   * 
14   * Running this program creates test.xml:
15   * 
16  <?xml version="1.0" encoding="UTF-8"?>
17  <java version="1.4.2_01" class="java.beans.XMLDecoder">
18   <object class="SimpleBean">
19    <void property="age">
20     <int>99</int>
21    </void>
22    <void property="favorites">
23     <void method="add">
24      <string>Red</string>
25     </void>
26     <void method="add">
27      <string>Green</string>
28     </void>
29     <void method="add">
30      <string>Blue</string>
31     </void>
32    </void>
33    <void property="name">
34     <string>Testing</string>
35    </void>
36   </object>
37  </java>
38   * 
39   * 
40   * 
41   */
42  public class XMLEncoderDemo {
43
44          public static void main(String[] args) {
45                  try {
46                          new XMLEncoderDemo().run(args);
47                          System.out.println("Normal termination.");
48                  } catch (Exception bland) {
49                          bland.printStackTrace();
50                  }
51          }//main()
52
53          public void run(String[] args) throws Exception {
54                  XMLEncoder e;
55
56                  SimpleBean foo = new SimpleBean();
57                  foo.setAge(99);
58                  foo.setName("Testing");
59                  foo.addFavorite("Red");
60                  foo.addFavorite("Green");
61                  foo.addFavorite("Blue");
62                  /* If SimpleBean is not a public class, this generates:
63  java.lang.IllegalAccessException: Class java.beans.Statement can not access a member of class SimpleBean with modifiers "public"
64  Continuing ...
65  java.lang.Exception: discarding statement XMLEncoder0.writeObject(SimpleBean0);
66  Continuing ...
67                   */
68                  e = new XMLEncoder(
69                                          new BufferedOutputStream(
70                                                  new FileOutputStream("test.xml")));
71                  e.writeObject(foo);
72                  e.close();
73          }//run()
74  }

And here’s the simple javabean data container…

 1  import java.util.ArrayList;
 2  import java.util.List;
 3
 4  public class SimpleBean {
 5          private int age;
 6          private String name;
 7          private List favorite;
 8
 9          public SimpleBean() {
10                  age=0;
11                  name="";
12                  favorite=new ArrayList();
13          }
14
15          public int getAge() {
16                  return age;
17          }
18          public void setAge(int age) {
19                  this.age = age;
20          }
21          public List getFavorite() {
22                  return favorite;
23          }
24          public void setFavorite(List favorite) {
25                  this.favorite = favorite;
26          }
27          public String getName() {
28                  return name;
29          }
30          public void setName(String name) {
31                  this.name = name;
32          }
33          public void addFavorite(Object arg1) {
34                  favorite.add(arg1);
35          }
36  }

Posted in Java | No Comments »

No Doubt! Apache’s XML Security will encrypt subtrees!

Posted by Payne on 23rd June 2006

Original post 10 May 2004. TODO: Still need to update the before and
after samples…

It was easy to hack the org.apache.xml.security.samples.encryption.Encrypter
demo to show that just a subtree of a document could be encrypted….
before
after

  1  /*
  2   * Copyright  1999-2004 The Apache Software Foundation.
  3   *
  4   *  Licensed under the Apache License, Version 2.0 (the "License");
  5   *  you may not use this file except in compliance with the License.
  6   *  You may obtain a copy of the License at
  7   *
  8   *      http://www.apache.org/licenses/LICENSE-2.0
  9   *
 10   *  Unless required by applicable law or agreed to in writing, software
 11   *  distributed under the License is distributed on an "AS IS" BASIS,
 12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13   *  See the License for the specific language governing permissions and
 14   *  limitations under the License.
 15   *
 16   */
 17  package org.apache.xml.security.samples.encryption;
 18
 19
 20  import java.io.File;
 21  import java.io.FileInputStream;
 22  import java.io.FileOutputStream;
 23
 24  import java.security.Key;
 25
 26  import javax.crypto.SecretKey;
 27  import javax.crypto.KeyGenerator;
 28
 29  import org.apache.xml.security.keys.KeyInfo;
 30  import org.apache.xml.security.encryption.XMLCipher;
 31  import org.apache.xml.security.encryption.EncryptedData;
 32  import org.apache.xml.security.encryption.EncryptedKey;
 33  import org.apache.xml.security.utils.XMLUtils;
 34  import org.apache.xml.security.utils.Constants;
 35
 36  import org.w3c.dom.Document;
 37  import org.w3c.dom.Element;
 38  import org.w3c.dom.NodeList;
 39
 40  import javax.xml.transform.TransformerFactory;
 41  import javax.xml.transform.Transformer;
 42  import javax.xml.transform.dom.DOMSource;
 43  import javax.xml.transform.stream.StreamResult;
 44  import javax.xml.transform.OutputKeys;
 45
 46  /**
 47   * This sample demonstrates how to encrypt data inside an xml document.
 48   *
 49   * @author Vishal Mahajan (Sun Microsystems)
 50   * Hacked by Matt
 51   */
 52  public class Encrypter2 {
 53
 54      /** {@link org.apache.commons.logging} logging facility */
 55      static org.apache.commons.logging.Log log =
 56          org.apache.commons.logging.LogFactory.getLog(
 57              Encrypter2.class.getName());
 58
 59      static {
 60          org.apache.xml.security.Init.init();
 61      }
 62
 63      private static Document createSampleDocument() throws Exception {
 64
 65          javax.xml.parsers.DocumentBuilderFactory dbf =
 66              javax.xml.parsers.DocumentBuilderFactory.newInstance();
 67          dbf.setNamespaceAware(true);
 68          javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
 69          Document document = db.newDocument();
 70
 71          /**
 72           * Build a sample document. It will look something like:
 73           *
 74           * <apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1">
 75           * <apache:foo>Some simple text</apache:foo>
 76           * </apache:RootElement>
 77           */
 78          Element root =
 79              document.createElementNS(
 80                  "http://www.apache.org/ns/#app1", "apache:RootElement");
 81          root.setAttributeNS(
 82              Constants.NamespaceSpecNS,
 83              "xmlns:apache",
 84              "http://www.apache.org/ns/#app1");
 85          document.appendChild(root);
 86
 87          root.appendChild(document.createTextNode("\n"));
 88
 89          Element childElement =
 90              document.createElementNS(
 91                  "http://www.apache.org/ns/#app1", "apache:foo");
 92          childElement.appendChild(
 93              document.createTextNode("Some simple text"));
 94
 95          Element e2 = document.createElementNS(
 96                  "http://www.apache.org/ns/#app1", "apache:goo");
 97                  e2.appendChild(document.createTextNode("Weather Report"));
 98
 99                  Element e3 = document.createElementNS(
100                  "http://www.apache.org/ns/#app1", "apache:bar");
101                  e3.appendChild(document.createTextNode("No Doubt"));
102
103                  e2.appendChild(e3);
104
105                  e2.appendChild( e3.appendChild(document.createTextNode("biteme")));
106
107          childElement.appendChild(e2);
108
109
110          root.appendChild(childElement);
111
112          root.appendChild(document.createTextNode("\n"));
113
114
115          outputDocToFile(document, "before2.xml");
116
117          return document;
118      }
119
120      private static SecretKey GenerateAndStoreKeyEncryptionKey()
121          throws Exception {
122
123          String jceAlgorithmName = "DESede";
124          KeyGenerator keyGenerator =
125              KeyGenerator.getInstance(jceAlgorithmName);
126          SecretKey kek = keyGenerator.generateKey();
127
128          byte[] keyBytes = kek.getEncoded();
129          File kekFile = new File("kek");
130          FileOutputStream f = new FileOutputStream(kekFile);
131          f.write(keyBytes);
132          f.close();
133          System.out.println(
134              "Key encryption key stored in " + kekFile.toURL().toString());
135
136          return kek;
137      }
138
139      private static SecretKey GenerateDataEncryptionKey() throws Exception {
140
141          String jceAlgorithmName = "AES";
142          KeyGenerator keyGenerator =
143              KeyGenerator.getInstance(jceAlgorithmName);
144          keyGenerator.init(128);
145          return keyGenerator.generateKey();
146      }
147
148      private static void outputDocToFile(Document doc, String fileName)
149          throws Exception {
150          File encryptionFile = new File(fileName);
151          FileOutputStream f = new FileOutputStream(encryptionFile);
152
153          TransformerFactory factory = TransformerFactory.newInstance();
154          Transformer transformer = factory.newTransformer();
155          transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
156          DOMSource source = new DOMSource(doc);
157          StreamResult result = new StreamResult(f);
158          transformer.transform(source, result);
159
160          f.close();
161          System.out.println(
162              "Wrote document containing encrypted data to " +
163              encryptionFile.toURL().toString());
164      }
165
166      public static void main(String unused[]) throws Exception {
167
168          Document document = createSampleDocument();
169
170          /*
171           * Get a key to be used for encrypting the element.
172           * Here we are generating an AES key.
173           */
174          Key symmetricKey = GenerateDataEncryptionKey();
175
176          /*
177           * Get a key to be used for encrypting the symmetric key.
178           * Here we are generating a DESede key.
179           */
180          Key kek = GenerateAndStoreKeyEncryptionKey();
181
182          String algorithmURI = XMLCipher.TRIPLEDES_KeyWrap;
183
184          XMLCipher keyCipher =
185              XMLCipher.getInstance(algorithmURI);
186          keyCipher.init(XMLCipher.WRAP_MODE, kek);
187          EncryptedKey encryptedKey =
188              keyCipher.encryptKey(document, symmetricKey);
189
190          /*
191           * Let us encrypt the contents of the document element.
192           */
193          Element rootElement = document.getDocumentElement();
194          NodeList node =  rootElement.getElementsByTagName("apache:bar");
195          rootElement = (Element) node.item(0);
196          System.out.println("node="+node);
197         // rootElement = (Element)
198                  System.out.println("rootElement="+rootElement);
199          //rootElement = (Element) rootElement.getFirstChild().getFirstChild();
200
201          algorithmURI = XMLCipher.AES_128;
202
203          XMLCipher xmlCipher =
204              XMLCipher.getInstance(algorithmURI);
205          xmlCipher.init(XMLCipher.ENCRYPT_MODE, symmetricKey);
206
207          /*
208           * Setting keyinfo inside the encrypted data being prepared.
209           */
210          EncryptedData encryptedData = xmlCipher.getEncryptedData();
211          KeyInfo keyInfo = new KeyInfo(document);
212          keyInfo.add(encryptedKey);
213          encryptedData.setKeyInfo(keyInfo);
214
215          /*
216           * doFinal -
217           * "true" below indicates that we want to encrypt element's content
218           * and not the element itself. Also, the doFinal method would
219           * modify the document by replacing the EncrypteData element
220           * for the data to be encrypted.
221           */
222          xmlCipher.doFinal(document, rootElement, true);
223
224          /*
225           * Output the document containing the encrypted information into
226           * a file.
227           */
228          outputDocToFile(document, "encryptedInfo2.xml");
229      }
230  }

Posted in Crypto, Java | No Comments »

implementors plugin for eclipse

Posted by Payne on 20th June 2006

Many thanks to Matt Secoske for telling about the implementors plugin for eclipse!

Now when “coding to the interface” I no longer have to be frustrated by not being able to easily walk my code in eclipse!

From http://eclipse-tools.sourceforge.net/implementors/usage.html:

Activating the Open Implementation action is done by pressing Alt+F3 in the Java editor (this shortcut may be customized in the preferences.) The plugin may also be activated in the editor’s context menu (the name of the action is “Open Implementation”.)

If the cursor is located on a method name, Eclipse jumps to the implementing method(s). If the cursor is located on a an interface type (either the type itself or an instance), Eclipse jumps to the implementing type(s).

If no matching classes are found, a message is shown in the status line.

Posted in eclipse | No Comments »

javadocbook utility

Posted by Payne on 8th June 2006

https://sourceforge.net/projects/javadocbook/ looks nice!

java -jar javadocbook.jar -t HTML hw.xml > hw.html
changes some docbook into some HTML. It’s nice because it’s so self contained…

http://mattpayne.org/db/hw.xml is some input taken from this tutorial. Results in the output http://mattpayne.org/db/hw.html

Maven2 understands simplified docbook. Maybe the javadocbook utility can be handy for someone using maven2 for their projects?

Posted in Java, XML | 1 Comment »