Friday, May 29, 2015

WebLogic mime mappings

To configure mime-mappings in WebLogic, you have 2 ways.
One is to configure the whole domain, with a mimemappings.properties file.
This is the entry in config.xml (you can do it in console, domain, webapplications):

 <web-app-container>
    <x-powered-by-header-level>NONE</x-powered-by-header-level>
    <mime-mapping-file>./config/mimemappings.properties</mime-mapping-file>
  </web-app-container>


Mime Mapping File 

Returns the name of the file containing mime-mappings for the domain.

Format of the file should be: extension=mime-type

Example:
htm=text/html
gif=image/gif
jpg=image/jpeg

If this file does not exist, WebLogic Server uses an implicit mime-mapping set of mappings defined in weblogic.utils.http.HttpConstants (DEFAULT_MIME_MAPPINGS). To remove a mapping defined in implicit map just set it to blank.

MBean Attribute:
WebAppContainerMBean.MimeMappingFile




The other way is to create a mime-mapping entry in your web application's web.xml

For a general presentation of IE11 and Mime: https://msdn.microsoft.com/en-us/library/ms775148%28v=vs.85%29.aspx

Remember also the default-mime-type attribute in weblogic.xml. "This element allows the user to specify the default mime type for a content-type for which the extension is not mapped."



Sunday, May 24, 2015

Book : Java EE 7 Development with NetBeans 8



Don't expect a highly entertaining narrative in this book, it's simply a collection of examples illustrating the most important features of Netbeans 8 to build various kind of JEE applications, including Rest services, JMS messaging and JSF webapps. However it's kind of useful.



Saturday, May 23, 2015

Book: Masterminds of Programming



I thought it was fun to hear the designer of so many different languages discuss on what is important in a language, and which rules to follow when designing a language and when writing an application.

Few of them seemed really to have clear ideas about language design.... and most statements contradict each others...so still in 2015 we don't have a clear, commonly agreed, scientific approach to language design...

The author of Haskell was definitely the most inspiring...

Monday, May 18, 2015

kill weblogic on OutOfMemory error

When a weblogic server is hit by an OutOfMemory condition, it often agonizes for a while before finally collapsing. This is not very healthy for the poor beast, and for humanitarian reasons you might want to end its suffering sooner.

The first approach could be to use the

<overload-protection>
   <panic-action>system-exit</panic-action>
</overload-protection>



OnOutOfMemoryError is a little-know flag documented here http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html

Try starting the JVM with -XX:OnOutOfMemoryError="kill -9 %p" or -XX:OnOutOfMemoryError='kill -9 %p' and see if this does the job.

This is my test (source code copied from Crunchify site):



cat GenerateOOM.java

public class GenerateOOM {
 
 
        public static void main(String[] args) throws Exception {
                GenerateOOM memoryTest = new GenerateOOM();
                memoryTest.generateOOM();
        }
 
        public void generateOOM() throws Exception {
                int iteratorValue = 20;
                System.out.println("\n=================> OOM test started..\n");
                for (int outerIterator = 1; outerIterator < 20; outerIterator++) {
                        System.out.println("Iteration " + outerIterator + " Free Mem: " + Runtime.getRuntime().freeMemory());
                        int loop1 = 2;
                        int[] memoryFillIntVar = new int[iteratorValue];
                        // feel memoryFillIntVar array in loop..
                        do {
                                memoryFillIntVar[loop1] = 0;
                                loop1--;
                        } while (loop1 > 0);
                        iteratorValue = iteratorValue * 5;
                        System.out.println("\nRequired Memory for next loop: " + iteratorValue);
                        Thread.sleep(1000);
                }
        }
 
}


This is the run:
java -XX:OnOutOfMemoryError="kill -9 %p" GenerateOOM 

=================> OOM test started..

Iteration 1 Free Mem: 244998456

Required Memory for next loop: 100
Iteration 2 Free Mem: 244998456

Required Memory for next loop: 500
Iteration 3 Free Mem: 244998456

Required Memory for next loop: 2500
Iteration 4 Free Mem: 244998456

