Developer Notes

Practical notes, advises on application development (java, seam, android, google api)

Conifgure JBoss mail-service for SMTP over SSL

Posted by Andrey Chorniy on December 15, 2009

I always have troubles with sending email-messages from my application which I host locally.
The issue is that my ISP provider SMTP works only via SSL. I was able to setup Outlook to work with it and since ISP use not trusted certificate I was asked to confirm that that certificate is trusted.
So, actually (going ahead) we have two problems

  1. Configure /deploy/mail-service.xml to use correct port and other SSL parameters
  2. Add ISP certificate into the java keystore (since the certificate is not trusted)

So, after couple of experiments and googling I find that following combination of parameters work for me

<server>
    <mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
        <attribute name="JNDIName">java:/Mail</attribute>
        <attribute name="User">${username}</attribute>
        <attribute name="Password">${password}</attribute>

        <attribute name="Configuration">
            <configuration>
                <!-- Change to your mail server prototocol -->
                <property name="mail.store.protocol" value="pop3"></property>
                <property name="mail.transport.protocol" value="smtp"></property>

                <!-- Change to the user who will receive mail  -->
                <property name="mail.user" value="${username}"></property>

                <!-- Change to the mail server  -->
                <property name="mail.pop3.host" value="${pop3-server}"></property>

                <!-- SSL parameters STARTED-->
                <property name="mail.smtp.host" value="${smtp-server}"></property>
                <property name="mail.smtp.auth" value="true"></property>
                <!-- The mail server port -->
                <property name="mail.smtp.port" value="465"></property>
                <property name="mail.smtp.ssl.enable" value="true"></property>
                <property name="mail.smtp.socketFactory.class" value="javax.net.ssl.SSLSocketFactory"></property>
                <!-- SSL parameters ENDED -->

                <property name="mail.smtp.connectiontimeout" value="20000"></property>
                <property name="mail.smtp.timeout" value="20000"></property>

                <!-- Change to the address mail will be from  -->
                <property name="mail.from" value="${yourname@yourisp}"></property>

                <!-- Enable debugging to see a lot of inetresting about SMTP protocol -->
                <property name="mail.debug" value="true"></property>
            </configuration>
        </attribute>
        <depends>jboss:service=Naming</depends>
    </mbean>
</server>

So, that configuration seems at least trying to connect to my SMTP server, but emails are still not sent out. The reason is the SSL-certificate which my ISP used is signed by cacert.org, which issue free certificates.
To fix this issue I have to install that certificate into my java keystore and the easiest way to do it was to use InstallCert program (the link to source-code)
I run java my-smtp-server:465 input “1″ and program generate jssecacerts. After that I updated cacerts file in my %JRE-HOME%/lib/security with generated file (of course I backed up previous cacerts) and that was enough to start using my SSL email.

To find more details or solve more issues you can read the JavaMail FAQ which cover a lot of topics, for example I think it worth to use gmail or yahoo smtp for your email testing purposes, since they are always present and you are not depend on your ISP SMTP

Posted in Software Development, Tips and Tricks | Tagged: , , , , , , | Leave a Comment »

Creating Excel reports from java is easy

Posted by Andrey Chorniy on December 2, 2009

Yeah, things sometime become really easy if you choose right tools and approach.
I’ve to create relatively complex Excel report which is not “die-hard” task itself (you can use Apache-POI or JExcel API)
But creating the formatting with Apache-POI API is really boring and it is too time consuming task. Since project was a JBoss-Seam based I also have an option to create it with Seam-Excel-support (btw, Seam use JExcel inside).  Much better then just a POI-API – you can define your Excel template in JSF template. Good enough, but still too much dancing around formatting is needed.

So, I decided to try to use JXLS which I use before for relatively simple reports.
JXLS allow you to define your dynamic Excel template right in Excel file, so you can just take an report example with required formatting and insert iteration tags (it also have condition tags). JXLS use JEXL as expression language so we can insert quite complex expressions and call java methods on objects.
So, everything works fine, I provide the data to JXLS, write output to OutputStream and was able to update formatting on the fly without any coding.

