Thursday, August 31, 2006

Programming MSMQ in .NET

Programming MSMQ in .NET

The System.Messaging namespace provides a set of classes which can be used to work with MSMQ. In this article we will be mainly focusing on Message and MessageQueue classes. The MessageQueue class provides all the necessary functionality to work with and manipulate MSMQ queues. It is like a wrapper around message queuing. The Message class provides everything required to define and use an MSMQ message.

Try

Dim queueAsMessageQueue

queue = MessageQueue.Create(".\Private$\MyNewQueue")

' If there is an error creating a queue you get a MessageQueueException exception

Catch ex As MessageQueueException

End Try

MyQueue.Send("<<Message>>", "<<Message Label>>")


Dim msg As Message

msg = MyQueue.Receive()

MessageBox.Show(msg.Body)


MyQueue.Delete(".\Private$\MyNewQueue")


Message could be lost or duplicated. Thats why we need to create the transactional message queue.

queue = MessageQueue.Create(".\Private$\TranQueueA ", TRUE)

Dim mqTran As New MessageQueueTransaction()

Dim queueA As New MessageQueue()

queueA.Path = ".\Private$\TranQueueA"

Dim queueB As New MessageQueue()

queueB.Path = ".\Private$\TranQueueB"

mqTran.Begin()

Try

queueA.Send("Message A", "Label A", mqTran)

queueB.Send("Message B", "Label B", mqTran)

mqTran.Commit()

Catch ex As Exception

mqTran.Abort()

Finally

queueA.Close()

queueB.Close()

End Try


The Send and Receive methods of the MessageQueue class also expose overloads which takes a parameter of type MessageQueueTransactionType which is an enumeration of certain values. This basically specifies how you would like to interact with the queue (transactionally). We have not used it thus far, but is important to understand why and where this is used.

The enumeration contains three values:

Single

You might often come across situations where you want to have each queue operation in a separate internal transaction. That is, you may not want to use MessageQueueTransaction object to qualify each MSMQ operation. In such cases you can use the Single option. Here's an example:

Dim queueA As New MessageQueue()

queueA.Path = ".\Private$\TranQueueA"

queueA.Send("Single internal transactional message A", "Label A", _

MessageQueueTransactionType.Single)

queueA.Close()

Understand that, to send a message to a transactional queue, you have to be in a transaction (internal or external), else an error will be thrown.

None

Using this option enables us to receive a message from a transactional queue, but outside a transaction. We can also use this option to send a transactional message to a non transactional queue.

Automatic

This option is used in conjunction with external transactions. This directs the send or receive operation to use an already existing transaction context created by COM+, MTS etc. This is shown in the next section.

Tony

Wednesday, August 16, 2006

i18n and l10n

i18n stands for Internationalization. There are 18 characters between the i and n. Internationalization includes locale and languages. Some good practices include use API to get data format. Program Files might be different in German windows. Leave text out of image. Some images might mean different in different culture, e.g. thumbs up. Unicode is always good for internationalization.

l10n stands for localization. There are 10 characters between l and n. l10n is to get anything localizable out of programs.

i18n and l10n are backend process. It is good for adapt agile process into it and innovate the internationalize process. Pseudo-localized message could be added in order to test the i18n. A very good tool to localize Win32 program/dll is called Alchemy Catalyst Localizer 6.0. .Net frameworks does a decent job in terms of localization. Usually it will look for business.resource.dll for the business.dll.

POC = Person of Contact

Tony

Thursday, August 10, 2006

JDK 6.0 new features

Client (Desktop) Core Enterprise

2D - GIF image writer JSR 223: Scripting for the Java Platform JSR 250: Common annotations
AWT
- Access to Desktop helper applications
- Fast splash screens
- Improved modal dialogs
- System-tray support
Debug
- Access to heap contents
- Attach-on-demand
- Multiple simultaneous agents
JDBC
-
JSR 221: JDBC 4.0
Internationalization
- Pluggable locale data
- Resource-bundle enhancements
- Unicode string norm
alization
Libs
- Array reallocation
- Collections: Deques
- Collections: Sorted sets and maps with bidirectional navigation
- Critical file-I/O enhancements
- Floating point: Add core IEEE 754 recommended functions
-
java.util.concurrent updates
JSR 202: Java Class-File Specification Update
- Password prompting
- Reflective access to parameter names
- Service-provider lookup
XML
- JavaBeans Activation Framework (JAF) 1.1
-
JSR 173: Streaming API for XML (StAX)
-
JSR 181: Web Services Metadata
-
JSR 222: Java Architecture for XML Binding (JAXB) 2.0
-
JSR 224: Java API for XML Web Services (JAX-WS) 2.0
Swing
- Baseline/gap APIs
- Improve Swing drag-and-drop
-
JTabbedPane: Tabs as components
-
JTable sorting, filtering, and highlighting
-
SwingWorker
- Text-component printing
Management & Monitoring
- Generalized lock monitoring
- Generalized MBean descriptors
- Generic annotations for MBean descriptor contents
- MXBeans