Required Memory for next loop: 12500
Iteration 5 Free Mem: 244998456

Required Memory for next loop: 62500
Iteration 6 Free Mem: 244998456

Required Memory for next loop: 312500
Iteration 7 Free Mem: 244998456

Required Memory for next loop: 1562500
Iteration 8 Free Mem: 243748440

Required Memory for next loop: 7812500
Iteration 9 Free Mem: 237498424

Required Memory for next loop: 39062500
Iteration 10 Free Mem: 206248408

Required Memory for next loop: 195312500
Iteration 11 Free Mem: 49998392

Required Memory for next loop: 976562500
Iteration 12 Free Mem: 50003032
#
# java.lang.OutOfMemoryError: Java heap space
# -XX:OnOutOfMemoryError="kill -9 %p"
#   Executing /bin/sh -c "kill -9 3860"...
Killed


I have also tested that if OnOutOfMemoryError and HeapDumpOnOutOfMemoryError are used together, the HeapDumpOnOutOfMemoryError is executed first, then the server is killed.

java -XX:OnOutOfMemoryError="kill -9 %p" -XX:+HeapDumpOnOutOfMemoryError GenerateOOM

PS I have tested using single quotes ( java -XX:OnOutOfMemoryError='kill -9 %p' ) and it works on Linux )

Friday, May 15, 2015

HP Wireless Module not found

All of a sudden my old compaq presario gave the "Wireless Module not found" error on startup.

I have googled all kind of solutions (power drain, driver update...), none worked.

Then I have watched this video:



I have grabbed a screwdriver, opened the lid, and I discovered that the card was not properly inserted in its socket - probably a mechanical shock pulled it out.

I have tried to report this SIMPLE but NOT MENTIONED solution to HP forum, it was impossible to add a reply...

Anyway.... this is just to say that not ALL SOFTWARE error messages are originated by SOFTWARE issues.... sometimes hardware fails, even only for mechanical problems...



Monday, May 11, 2015

java.security.cert.CertificateException: no trust anchor defined

Or also "Trust anchor for certification path not found "


If you see a "java.security.cert.CertificateException: no trust anchor defined", most likely it means that someone has messed up the Certificate, for instance replacing a trusted CA certificate with a Self-Signed certificate.

you can use "openssl s_client -debug -connect yourhost:yourport" and check for the dreaded "verify error:num=18:self signed certificate"

In case you use an Oracle Wallet to hold certificates, you can do a

orapki wallet display -wallet /path/to/wallet -summary

http://docs.oracle.com/cd/B28359_01/network.111/b28530/asoappf.htm#i636653


Here https://medium.com/@kibotu/handling-custom-ssl-certificates-on-android-and-fixing-sslhandshakeexception-65ffb9dc612e some troubleshooting is suggested

#this to display the server's certificates
openssl s_client -connect myserver.com:443 -showcerts


#to save server cert to pem format
openssl s_client -connect google.com:443 -showcerts < /dev/null 2> /dev/null | openssl x509 -outform PEM > googlecert.pem

The JVM trusted CA certs are in $JAVA_HOME/jre/lib/security/cacerts

To add an entry in cacerts:

keytool -import -trustcacerts -keystore cacerts -storepass changeit -alias googleca -import -file googlecert.pem

To examine the content of cacerts , use https://keystore-explorer.org/


To dump all your trustedCA()

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Arrays;


public class TM {
    public static void main(String[] args) throws Exception {
        TrustManagerFactory factory = TrustManagerFactory.getInstance("X509");
        factory.init((KeyStore) null);
        TrustManager[] tms = factory.getTrustManagers();
        X509TrustManager tm = (X509TrustManager) tms[0];
        X509Certificate[] ai = tm.getAcceptedIssuers();
        Arrays.stream(ai).forEach(item -> System.out.println(item.toString()));
    }
}




Here https://nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/ a dirty trick to trust all certificates:


import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
 