The only thing make me unhappy – my report require generation of dynamic sheets but this feature just failed in the latest JXLS release (0.9.8). It throws ClassCastException during sheet copy operation java.lang.ClassCastException: org.apache.poi.hssf.util.CellRangeAddress cannot be cast to java.lang.Comparable
It looks like nobody check this feature (never run this code) since CellRangeAddress is NOT Comparable. As I got from inspecting the code in subversion it was refactored to work with new POI API and TreeSet was used as a container for CellRangeAddress (maybe just mechanic error)
So, that sad issue may be easily fixed if all TreeSet instances created in the “net.sf.jxls.util.Util.java” will be changed to HashSet

    public static void copyRow(HSSFSheet sheet, HSSFRow oldRow, HSSFRow newRow) {
        //TreeSet --> HashSet
        Set mergedRegions = new HashSet();
    }
    public static void copyRow(HSSFSheet srcSheet, HSSFSheet destSheet, HSSFRow srcRow, HSSFRow destRow) {
        //TreeSet --> HashSet
        Set mergedRegions = new HashSet();
    }

    public static void copyRow(HSSFSheet srcSheet, HSSFSheet destSheet, HSSFRow srcRow, HSSFRow destRow, String expressionToReplace, String expressionReplacement) {
        //TreeSet --> HashSet
        Set mergedRegions = new HashSet();
    }

You can apply that patches on your own, by downloading jxls with sources and call “mvn clean install” from source code folder.

Another issue I’ve found about JXLS – is perfomance, on my reporting example (which has about 32 sheets) template processing was quite long (about 3-5 seconds) which is not good if your reports are frequently generated. I have a plan to profile and fix that performance issue in my free time.

Happy templating with JXLS, it’s really good tool and this article is my attempt to support that library and the efforts which JXLS developers put on it.
Thank You Guys !

Posted in Software Development, Tips and Tricks | Tagged: , , , , | 2 Comments »

How to Become an Early Riser

Posted by Andrey Chorniy on September 6, 2009

Very nice solution which upgrade your lifestyle and get you more productive time each day.
How to Become an Early Riser

The idea in short is to “Go to bed when you’re sleepy and then get up at a fixed time”. It’s hard to start such practice but after some time it become your habit.
As a result your body perform self-regulations (adapted) to that, so if you go to bad too late one day your body will force you to fall asleep sooner next day.

Posted using ShareThis

Posted in Tips and Tricks | Tagged: , | Leave a Comment »

Gmail failure 502 on September 1, 2009

Posted by Andrey Chorniy on September 1, 2009

Today, September 1, 2009, Gmail was down from 20-00/8pm GMT it is actually in progress now , but my IMAP access from Outlook still works, cool.
Gmail shows “502 Server error” in the title and “The server encountered a temporary error and could not complete your request.” in the page. I was able to load it with standart (static HTML/non-ajax) mode, but it looks awful, Outlook with IMAP is much better.

Interesting – is it some attack on Google or what ?
The only issue I experienced with Outlook/IMAP is the absence of gmail contact’s in Outlook and it’s actually slower then Gmail web-application.
But that could be fixed by exporting contacts from GMail in CSV/Outlook format and importing it in Outlook.
Here is instructions for Export/Import GMail contacts

  1. Click on Contacts in your GMail
  2. Click Export (right corner)
  3. Choose “Everyone” and “Outlook CSV format (for importing into Outlook or another application)”
  4. Open “File/Import and Export” in Outlook
  5. Select “Import from another program or file”
  6. Select comma-separated values (Windows)
    not sure which encoding GMail use, but russian names inserted as question marks “????”
  7. Select “Do not import duplicate items” if you don’t want to override your contacts
  8. Select destination folder for contacts. I’ve choosed “Contacts” in “Personal Folders”

But.. anyway, I’m still the fan of Gmail web application and Google Docs.

Here is the link to Gmail IMAP intructions – select your IMAP client and GO! BTW, I suppose my Android G1 also use IMAP access. Sorry, upps, you have to enable IMAP in GMail first. The bad news is that you need Gmail web application for that, so it’s better to enable it to use later.

