Dieses Blog durchsuchen

Mittwoch, 28. Oktober 2015

Using sublime in MacOSX or Linux terminal

To use SublimeText editor within your console just create a link like

ln -fs /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl    /usr/local/bin/sublime

and from now on you could use Sublime in your console like this

andre ~$ sublime .bashrc 

Mittwoch, 21. Oktober 2015

JUnit in eclipse

Running JUnit in eclipse shouldn't be a problem. I run into a

java.lang.NoSuchMethodError: org.junit.runner.Description.getClassName()Ljava/lang/String;

while using a bunch of projects in eclipse. Reason for that error was a project, which has an older version of Junit in his build path. Removing the old ref solves the problem.

set file.encoding in a JVM

To set the default file.encoding in a JVM you could set it in the JVM startup as -Dfile.encoding=UTF-8 or in JAVA_TOOLS_OPTIONS with the same part. But if you want to set it programmatically after the JVM already started?
A System.setProperty("file.encoding", "UTF-16"); will only set the file.encoding property. All other classes which rely on the defaultCharset, like all Streams and Buffers won't recognize that change. Here is a Junit Test, which shows you how to reset the Charset.defaultCharset field:


package de.kambrium;

import java.lang.reflect.Field;
import java.nio.charset.Charset;

import org.junit.Before;
import org.junit.Test;

public class CharsetTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        dump("Actual system config");
        System.setProperty("file.encoding", "UTF-16");
        dump("Config after System.setProperty(\"file.encoding\", \"UTF-16\")");
        Field cs = Charset.class.getDeclaredField("defaultCharset");
        cs.setAccessible(true);
        cs.set(null, null);
        dump("Config after manipulating defatulCharset field");
    }

    private void dump(String msg) {
        System.out.println(msg);
        System.out.println("****************************************************************");
        System.out.println("file.encoding          = " + System.getProperty("file.encoding"));
        System.out.println("defaultCharset         = " + Charset.defaultCharset());
        System.out.println("****************************************************************");
        System.out.println("");
    }
}


Output will look like this

Actual system config
****************************************************************
file.encoding          = UTF-8
defaultCharset         = UTF-8
****************************************************************

Config after System.setProperty("file.encoding", "UTF-16")
****************************************************************
file.encoding          = UTF-16
defaultCharset         = UTF-8
****************************************************************

Config after manipulating defatulCharset field
****************************************************************
file.encoding          = UTF-16
defaultCharset         = UTF-16
****************************************************************

Dienstag, 28. April 2015

Script for grabbing a root ca cert of a website

If you are using self signed certs or you are using certs, which are not part of the standard cacerts of your JDK you need to get the root ca cert from the desired website. To do so you might use the following script:

#!/bin/bash
ADDRESS=$1
echo -n | openssl s_client -connect $ADDRESS:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ./$ADDRESS.cert 



now you should have a cert file, which you could easily add to your cacert file of the jdk with this command:


keytool -importcert -alias startcom -file $ADDRESS.cert -keystore cacerts -storepass changeit

cacerts is located in JAVA_HOME/jre/lib/security (i.e. Mac OSX /Library/Java/JavaVirtualMachines/jdkX.X.X_XX.jdk/Contents/Home/jre/lib/security/cacerts)

This command adds your cert to the cacerts of the jdk and allows any java app using the jdk to connect via ssl to the desired website. Downsite of this trick is if you move to another server or workstation you might always need to patch the cacerts with your cert. 
So the best way is to prepare a keystore with your add on certs and add it to the Java System property

-Djavax.net.ssl.keyStore=/tmp/mykeystore.jks
or even in your Java Code by using System.setProperty. This will ensure that your java prog uses trusts the certs you want to trust.



Donnerstag, 10. Oktober 2013

Proximity sensor on IPhone 5 and IOS7 not working

