Monday, September 25, 2006

UTF4.0 defines U+FFFF Java String

Counting char Units

private String testString = "abcd\u5B66\uD800\uDF30";
int charCount = testString.length();
System.out.printf("char count: %d\n", charCount);

The length method counts the number of char values in a String object. The sample code prints this:

char count: 7

Counting Character Units

When Unicode version 4.0 defined a significant number of new characters above U+FFFF, the 16-bit char type could no longer represent all characters. Starting with the Java 2 Platform, Standard Edition 5.0 (J2SE 5.0), the Java platform began to support the new Unicode characters as pairs of 16-bit char values called a surrogate pair.

This special use of 16-bit units is called UTF-16, and the Java Platform uses UTF-16 to represent Unicode characters. The char type is now a UTF-16 code unit, not necessarily a complete Unicode character (code point).

private String testString = "abcd\u5B66\uD800\uDF30";
int charCount = testString.length();
int characterCount = testString.codePointCount(0, charCount);
System.out.printf("character count: %d\n", characterCount);

This example prints this:

character count: 6 The Japanese character has Unicode code point U+5B66, which has the same hexadecimal char value \u5B66. The Gothic letter's code point is U+10330. In UTF-16, the Gothic letter is the surrogate pair \uD800\uDF30.

Counting Bytes

byte[] utf8 = null;
int byteCount = 0;
try {
utf8 = str.getBytes("UTF-8");
byteCount = utf8.length;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
System.out.printf("UTF-8 Byte Count: %d\n", byteCount);

The target character set determines how many bytes are generated. The UTF-8 encoding transforms a single Unicode code point into one to four 8-bit code units (a byte). The characters a, b, c, and d require a total of only four bytes. The Japanese character turns into three bytes. The Gothic letter takes four bytes. The total result is shown here:

UTF-8 Byte Count: 11


Tony

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

Be A Developer That Uses AI

Developers will not be replaced by AI, they'll be replaced by developers that use AI. Generative AI tools are revolutionizing the way de...