Anyway, it is just a backup option for me which help to read couple of recent emails and I steel need to make GMail contacts export/import to work with my GMail in Outlook.
I’d prefer Google and Microsoft will include it (or write plugin) to import GMail contacts in the next version of Outlook :-) Sounds like a joke, isn’t it ?

Posted in Tips and Tricks | Tagged: , , | 1 Comment »

Howto delete large emails from GMail

Posted by Andrey Chorniy on August 24, 2009

Problem description
I use GMail almost every day during 4 years (and I love it) and on the moment I have a tons of emails and about 1.5 Gb of email storage size.
I’m sure that a most of that is eaten by couple of big attachments. The issue is that GMail web interface doesn’t have the ability to sort by email-size and that’s why you can’t find the biggest ones emails to delete them first. As well you may need to use some specific filtering to your emails which are not available in GMail web interface.
Solution

  1. Download your GMail emails with IMAP to your favorite email-client
  2. Open “[GMail]/All Mail” folder and wait for messages are downloaded.
  3. Sort by email size or apply whatever filter you need
  4. Delete emails you don’t won’t to keep in GMail

Important Note since downloading of all your emails could take a while and you even can be blocked by GMail – split your downloads into few days. So download during 1-2 hours each day.
Email should be deleted form the “All Mail” folder since deletion it from your “Gmail Labels” will just remove that label form that email but not delete it. GMail have special topic “Deleting IMAP messages”.

If you delete a message from your inbox or one of your custom folders in your IMAP client, it will still appear in [Gmail]/All Mail.

It is interesting for me which application behaves better with handling thousands of emails – Outlook or Thunderbird. My experience is that Outlook 2007 becomes crazy now – it try to synchronize with GMail and I’m experiencing problems with it. CPU loading is high (30-70%), network is loaded (it’s understandable) and click on email to view it and on navigation buttons just stuck the Outlook.
BTW, what I like from Outlook – it has special “Search Folders” folder with “Large Mail” folder in which I can group my emails with “Enormous >5MB” , “Huge 1-5 MB” etc. It’s perfectly suits my needs :-)

Posted in Tips and Tricks | Tagged: , , | Leave a Comment »

TinyMCE spellchecker java implementation

Posted by Andrey Chorniy on August 11, 2009

TinyMCE rich-editor have a plugin to provide Ajax-spell-checking functionality. See the link to TinyMCE plugin documentation
So, if you have a PHP and PSPell/ASpell on your server – then you are fine and you can use them, but this post is about the situation then you don’t have them or want to use your own implementation. In that case we can configure “spellcheck” plugin to use our own service.
What we have to do is to create a webservice compatible with the “TinyMCE spellchecker plugin” and configure spellcheck with the URL to that service. Because of browser security reasons this service should be hosted on the same domain as the application which use it (ajax calls can be blocked if requested URL is on another domain then your page). And since we are using java then we can use open-source Jazzy spellchecker library to implement spell-checking functions required by the TinyMCE spellchecker plugin

tinyMCE.init({
	theme : "advanced",
	mode : "textareas",
	plugins : "spellchecker",
	theme_advanced_buttons3_add : "spellchecker",
	spellchecker_languages : "+English=en,Swedish=sv"
        spellchecker_rpc_url    : "/spellchecker/jazzy-spell-check", //spellcheck url
});

In the configuration example above we set the link to our splechecker-service-url with the “spellchecker_rpc_url : “/spellchecker/jazzy-spell-check”;”
“/spellchecker/jazzy-spell-check” will be served by the servlet which use Jazzy project.
TinyMCE spellchecker plugin send JSON request to spellchecker_rpc_url with two possible methods:

  1. checkWords – send the array of words as params attribute and expect the JSONArray of misspelled words in the result JSON-response attribute.
  2. getSuggestions – send the checked word as the first and only element of params attribute and expects the JSONArray of suggested words the result JSON-response attribute.