Since the update to IOS7 on my IPhone 5 I sometimes switched the speaker on during a running phone call with my ears. To avoid this you should do the follwing after update your device to IOS 7:

  1. Go to Settings->General->Reset->Reset All Settings
  2. Reboot your device

thats it. A simple test can be done by calling your voice mail an during the call just put your finger on the sensor (it's located  left beside the camera on IPhone5). The sensor will turn of the display once you finger approaches the sensor.

Mittwoch, 9. Oktober 2013

HP-UX WebLogic and a Jaxb2Marshaller startup failed with ArrayIndexOutOfBoundsException

I ran in to a problem on a weblogic 10.3.5 instance where we installed an ear file with a new springframework ws application. This application uses a Jaxb2Marshaller for handling the ws messages in a spring config like this:


    <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"
          p:contextPath="com.mycomp.ws..client.model" />
    <bean id="sampleWsTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
    <constructor-arg ref="messageFactory"/>
    <property name="marshaller"      ref="marshaller" />
    <property name="unmarshaller"   ref="marshaller" />
    </bean>

the weblogic container failed to start up the application with the follwing messages:

org.springframework.web.context.ContextLoader Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.ws.client.core.WebServiceTemplate net.kambrium.service.impl.ServiceImpl.webServiceTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'WsTemplate' defined in class path resource [webservices.xml]: Cannot resolve reference to bean 'marshaller' while setting bean property 'marshaller'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'marshaller' defined in class path resource [webservices.xml]: Invocation of init method failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: 1
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.ws.client.core.WebServiceTemplate net.kambrium.service.impl.ServiceImpl.webServiceTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'WsTemplate' defined in class path resource [webservices.xml]: Cannot resolve reference to bean 'marshaller' while setting bean property 'marshaller'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'marshaller' defined in class path resource [webservices.xml]: Invocation of init method failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: 1
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'WsTemplate' defined in class path resource [webservices.xml]: Cannot resolve reference to bean 'marshaller' while setting bean property 'marshaller'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'marshaller' defined in class path resource [webservices.xml]: Invocation of init method failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: 1
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'marshaller' defined in class path resource [webservices.xml]: Invocation of init method failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: 1
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1

after deep diving into a lot of config an other WebLogic settings I found one settings, which was caused the problem. Within the startup of the WebLogic we used some of the tuning options HP recommends for performance reasons:

-XX:-StackTraceInThrowable



after removing that flag from the startup everything went fine. Looks like one of the initialization routines of Jaxb2 or of one of their dependent libs rely on interpreting the StackTrace. With that option we remove the stacktrace and with that we remove the chance for interpreting getStackTrace().

Dirk finally find out the reason for this error within the jaxb implementation. The jaxb uses a Util class, which uses the follwoing code



    public static Logger getClassLogger() {
        try {
            StackTraceElement[] trace = new Exception().getStackTrace();
            return Logger.getLogger(trace[1].getClassName());
        } catch( SecurityException _ ) {
            return Logger.getLogger("com.sun.xml.bind"); // use the default
        }
    }

well and that's it. The getStackTrace method returns null if the parm -StackTraceInThrowable is set thus resulting in ArrayIndexOutOfBoundsException. Thanks for not catching Exception beside Security Exception.

Freitag, 13. September 2013

Eclipse Keppler and the missing type ahead ctrl-space

Well when coding in eclipse I tend to hit ctrl-space frequently. Usually you'll see the proposed methods or vars of the class you point at. After installing a special Keppler build from one of our customers I hit ctrl-space and see a screen with just new, nls, runnable and to array:


well thats the new kind of type ahead from the eclipse guys? Ah, not at all!

Just go to Windows->Preferences->Java->Editor->Content Assist->Advanced and activate "Java Proposals" again:


eh voilá



Donnerstag, 22. August 2013

Unable to start Rule Studio of WODM aka JRules

I ran into a situation where the rule studio component of JRules 7.1.14 doesn't start anymore. While tumbling around I found out that the Rule Studio.exe just fires up an ant script behind the scenes to start eclipse.
The config of all that desaster lives in \shared\bin. If you have a look at the build.xml in here you'll find a target called runrulestudio. This is the target, which the standard starter fires up. You could even configure your permsize and other config flags here.

As I blamed some misconfiguration of my windows profile or my machine I just wrote a small ant starter to fire the RuleStudio with the environment of my joice like this:


set INSTALLDIR=C:\Program Files (x86)\IBM\WebSphereILOGJRules711
set JAVA_HOME=%INSTALLDIR%\jdk
set ANT_HOME=%INSTALLDIR%\shared\tools\ant
set PATH=%JAVA_HOME%\bin;%ANT_HOME%\bin

c:

cd %INSTALLDIR%\shared\bin

ant runrulestudio -Declipse.location="%INSTALLDIR%\eclipse"



well and that does the trick. Rule Studio starts up again 

Mittwoch, 31. Juli 2013

Windows 7 good to know

Screenshots or snapshots with onboard tool

With Windows 7 you don't need external tools like snagit, gimp, etc. Just use the SnippingTool, which ships with Windows 7!


Send to clipboard as path or name

Well who hasn't used the windows 95 powertoys? One of the need features was "Send to Clipboard as..." which has copied the currently selected file or folder and copied the name or path of it to the clipboard. 
With windows 7 just hold shift key while right clicking the selected files and you will find a new entry within the context menu "Copy as Path". 

Dienstag, 16. Juli 2013

Pretty print a SOAP Message

Here's a code snip for pretty printing a SOAP message 

import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;


    private static final Logger LOG = Logger.getLogger(PrettyPrint.class);
 

    /**
     * Pretty print the XML SOAP message
     *
     * @param source the source payload of a SOAP response or request
     * @return the pretty format of the SOAP message
     */

    private String getPrettyPrintSoapSource(Source source) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.setOutputProperty(OutputKeys.INDENT, "yes");
            t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(bos);
            t.transform(source, result);
            return bos.toString();
        } catch (Exception e) {
            LOG.error("Error while pretty printing SOAP source", e);
            return "Error while pretty printing SOAP source";
        }
    }