public class Example {
    public static void main(String[] args) throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
        };
 
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
 
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
 
        URL url = new URL("https://www.nakov.com:2083/");
        URLConnection con = url.openConnection();
        Reader reader = new InputStreamReader(con.getInputStream());
        while (true) {
            int ch = reader.read();
            if (ch==-1) {
                break;
            }
            System.out.print((char)ch);
        }
    }
}




Wednesday, May 6, 2015

Learning Angular 2

I have recently applied for a job in Toptal - just to keep be busy on weekends, after my regular bicycle rides - and they asked me to build a small Web Application.
jQuery seemed a bit outdated, so I have decided to learn Angular 2
Here a useful presentation (just skip the first 10 minutes.... why people can't simply go straight to the point....)
http://www.infoq.com/presentations/angularjs-2
and the next thing you probably want to do is to go through the tutorial https://angular.io/docs/js/latest/quickstart.html

I know there are other products (Ember, React) but I don't have the time to examine them all.
This one is very good, about HTML5 and Angular 1:



This contains a really cool, simple example you can easily code yourself:





This one attempts to explain you the concepts, there are good things but I find it very very verbose:



(I might take the whole 7 hours course, it's only 19 USD)

Then this one is really good to show all the bits and pieces who put together form the AngularJS framework







Tuesday, May 5, 2015

OpenJPA will not be used

http://www.artofbi.com/blog/weblogic-log-repeats-openjpa-will-not-be-used-solution/

a customer was complaining today about his stdour/stderr file being flooded by the message "OpenJPA will not be used".

The link above explains very well the story. The only issue is that not always it's advisable to redirect the stderr to the weblogic log file (I like very much the idea, but if already some monitoring mechanism is in place, it has to be adjusted)

Anyway in the config.xml you should have

for the domain:

  <log-filter>
    <name>OpenJPA</name>
    <filter-expression>NOT(MESSAGE LIKE '%OpenJPA will not be used%')</filter-expression>
  </log-filter>


then for each server

<stdout-filter>OpenJPA</stdout-filter>


and also

<redirect-stderr-to-server-log-enabled>true</redirect-stderr-to-server-log-enabled>


According to Oracle Support, "This message comes up whenever a persistence provider (ex: Eclipse) other than Kodo or OpenJPA is used in Weblogic Server. "

In config.xml you can have one of 2 values:

TOPLINK

  <jpa>
    <default-jpa-provider>org.eclipse.persistence.jpa.PersistenceProvider</default-jpa-provider>
  </jpa>
  


KODO

  <jpa>
    <default-jpa-provider>org.apache.openjpa.persistence.PersistenceProviderImpl</default-jpa-provider>
  </jpa>
  <log>


See http://docs.oracle.com/cd/E24329_01/web.1211/e24972/using_toplink.htm#EJBAD1415 , possibly the application is setting the provider in the code : "Specify the provider in the javax.persistence.provider property passed to the Map parameter of the javax.persistence.Persistence.createEntityManagerFactory(String, Map) method."

Sunday, May 3, 2015

Stateful REST : it can be done

Even in the SOA Philosophy, mostly based on SOAP over HTTP, a Service can be Stateful: you just need to enable javax.xml.ws.BindingProvider.SESSION_MAINTAIN_PROPERTY on the BindingProvider

in order to maintain state, you don't necessarily need to implement a Service as a Stateful EJB!

See http://docs.oracle.com/cd/E19226-01/820-7627/6nisfjmk8/index.html :

Stateful interactions through hyperlinks. Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. This topic is discussed somewhat in Using Entity Providers to Map HTTP Response and Request Entity Bodies, is discussed somewhat in the section Building URIs in the JAX-RS Overview document, and may be discussed in more detail in a forthcoming advanced version of this tutorial.

One can achieve this in JAX-RS 2.0 by using the javax.ws.rs.client.ClientResponseFilter for saving the cookie(s) from the HttpRequest and the javax.ws.rs.client.ClientRequestFilter for adding them again in the (subsequent) requests.

If you use WebLogic on the server side, remember that Jersey 2.5.1 is the supported "JAX-RS 2.0 Reference Implementation"