So, when user click on “check spellcheck” button, plugin get the list of words and send them as the JSON request, with two parameters “method”=”checkWords” and “params”=”JSONArray(words)”. Servlet return the list of misspelled words in the JSON-response "{'id':null,'result': JSONArray(misspelled-words),'error':null}" , misspelled words are highlighted and once user click on one of them – request to get the list of suggested words is send to the server. “method”=”getSuggestions” and “params”=”JSONArray(checked-word)” . Server return the "{'id':null,'result': JSONArray(word-suggestions),'error':null}" JSON-response and list of suggestions is displayed to the user.

Update: You can see the backend java source code at the jspellchecker sourceforge project. SVN is accessible via “svn co https://jspellchecker.svn.sourceforge.net/svnroot/jspellchecker jspellchecker” or you can browse source-code . Please take a notice that source-code doesn’t include dictionaries. The dictionaries are located in the /WEB-INF/dictionary/${lang}-${country-code}.
Special thanks to the Rich Irwin who initially provide me the code.
The quality of spell-checking with jazzy depends on the quality of your dictionary. I think it possible to get thelist of words from Mozilla Dictionaries by saving XPI and opening it as ZIP file, saving dictionary file and remove “/xyz” from the end of the words, but please check the licensing notice before. You can also extract dictionaries form aspell (have no details how to do it)

Posted in Software Development | Tagged: , , , , , , , | 8 Comments »

JBoss SSL configuration

Posted by Andrey Chorniy on July 15, 2009

Ok, I just google for “JBoss SSL configuration” and found couple of useful articles, I don’t want to create “yet another guide to JBoss SSL configuration” but will describe particular issues I met.
Here is the links :http://www.jboss.org/community/wiki/SSLSetup is quite informative to configure your SSL. The general idea is to configure your server/${profile}/deploy/jboss-web.deployer/server.xml and define SSL Connector here. That article give some more advanced information on SSL configuration (using SSL Connector with APR – Apache Portable Runtime , etc.)

In practice I’ve found that JBoss port configuration for HTTP/HTTPS is not trivial thing – require a lot of changes. But the workaround exists – you can update your conf/jboss-service.xml and uncomment ServiceBindingmanager which use port-bindings.xml
Here is a way to configure your ports and be able to switch between them relatively fast

Once you have configured your JBoss/Tomcat to use SSL, you have to configure your application to use it. Yes, at this point pages at your application are also available

I also should mention that by default all encryption cyphers supported by JVM will be used. To change it you have to specify ciphers attribute for your SSL Connector.
here is an example which include almost all ciphers with length > 64

<Connector port="8443" address="${jboss.bind.address}"
maxThreads="150" strategy="ms" maxHttpHeaderSize="8192"
emptySessionPath="true"
scheme="https" secure="true" clientAuth="false"
sslProtocol = "TLS"
keystoreFile="${jboss.server.home.dir}/conf/keystore/yourkeystore.keystore"
keystorePass="your-keystore-password"
protocol="HTTP/1.1"
ciphers="SSL_DHE_DSS_WITH_RC4_128_SHA,
SSL_DH_anon_WITH_RC4_128_MD5,
SSL_RSA_WITH_RC4_128_MD5,
SSL_RSA_WITH_RC4_128_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
TLS_DH_anon_WITH_AES_128_CBC_SHA,
TLS_DH_anon_WITH_AES_256_CBC_SHA,
TLS_KRB5_WITH_RC4_128_MD5,
TLS_KRB5_WITH_RC4_128_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA,
TLS_RSA_WITH_AES_256_CBC_SHA"
SSLEnabled="true">
</Connector>

and if you want to make it even more secure – you have to remove anonymous cyphers from that list SSL_DH_anon_WITH_RC4_128_MD5, TLS_DH_anon_WITH_AES_128_CBC_SHA and TLS_DH_anon_WITH_AES_256_CBC_SHA

Important note: During keystore/private-key generation you MUST use SAME passwords for both. You don’t have the way to specify different passwords for keystore and key in tomcat SSL configuration.
See in the original issue description and Tomcat 5.5 documentation

Posted in Software Development | Tagged: , , , , , | 1 Comment »