Net
- Internationalized domain names
- Internationalized resource identifiers
- Programmatic access to network parameters
- Simple HTTP cookie manager

Security
-
JSR 105: XML Digital-Signature APIs
Tools
-
JSR 199: Java Compiler API
-
JSR 269: Pluggable Annotation-Processing API
Tony

Embedded Jetty Server and Enhanced Jetty Security

Jetty is an open-source, standards-based, full-featured web server implemented entirely in java. It is released under the Apache 2.0 licence and is therefore free for commercial use and distribution. It is a pretty good for embedded the server into any other java enabled product.

Hereunder are some points to enhance the Jetty server security.

Suppress the server version header

By default, the Jetty server includes some version information in it's response headers:

HTTP/1.1 200 OK

Date: Wed, 31 Mar 2004 03:46:50 GMT

Content-Type: text/html;charset=ISO-8859-1

Server: Jetty/4.2.7 (SunOS/5.8 sparc java/1.4.1_03)

...

<snip>

While this is not itself a security risk, some organisations would rather not give out such detailed information. To suppress this header, the system property org.mortbay.http.Version.paranoid needs to be set to true:

java -Dorg.mortbay.http.Version.paranoid=true ...


Hide the jetty config file

We could move the jetty config file into the jar file and read the config file from Jar file. How to access from jar file has some choices:

Choice 1: "jar:file:../lib/Ardmore.jar!/com/avocent/amt/ardmore/serverconfig.xml"

Resource configurationResource = Resource.newResource(System.getProperty( SERVER_CONFIG_XML, DEFAULT_CONFIGURATION_LOCATION));

server = new Server(configurationResource);

Choice 2: InputStream resourceAsStream = this.getClass().getResourceAsStream("/com/avocent/amt/core/server-config.wsdd");

Make web application read only

We could war the web application folders.

<target name="war.single.war" depends="">

<war warfile="${singlewar.webapp.root}/${deploy.webapp.name}.war" webxml="${singlewar.webapp.dir}/WEB-INF/web.xml">

<fileset dir="${singlewar.webapp.dir}" />

          <manifest>

          <attribute name="CSS-Server-Version" value="${product.version}"/>

          <attribute name="Build-Number" value="${build.number}"/>

          </manifest>

</war>

<copy todir="${release.base.dir}">

<fileset dir="${singlewar.webapp.root}">

<include name="*.war" />

</fileset>

</copy>

</target>

Remove context list

SOLUTION:

          Add the “/” root context and return and intercept the call and dont return.

          HttpContext context = server.addContext("/");

          context.addHandler(new AMSGNotFoundHandler());

Suppress Powered by Jetty button

Customize the jetty 404 error message. Same as above

Aliases and Symbolic Links

Jetty by defaults runs in a mode where all file accesses are checked for aliases, such as case insensitivity, short names, symbolic links and extra characters (Eg %00). If a resource is an alias, then it is treated as not found.