Mittwoch, 10. April 2013

No spaces in Misson Control Mac OSX 10.8.3

I like misson control (aka Exposé) in Mac OSX and the spaces functionality, which allows you to control multiple desktops in Mac OSX. Sincce 10.8.3 I noticed sometimes that the spaces just won't show up anymore in Misson Control. To me it seems to be a problem with the Dock as well. The Dock doesn't display correctly. So open up a terminal and enter

killall Dock

after that your spaces within Mission Control will be back and the Dock will restart.

Donnerstag, 4. April 2013

How to export a google docs document with comment to pdf

If you export a document with google docs to pdf you will loose all your comments. Heres a way to export the doc with comment

  1. Export google docs document to .odt open office file
  2. Open document in OO
  3. Go to export as PDF and select the "export comments" option
  4. Export to PDF with comment

Mittwoch, 26. September 2012

Show Hidden Files in MACOSX

to display hidden Files in Macosx Finder enter the following cmds in your console:

defaults  write    com.apple.Finder    AppleShowAllFiles  TRUE

killall Finder


Mittwoch, 29. August 2012

Js Modules with Titanium Appcelerator Framework

Here are the two ways you could currently use JS modules within the Titanium Mobile Framework from appcelerator:

1. Function Module

Assume you have a FunctionModule.js with the following content:

// an internal variable, which is only accesible within the module
var internalMsg = "Only visible within the module";

// an exported function, which this module offers
exports.hello = function(msg) {
alert('your message: ' + msg + ' internal message: ' + internalMsg);
}


you could use you module like this:

// reference the module
var fmo = require('/ui/common/FunctionModule');

// call the exported function
fmo.hello('External Message');










// no access from the outside to the internal variable
alert('interal var from module: ' + fmo.internalMsg)