Howto avoid concurrent call to conversation problem in Seam

Posted by Andrey Chorniy on July 14, 2009

It’s very common that in your Seam web-application you will get “HTTP Status 503 – Concurrent call to conversation” error and an exception stacktrace if you in debug-mode.

That can be caused by several reasons, one of them is double click on the ajax-link like <a4j:commandLink action=”#{myAction.action} value=”Simple link”/>
A4J/RichFaces allow the solultion for that problem – you have just to specify eventsQueue attrbute
<a4j:commandLink action=”#{myAction.action} value=”Simple link” eventsQueue=”myQueue” />
In that way even if user will click on that link twice – the events (requests) will be sent only one-by-one

As a side-note it worth also to specify “requestDelay” (specify the time the request will wait in queue before send) and ignoreDupResponses=”true” (A4J will ignore ajax response if another “similar” request is in queue). It’s worth for everyone to read that in RichFaces docs

But, it not always solve your problem – users are unpredicted creatures and they can click on your h:commandLink (which is not ajax and can’t be set to queue) or even on some link which actually triggers an action.  So,  you are still not safe since user have a lot of ways to break your application by click on another element which will trigger action inside current conversation.

Besides the fact that using a4j-queues is a good practice (it improve the overall perfomance of application also) – to be absolutely safe you have to disable ALL THE LINKS in the document or make them inaccessible for the user. And the solution exists, it rather simple but very powerful. So what you have to do – is to show <rich:modalPanel> once user is click on the link (or start ajax request with <a4j:support>) and hide it after ajax-response is complete. For h:commandLink or h:commandButton – you don’t have to worry about hiding it, since once new page will be loaded rich:modalPanel will be disappeared automatically (since it belongs to previous page/DOM-document). Once rich:modalPanel is shown – it makes impossible to use any navigation elements on the page except the elements on that form itself.

You can even automatically enable it for all your ajax-request’s with help of <a4j:status> and “onstart” “onstop” handlers.  In the example below the onRequestStart() function is called by onstart handler of aj4:status component. In the example below

//javascript
var waitDialogShown = false;
var useTimerBeforeShowWaitDialog = true;
var waitDialogTimeout = 50;
var waitDialogTimer;

function showWaitDialog() {
    //avoid attempt to show it if it is already shown
    if (!waitDialogShown) {
        Richfaces.showModalPanel('wait-dialog');
        waitDialogShown = true;
    }
}

function onRequestStart() {
    if (useTimerBeforeShowWaitDialog) {
        waitDialogTimer = setTimeout("showWaitDialog();", waitDialogTimeout);
    } else {
        showWaitDialog();
    }
}
function onRequestEnd() {
    if (waitDialogShown) {
        Richfaces.hideModalPanel('wait-dialog');
        waitDialogShown = false;
    } else if (useTimerBeforeShowWaitDialog && waitDialogTimer) {
        clearTimeout(waitDialogTimer);
    }
}
<a4j:status onstart="onRequestStart()" onstop="onRequestEnd()"/>

<rich:modalPanel id="wait-dialog" resizeable="false" autosized="false" width="200" height="65" moveable="false" shadowOpacity="0">
  <f:facet name="header">One moment please..</f:facet>
  <h:outputText value="Your request is being processed."/>
</rich:modalPanel>

<!-- Your wait dialog can be invisible for the users if you don't want your screen blink with that dialog on each request -->
<rich:modalPanel id="wait-dialog-invisible" resizeable="false" autosized="false"
width="10" height="10" moveable="false" left="-100" top="-100" shadowOpacity="0"/>

And if you don’t want to apply that for every component or want to modify prevention behavior you can do one of the:

  1. Explicitly define onclick function of your links/buttons
    <h:commandButton onclick=”onRequestStart();” value=”Button”/>
    for ajax you also have to define oncomplete to hide the modalPanel, otherwise your browser-page will be blocked
    <a4j:commandButton onclick=”onRequestStart();” oncomplete=”onRequestEnd();” value=”Button”/>
  2. Define a4j:status with id and forceId=”true” and use status attribute of your ajax components to specify the a4j:status component they will use.
   <a4j:status id="waitStatus" forceId="true" onstart="onRequestStart()" onstop="onRequestEnd()"/>
   <a4j:commandLink status="waitStatus"/>