Alias requests are a security problem because webapplication security constraints are applied with case sensitive URL patterns. For example, if a security constraint is place on a /mySecretFolder/* and alias checking was not implemented then on a win32 system the following requests could retrieve files from that URL:

o /MySeCrEtFoLdEr/secret.html
o /mysec~a0.dir/secret.html
o /mySecretFolder/secret.html%00

File name aliases come in many forms including case insensitivity, VMS version numbers, Unix symbolic links, 8.3 short names, etc. While some of these aliases (eg symbolic links) are deliberate, there is no general way to tell this in portable 100% java.

Jetty detects aliases by comparing the files absolutePath with its canonicalPath. If the JVM reports these as different an alias is assumed and the resource treated as not found.

SOLUTION:

Alias checking can be turned off by setting the system parameter org.mortbay.util.FileResource.checkAliases to false (see jetty.xml for an example of how to do this in XML configuration). If alias checking is not used, then greater care is needed when designing security constraints. It is recomended that a restrictive constraint be applied to a whole subtree of URL space and then selective constraints be applied to relax security only for specific URLs.


REFERENCES:

http://jetty.mortbay.org/jetty/faq/

http://jetty.mortbay.org/jetty/tut/HttpServer.html


Tony

Generate JDK compatible certificate from OPEN SSL

Our shop is using SSL/TLS a lot. We generate the home made certificate a lot. OpenSSL is much powerful to generate the certificate than simply use Java key certificate tool.

OPEN SSL STEPS

Download open ssl 0.9.8.a

1. CREATE A KEY

openssl genrsa -des3 1024 > c:\temp\server.key

2. create request

openssl req -new -key c:\temp\server.key -x509 -days 730 -out c:\temp\server.crt -extensions v3_ca

Country Name:CAf

Province:Alberta

Locality:Calgary

Organization Name:Xyz Corporation

Organization Unit Name:BOB

Common Name:Gandalf.xyz.com

email:gandalf@xyz.com

3. convert to Java key store

openssl pkcs12 -inkey c:\temp\server.key -in c:\temp\server.crt -export -out c:\temp\jetty.pkcs12

4. convert to a java keystore format

set JETTY_HOME=C:\Program Files\ArdmoreServer\lib

java -classpath "%JETTY_HOME%/org.mortbay.jetty.jar" org.mortbay.util.PKCS12Import jetty.pkcs12 c:\temp\BOBkeystore

5. listing the certificates

keytool -list -keystore BOBkeystore

6. obfuscate a password

java -cp "%JETTY_HOME%/commons-logging.jar;%JETTY_HOME%/org.mortbay.jetty.jar" org.mortbay.util.Password Xyz


CN=www.verisign.com, O=VeriSign, C=US, S=California, L=Mountain View


Tony

TestNG 5.0 Release

Test NG is replacement for JUnit. Super strong and support Eclipse as well. But our shop is using JUnit. So I dont have much time to investigate it.

http://testng.org/doc/

Tony

Java EE XML handling

Java EE provides various technology choices for handling XML documents. Three of these technologies are Java Architecture for XML Binding (JAXB), Streaming API for XML (StAX), and the Document Object Model (DOM) API. This Tech Tip compares these choices, and shows the technologies in use in a sample application.

JAXB

JAXB technology provides a way to bind XML schemas to Java objects so that developers can easily process data in their Java applications. The JAXB API provide methods to unmarshal an XML document into a Java object and marshal a Java object into an XML document. For more information about JAXB, see the Tech Tip What's New in JAXB 2.0.

A significant advantage of using JAXB is that you can compile the schema (or dtd) to generate a Java content tree, and then work with plain Java objects. JAXB is not particularly good in cases where complex schemas are involved and you want to work with only a small set of content.

StAX

StAX is a streaming API for processing XML documents. It's an event-driven, "pull" parser that reads and writes XML documents. For more information about StAX, see the Tech Tip Introducing the Sun Java Streaming XML Parser.

StAX's bidirectional features, small memory footprint, and low processor requirements give it an advantage over APIs such as JAXB or DOM. StAX is particularly effective in extracting a small set of information from a large document. The primary drawback in using StAX is that you get a narrow view of the document -- essentially you have to know what processing you will do before reading the XML document. Another drawback is that StAX is difficult to use if you return XML documents that follow complex schema.

DOM

DOM is platform-neutral and language-neutral API that enables programs to dynamically update the contents of XML documents. For more information about DOM, see the Tech Tip Using the Document Object Model.

DOM creates an in-memory object representation of an entire XML document. This allows extreme flexibility in parsing, navigating, and updating the contents of a document. DOM's drawbacks are high memory requirements and the need for more powerful processing capabilities.


http://java.sun.com/developer/EJTechTips/2006/tt0527.html#2

Tony

Wednesday, August 09, 2006

jMock

This is a really cool open source java testing packages which works very well with JUnit. For a simple example we are going to test a publish/subscribe message system. A Publisher sends objects to zero or more Subscribers. We want to test the Publisher

import org.jmock.*;

class PublisherTest extends MockObjectTestCase {

public void testOneSubscriberReceivesAMessage() {

// set up

Publisher publisher = new Publisher();

Mock mockSubscriber = mock(Subscriber.class);

publisher.add((Subscriber) mockSubscriber.proxy());

// expectations Next we define expectations on the mock Subscriber that specify the methods that we expect to be called upon it during the test run.

final String message = "message";

mockSubscriber.expects(once()).method("receive").with( eq(message) );

publisher.publish(message);

}

}

We expect the receive method to be called with a single argument, the message that will be sent. The eq method is defined in the MockObjectTestCase class and specifies a "constraint1" on the value of the argument passed to the subscriber: we expect the argument to be the equal to the message, but not necessarily the same object. (jMock provides several constraint types1 that can be used to precisely specify expected argument values). We don't need to specify what will be returned from the receive method because it has a void return type.

http://www.jmock.org/

Tony

Thursday, August 03, 2006

Apache Commons-Email 1.0

Commons-Email aims to provide a API for sending email. It is built on top of the Java Mail API, which it aims to simplify.

Some of the mail classes that are provided are as follows:

·         SimpleEmail - This class is used to send basic text based emails.

·         MultiPartEmail - This class is used to send multipart messages. This allows a text message with attachments either inline or attached.

·         HtmlEmail - This class is used to send HTML formatted emails. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added. It also supports embedded images.

·         EmailAttachment - This is a simple container class to allow for easy handling of attachments. It is for use with instances of MultiPartEmail and HtmlEmail.

 

http://jakarta.apache.org/commons/email/



Tony

 

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...