2. Object Module

Assume you have a ObjectModule.js with the following content:


// constructor of your object
function Sample(name) {
   this.name = name;
}
// function, which alerts the current name
Sample.prototype.showName = function() {
alert('Name: ' + this.name);
}
// function, which sets the name
Sample.prototype.setName = function(name) {
this.name = name;
}
// you just export your Object and override the methods as prototypes
module.exports = Sample;


you could use you module like this:


// reference the module
var SampleModule = require('/ui/common/ObjectModule');
// Create a sample Object
var sam = new SampleModule('Fred');
// call a Method
sam.showName();

// change the internal name
sam.setName('Hugo');
sam.showName();













Dienstag, 21. August 2012

Avoid the git username password prompt

Coming from cvs and svn I tend to clone git repos with https, which work but ask for the username password every time you connect.
To avoid the prompt you should use the ssh url an be done with it. If you already use a repo and want to switch to ssh follow the following steps



1. git remote show origin
Password for 'https://username@bitbucket.org': 
* remote origin
  Fetch URL: https://username@bitbucket.org/username/reponame.git
  Push  URL: https://username@bitbucket.org/username/reponame.git
  HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)
2. git remote set-url origin git@bitbucket.org:username/reponame.git

3. git remote show origin
* remote origin
  Fetch URL: git@bitbucket.org:username/reponame.git
  Push  URL: git@bitbucket.org:username/reponame.git
  HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

You can easily get the URL for your repo from your Github, bitbucket or wherever you are hosting your repo. If you get a response i.e. like this


Permission denied (publickey).
fatal: The remote end hung up unexpectedly

then you might forgot to put your ssh key on the github repo server.



Dienstag, 17. Juli 2012

Timeout für das Umschalten auf die Voicemail einstellen


Wie stelle ich die Dauer für das Umschalten auf die Voicemail (IPhone) bei T-Mobil/Telekom ein?

**61*3311*11*XX#

eingeben. Wobei unter XX die Dauer eingestellt werden kann 5, 10, 15, 20, 25 oder 30 Sekunden.


**61*3311*11*20#

schaltet z.B. die Voicemail nach 20 Sekunden klingeln lassen ein.

Freitag, 24. Februar 2012

Quick ref of managed Beans config in Spring

Within your service


@ManagedResource
(objectName="bean:name=SampleService",
description="Properties Service", log=true)
public class SampleImpl implements ISampleService

      @ManagedAttribute
      public void setName(String name) {
            ...
      }


Within your startup of your weblogic or whatever app container

 
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=8088
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false



Startup jconsole and enter the hostname and the port within the "Remote Process" field.

done.


The full address to the remote process is

service:jmx:rmi:///jndi/rmi://SERVERNAME:PORT/jmxrmi



Donnerstag, 9. Februar 2012

Buffered File writing Snip

        byte[] content  = "Content is overrated".getBytes();
        String filename = "C:/temp/hirsch." + lieferung.getFormat();
        BufferedOutputStream bos = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File(filename));
            bos = new BufferedOutputStream(fos);
            bos.write(content);
        } catch (Exception e) {
            LOG.error("Write Exception" , e);
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                    bos.close();
                } catch (Exception e) {
                    LOG.error("Close or Flush Exception" , e);
                }
            }
        }

Donnerstag, 26. Januar 2012

Database table history with triggers

Here is a short sample about keeping all data of a table within a history table. The way I prefer it to do is via database triggers. Lets assume you have a table called:

CREATE TABLE BOOK {
  • BOOK_ID       NUMBER(10),
  • NAME             VARCHAR2(10),
  • AUTHOR         VARCHAR2(10),
  • ISBN                VARCHAR2(13)
}

Your application as well as your database scripts are working on that table. Your aim is to keep track on all changes on that table. To do so you need a history table, which looks pretty much the same as the original table and you have to add to fields to your original table:

CREATE TABLE BOOK {
  • BOOK_ID                NUMBER(10),
  • NAME                      VARCHAR2(10),
  • AUTHOR                  VARCHAR2(10),
  • ISBN                         VARCHAR2(13)
  • CHANGE_DATE      DATE,
  • CHANGE_USER      VARCHAR2(20)
}

CREATE TABLE BOOK_HISTORY {
  • BOOK_ID                NUMBER(10),
  • NAME                      VARCHAR2(10),
  • AUTHOR                  VARCHAR2(10),
  • ISBN                         VARCHAR2(13)
  • CHANGE_DATE      DATE,
  • CHANGE_USER      VARCHAR2(20),
  • ACTION                   VARCHAR2(100)
}
and create db triggers for all manipulations to the original table:

CREATE OR REPLACE TRIGGER BOOK_INSERT
       BEFORE INSERT ON BOOK
       FOR EACH ROW
BEGIN
   INSERT INTO BOOK_HISTORY
                    (BOOK_ID, NAME, AUTHOR, ISBN, 
                     CHANGE_DATE, CHANGE_USER, ACTION)
    VALUES (:new.BOOK_ID,:new.NAME, :new.AUTHOR, :new.ISBN, 
                      :new.CHANGE_DATE, :new.CHANGE_USER, 'INSERTED');
 END;


CREATE OR REPLACE TRIGGER BOOK_CHANGE
       BEFORE UPDATE ON BOOK
       FOR EACH ROW
BEGIN
   INSERT INTO BOOK_HISTORY
                    (BOOK_ID, NAME, AUTHOR, ISBN, 
                     CHANGE_DATE, CHANGE_USER, ACTION)
    VALUES (:old.BOOK_ID, :old.NAME, :old.AUTHOR, :old.ISBN, 
                      :old.CHANGE_DATE, :old.CHANGE_USER, 'CHANGED');
 END;

CREATE OR REPLACE TRIGGER BOOK_DELETE
       BEFORE DELETE ON BOOK
       FOR EACH ROW
BEGIN
   INSERT INTO BOOK_HISTORY
                    (BOOK_ID, NAME, AUTHOR, ISBN, 
                     CHANGE_DATE, CHANGE_USER, ACTION)
    VALUES (:old.BOOK_ID, :old.NAME, :old.AUTHOR, :old.ISBN, 
                      :old.CHANGE_DATE, :old.CHANGE_USER, 'DELETED');
 END;


These are three simple triggers which will fire if someone (application, scripts or whatever) will change the book table. You might write more sophisticated triggers like WHERE clauses or a CHANGE_FIELD and CHANGE_VALUE column.

Donnerstag, 25. August 2011

Spring Source Tool STS 2.7.1 and Grails

There are several pitfall you can win if you start using STS behind a proxy. Here is my shit list :-)

Install Groovy and Grails support in STS
After downloading STS 2.7 most of us would try to install the Grails and Groovy Support on the Extension tab of the STS. This will fail if you are behind a proxy. They claim to fix it in later versions. Till then just do the following:
  1. Adjust your network settings within the STS Window->Prefs->network according to your proxy
  2. Go to Help->Install New Software and http://download.eclipse.org/mylyn/snapshots/3.6 as a new site
  3. Install the MyLyn Task List Feature
  4. Restart
you should now be able to use the extension tab.

Install Grails plugins
If you try to install Grails plugins behind a proxy or firewall i.e. like

grails install-plugin calendar
 
you might get an error. To workaround this set the Proxy settings for grails 
within the  ProxySettings.groovy wihtin your .grails folder in your home dir. 
Or you go the grails command line way like that:
grails add-proxy aproxy "--host=myproxy.de" "--port=8008" "--username=myusername" "--password=mypassword" 
grails set-proxy aproxy 
 
That should create a valid ProxySettings.groovy and activate the proxy. 
Even the STS integrated Grails plugin manager should work now.