Posted in Software Development, Tips and Tricks | Tagged: , , , , , , | 12 Comments »

Howto improve Seam application security

Posted by Andrey Chorniy on July 12, 2009

In this post I’ll show some tips & tricks to make your application more secure then it is by default. See the links section at the bottom for future reading.

It’s clear that in reality your application can be hacked by some advanced geek, but anyway, let’s start.

1. Be careful with uploaded files

The most dangerous security issue with your site (not only Seam based) – is the ability to upload ANY file to the server and then access it via HTTP.  So, let’s say you have to organize image-files uploading. You can do it in the way
use <rich:upload /> component, upload them and save in some directory on the server which is under some ${context-path}.
This approach have several problems
1) it is always dangerous to allow user upload files and use them directly.
rich:upload by default allow you to upload any file (.jsp) for example and *.jsp file is uploaded it can be accessed by GET/POST request like

http://yourappdomain/${context-path}/directory-path/uploaded.jsp

that jsp can then be used to allow external users to access to all your system resources (list directories, do file operations, etc.)

That problem could be solved on different levels
1) Specify <rich:upload acceptedTypes=”jpg,gif,png”/>
2) Check that uploaded file is the real-image on the server-side. it could be done with such method

public static boolean isImageFile (String fileName) {
if (!isExtensionAllowed(fileName))
    return false;
try {
    BufferedImage img = ImageIO.read(new File(fileName));
    if (img == null){
        return false;
    }
    return img.getWidth() > 0 && img.getHeight() > 0;
} catch (IOException e) {
    return false;
}
}

3) Don’t use direct access (${context-path} based). You can create some simple resource-servlet like /resource-servlet?rid=${resource-id}  You also may use content-repositories (Alfresco, JackRabit) if you need something which is more advanced and scalable. It depends on your needs, how much files you want to upload and how are you going to use it (search, etc.).

2. Store password encrypted

You never know if you will be hacked or not, but a good point will be to store encrypted password in your DB, but no a passwords in a plain text.

I was surprised that Seam contains ready-to-use solution for that issue. You can see the Identity Management
So, actually you just need to define several seam annotations like @UserPrincipal for login-name/username field and @UserPassword(hash = “md5″) or other hashing algorithm (curently “md5″ and “sha” algorithms are supported).
Please be advised that you have to use identity-manager interface manage users. For example you have to create user with following call identityManager.createUser(“login”,”password”,”firstname”,”lastname”) – in that way the password will be saved in a hashed form. Don’t use entityManager.persist(user) directly.

  <security:identity-manager
    identity-store="#{ldapIdentityStore}"
    role-identity-store="#{jpaIdentityStore}"/>

It’s intresting to try to provide my own hashing algorithm. BTW, interesting features have been added to the latest Seam version. We should be able to specify the iteration attribute for @UserPassword and should have the way to override the attribute used together with user-password to generate hash (Salt) https://jira.jboss.org/jira/browse/JBSEAM-3762, by default attribute annotated with @UserPrincipal used as a Salt.

Here is another approach without Seam IdentityManager. You can use MD5 checksum of user-provided password and save it in a hashed form in DB.
Here is the java-function to generate MD5 from String

public static String generateMD5(String password) {
try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(password.getBytes());
    StringBuilder result = new StringBuilder();
    for (byte b : md.digest())
        result.append(String.format("%02x", b));
    return result.toString();
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    return null;
}
}

So, to set the password on User entity use the
user.setPassword(generateMD5(password));

Here is the JPA-query to search user by login and MD5-hashed password.

User user = entityManager.createQuery(
    "select u from User u where u.login= :login and u.password= MD5(:password)")
    .setParameter("login", login).setParameter("password", password)
    .uniqueResult();

Assuming that user-login is the unique field in the DB, you can use the search by login, in that case you may use any hashing algorithms you want, event those which are not supported by DB.

User userByLogin =  entityManager.createQuery(
    "select u from User u where u.login= :login )
    .setParameter("login", login)..uniqueResult();
if (user.getPassword().equals(PasswordHashFunction.createPasswordHash(userPassword)){
   //authentication successful
}

You can also look for other MD5 here http://rosettacode.org/wiki/MD5 . MD5 disadvantage is cryptographic weakness, SHA is better but it is still wll-known, so you may think about AES, or DES functions to encrypt your very private data. See mysql-encrypt-funcitons

3. Store data encrypted

Here is an intresting solution for the encrypting data with Hibernate – Jasypt. Hower please be advised that you can’t use that fields in the WHERE clause.
“Jasypt” + “Bouncy Castle Crypto package SHA-1″ should play well toghether. it also have Seam integration

4. HTTPOnly cookies

Microsoft introduced HTTPOnly cookies which is actually just a flag on the cookie “HTTPOnly”

If the HTTPOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.

If a browser does not support HTTPOnly and a website attempts to set an HTTPOnly cookie, the HTTPOnly flag will be ignored by the browser, thus creating a traditional, script accessible cookie. As a result, the cookie (typically your session cookie) becomes vulnerable to theft of modification by malicious script.

But currently JBoss/Tomcat application can’t use that feature – they are not implemented in Tomcat yet (https://issues.apache.org/bugzilla/show_bug.cgi?id=44382)
Here is an approach which allow you to introduce it, but I don’t think it is recomended way http://stackoverflow.com/questions/33412/how-do-you-configure-httponly-cookies-in-tomcat-java-webapps.

So, the solution here – is wait for next releases of Tomcat/JBoss.

5. Remove or secure default JBoss applications

Don’t forget to secure or even remove JBoss webapps like /web-console /jmx-console. See the JBoss documentation for details

6. Disable “debug” mode for production deployment

In debug mode a lot of information is disclosure about your application, as well application works slower in “debug” mode. Usually it is configured via property in the components.properties file, something like  “debug=true”, just check your components.xml file for the

<core:init debug="@debug@" jndi-pattern="@jndiPattern@"/>

SSL configuration

It is not always a requirement to have SSL configured for application to have trusted HTTPS protocol, so I’ll put it in a separate post http://achorniy.wordpress.com/2009/07/15/jboss-ssl-configuration/

Links

Blogged with the Flock Browser

Posted in Software Development | Tagged: , , , , | Leave a Comment »

GData Api and JSON feed generation from java

Posted by Andrey Chorniy on July 10, 2009

I found that google GData API allow you to access and manage almost all google-services (like Calendar, Picassa, Blogger). It give you numerous ways to do that – via java, PHP, javascript or pure HTTP/XML feeds. very powerful. great work!
And on the moment there are a lot of components exists which use that API.

But components I need require JSON feed which could be generated by HTTP request to google Calendar-Service, but the problem is I don’t want to put my data here to access it, I just need to generate JSON from my events.
Unfortunately I don’t find the solution in java-gdata API for that, what I find was only the small notice in documentation

The XmlWriter class exposes a number of protected methods that enable it to be subclassed for the purposes of customizing its output. See {@link com.google.javascript.util.JsonWriter} for an example.

Hey, they have the solution for my problem! But in reality there is no such class (I will be very helpful for somebody who can point me to the source/jar with that file) But it seems it only the notice in documentaiton which express one of the the design point for that class.

Ok, it’s not great, but I want that JSON to be generated and I wrote my own implementation of JsonWriter which use org.json implementation. It was not easy since I don’t find anything except that draft comparison of XML and JSON formats.
So actually I based on the generateAtom() method of BaseFeed and write JsonWriter implementation which was tested by using it with google gdata javascript api, which successfully transform it to the CalendarEventFeed/CalendarEvent objects.

I will update it later with sources and comments. Implementation is in really draft (but working) state.
The open question for me is how that changes could be promoted to a google-community/google data-api research group.

Posted in Software Development | Tagged: , , , , , | Leave a Comment »