android apk NoClassDefFoundError (gradle build)

My android application is build with gradle and my apk is generated and works correctly.
After some developpement iterations, i include android-support-v4.jar library to ide project and gradle build file like following:

compile files('libs/android-support-v4.jar')

Build with gradle and install apk on avd ==> NoClassDefFoundError (class which extends class located in android-support-v4.jar library)

Solution:

./gradlew clean

And it works again

onSwipe listener without using Swipe Views

1. create SimpleGestureFilter class containing interface SimpleGestureListener

package net.witr.swipe.ui;

import android.app.Activity;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;

public class SimpleGestureFilter extends SimpleOnGestureListener{

    public final static int SWIPE_UP    = 1;
    public final static int SWIPE_DOWN  = 2;
    public final static int SWIPE_LEFT  = 3;
    public final static int SWIPE_RIGHT = 4;

    public final static int MODE_TRANSPARENT = 0;
    public final static int MODE_SOLID       = 1;
    public final static int MODE_DYNAMIC     = 2;

    private final static int ACTION_FAKE = -13; //just an unlikely number
    private int swipe_Min_Distance = 100;
    private int swipe_Max_Distance = 1000;
    private int swipe_Min_Velocity = 0;

    private int mode             = MODE_DYNAMIC;
    private boolean running      = true;
    private boolean tapIndicator = false;

    private Activity context;
    private GestureDetector detector;
    private SimpleGestureListener listener;

    public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {

        this.context = context;
        this.detector = new GestureDetector(context, this);
        this.listener = sgl;
    }

    public void onTouchEvent(MotionEvent event){

        if(!this.running)
            return;

        boolean result = this.detector.onTouchEvent(event);

        if(this.mode == MODE_SOLID)
            event.setAction(MotionEvent.ACTION_CANCEL);
        else if (this.mode == MODE_DYNAMIC) {

            if(event.getAction() == ACTION_FAKE)
                event.setAction(MotionEvent.ACTION_UP);
            else if (result)
                event.setAction(MotionEvent.ACTION_CANCEL);
            else if(this.tapIndicator){
                event.setAction(MotionEvent.ACTION_DOWN);
                this.tapIndicator = false;
            }

        }
        //else just do nothing, it's Transparent
    }

    public void setMode(int m){
        this.mode = m;
    }

    public int getMode(){
        return this.mode;
    }

    public void setEnabled(boolean status){
        this.running = status;
    }

    public void setSwipeMaxDistance(int distance){
        this.swipe_Max_Distance = distance;
    }

    public void setSwipeMinDistance(int distance){
        this.swipe_Min_Distance = distance;
    }

    public void setSwipeMinVelocity(int distance){
        this.swipe_Min_Velocity = distance;
    }

    public int getSwipeMaxDistance(){
        return this.swipe_Max_Distance;
    }

    public int getSwipeMinDistance(){
        return this.swipe_Min_Distance;
    }

    public int getSwipeMinVelocity(){
        return this.swipe_Min_Velocity;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {

        final float xDistance = Math.abs(e1.getX() - e2.getX());
        final float yDistance = Math.abs(e1.getY() - e2.getY());

        if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
            return false;

        velocityX = Math.abs(velocityX);
        velocityY = Math.abs(velocityY);
        boolean result = false;

        if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
            if(e1.getX() > e2.getX()) // right to left
                this.listener.onSwipe(SWIPE_LEFT);
            else
                this.listener.onSwipe(SWIPE_RIGHT);

            result = true;
        }
        else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
            if(e1.getY() > e2.getY()) // bottom to up
                this.listener.onSwipe(SWIPE_UP);
            else
                this.listener.onSwipe(SWIPE_DOWN);

            result = true;
        }

        return result;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        this.tapIndicator = true;
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent arg) {
        this.listener.onDoubleTap();;
        return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent arg) {
        return true;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent arg) {

        if(this.mode == MODE_DYNAMIC){        // we owe an ACTION_UP, so we fake an
            arg.setAction(ACTION_FAKE);      //action which will be converted to an ACTION_UP later.
            this.context.dispatchTouchEvent(arg);
        }

        return false;
    }

    static interface SimpleGestureListener{
        void onSwipe(int direction);
        void onDoubleTap();
    }

}

And then, your Activity must implement SimpleGestureListener interface like following

import com.android.swipe.R;
import net.witr.swipe.SimpleGestureFilter.SimpleGestureListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
 
public class WitrActivity extends Activity implements SimpleGestureListener{

    private SimpleGestureFilter detector;
          
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.witr);
          
        // Detect touched area 
        detector = new SimpleGestureFilter(this,this);
    }
          
    @Override
    public boolean dispatchTouchEvent(MotionEvent me){
        // Call onTouchEvent of SimpleGestureFilter class
         this.detector.onTouchEvent(me);
       return super.dispatchTouchEvent(me);
    }

    @Override
    public void onSwipe(int direction) {

      String str = "";
      
      switch (direction) {
      
      case SimpleGestureFilter.SWIPE_RIGHT :
          str = "Swipe Right";
          break;
      case SimpleGestureFilter.SWIPE_LEFT :
          str = "Swipe Left";
          break;
      case SimpleGestureFilter.SWIPE_DOWN :
          str = "Swipe Down";
          break;
      case SimpleGestureFilter.SWIPE_UP :
          str = "Swipe Up";
          break;      
      }

      Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

    }
      
    @Override
    public void onDoubleTap() {
        Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
    }
          
}

Reference : here

profile remote host jboss7 with jprofiler

local machine
– create ssh tunnel : ssh -L 8849:127.0.0.1:8849 remoteuser@remotehost
– launch jprofiler : e.g. /mnt/jprofiler7/bin/jprofiler
– new session -> remote host -> enter host 127.0.0.1 as port 8849 -> save session (don’t start session you must accomplish remote host configuration and restart server before)

remote host (linux x64)
– install(unzip) jprofiler in any folder in remote host file system : e.g. /opt/jprofiler
– edit $JBOSS_HOME/bin/standlaone.sh and add following (this will launch jprofiler agent uppon jboss server. jprofiler agent will listen on port 8849)

export JAVA_OPTS="$JAVA_OPTS -agentpath:/opt/jprofiler/bin/linux-x64/libjprofilerti.so=port=8849"

– restart jboss server

local machine
– start jprofiler saved session

That’s all

want to handle json in Java : play with javax.json

First get libraries
With maven for example add these two artifacts

        
        
            javax.json
            javax.json-api
            1.0
        

        
        
            org.glassfish
            javax.json
            1.0.4
        

Parse json String variable (event processing)


    String json = "{"name":"witr","quotes":{"java":"150","linux":"200"}}";

    JsonParserFactory factory = Json.createParserFactory(null);
    JsonParser parser = factory.createParser(new StringReader(json));

    while (parser.hasNext()) {
        JsonParser.Event event = parser.next();

        switch (event) {
            case KEY_NAME: {
                String key = parser.getString();
                System.out.print(key + "="); break;
            }
            case VALUE_STRING: {
                String value = parser.getString();
                System.out.println(value); break;
            }
        }
    }
    
    // output :
    // name=witr
    // quotes=java=150
    // linux=200

    String json = "{"name":"witr","quotes":{"java":150,"linux":200}}";

    JsonReader jsonReader = Json.createReader(new StringReader(json));
    JsonObject jsonObject = jsonReader.readObject();
    System.out.println("name : "+jsonObject.getString("name"));
    System.out.println("quotes : "+jsonObject.getJsonObject("quotes"));
    System.out.println("java : "+jsonObject.getJsonObject("quotes").getInt("java"));
    System.out.println("linux : "+jsonObject.getJsonObject("quotes").getInt("linux"));

    // output :
    // name : witr
    // quotes : {"java":150,"linux":200}
    // java : 150
    // linux : 200

Hibernate exception : cannot simultaneously fetch multiple bags

Problem

Exception class : org.hibernate.loader.MultipleBagFetchException
Exception : cannot simultaneously fetch multiple bags

Solution

Use @LazyCollection(LazyCollectionOption.FALSE) rather than fetch=FetchType.EAGER
Annotation @LazyCollection(LazyCollectionOption.FALSE) makes that collecion is loaded like with FetchType.EAGER and you can use it on two and more collections.

Example

Initial Code : Works with lazy fetch type

public class WitrEntity{

    private Set witrEntityLabels = new HashSet(0);

    [...]

    @OneToMany(fetch=FetchType.LAZY, mappedBy="witrEntity")
    public Set getWitrEntityLabels() {
        return this.witrEntityLabels;
    }

}

public class WitrEntityLabel{

    private WitrEntity witrEntity;

    [...]

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="WITR_ENTITY_ID", nullable=false, insertable=false, updatable=false)
    public WitrEntity getWitrEntity() {
        return this.witrEntity;
    }

}

Wrong manipulation : wanna set fetch type to eager

public class WitrEntity{

    private Set witrEntityLabels = new HashSet(0);

    [...]

    @OneToMany(fetch=FetchType.EAGER, mappedBy="witrEntity") // THIS IS THE CAUSE OF EXCEPTION
    public Set getWitrEntityLabels() {
        return this.witrEntityLabels;
    }

}

public class WitrEntityLabel{

    private WitrEntity witrEntity;

    [...]

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="WITR_ENTITY_ID", nullable=false, insertable=false, updatable=false)
    public WitrEntity getWitrEntity() {
        return this.witrEntity;
    }

}

Solution : if you want to force loading collection

public class WitrEntity{

    private Set witrEntityLabels = new HashSet(0);

    [...]

    @OneToMany(mappedBy="witrEntity") // delete fetch=FetchType.LAZY
    @LazyCollection(LazyCollectionOption.FALSE) // add use @LazyCollection false
    public Set getWitrEntityLabels() {
        return this.witrEntityLabels;
    }
}

XSLT java debug

You may need some debug message to be logged in standard output

java debug class

package net.witr.xslt;

public class XslDebug {

    public static void debug(String msg){
        System.out.println(msg);
    }

}

xsl code


  ..
  
    
    
    
  
  ..

Apache POI : delete excel empty rows

POI method sheet.removeRow(), removes row cells but doesn’t clear them from excel output.
Means if you have three rows and you apply sheet.removeRow(1), you will have:
– not changed first row
– empty second row
– not changed third row

So to remove row completly you must then shift rows following.
But for some reason sheet.shiftRows() poi api method doesn’t work for me.
Code bellow do it

    public void deleteEmptyRows(){
        SXSSFSheet sheet = (SXSSFSheet)sh;
        for ( int r=sheet.getLastRowNum(); r >= 0; r-- ){
            Row row     = sheet.getRow( r );

            // if no row exists here; then nothing to do; next!
            if ( row == null )
                continue;

            int lastColumn = row.getLastCellNum();
            boolean rowToDelete = true;
            if(lastColumn > -1){
                for ( int x=0; x < lastColumn + 1; x++ ){
                    Cell cell    = row.getCell(x);
                    if ( cell != null && cell.getStringCellValue() != null){
                        String cellTrimValue = cell.getStringCellValue().trim();
                        if(!cellTrimValue.isEmpty()){
                            rowToDelete = false;
                            break;
                        }
                    }
                }
            }

            if(rowToDelete){
                if(r == sheet.getLastRowNum()){
                    sheet.removeRow(row);
                }else{
                    sheet.removeRow(row);
                    for(int j= r+1; j <= sheet.getLastRowNum(); j++){
                        Row rowToShift = sheet.getRow(j);
                        rowToShift.setRowNum(j-1);
                    }
                }
            }
        }
    }

Apache POI : delete list of excel columns / keep only list of excel columns

First you must got code from here

Remove some columns with provided headers

    public void deleteColumnsWithHeader(String columnHeader){
        SXSSFSheet sheet = (SXSSFSheet)sh;
        Row row     = sheet.getRow( 0 );
        if ( row == null ){
            return;
        }

        int lastColumn = row.getLastCellNum();

        for ( int x=lastColumn; x >= 0; x-- ){
            Cell headerCell    = row.getCell(x);
            if ( headerCell != null && headerCell.getStringCellValue() != null && 
                 headerCell.getStringCellValue().equalsIgnoreCase(columnHeader)){
                deleteColumn(x);
            }
        }
    }

Keep only columns with provided headers

    public void keepOnlyColumnsWithHeaders(List columnHeaders){
        SXSSFSheet sheet = (SXSSFSheet)sh;
        Row row     = sheet.getRow( 0 );
        if ( row == null ){
            return;
        }

        int lastColumn = row.getLastCellNum();

        for ( int x=lastColumn; x >= 0; x-- ){
            Cell headerCell    = row.getCell(x);
            if ( headerCell != null && headerCell.getStringCellValue() != null && 
                 !columnHeaders.contains(headerCell.getStringCellValue())){
                deleteColumn(x);
            }
        }
    }

Apache POI : remove excel columns

<

div>
Unfortunatly there was no method to remove excel columns in poi api.
Code bellow (found here) can help

    public void deleteColumn(SXSSFSheet sheet, int columnToDelete){        
        int maxColumn = 0;
        for ( int r=0; r  maxColumn )
                maxColumn = lastColumn;

            if ( lastColumn < columnToDelete )
                continue;

            for ( int x=columnToDelete+1; x < lastColumn + 1; x++ ){
                Cell oldCell    = row.getCell(x-1);
                if ( oldCell != null )
                    row.removeCell( oldCell );

                Cell nextCell   = row.getCell( x );
                if ( nextCell != null ){
                    Cell newCell    = row.createCell( x-1, nextCell.getCellType() );
                    cloneCell(newCell, nextCell);
                }
            }
        }
    }

    private void cloneCell( Cell cNew, Cell cOld ){
        cNew.setCellComment( cOld.getCellComment() );
        cNew.setCellStyle( cOld.getCellStyle() );

        switch ( cNew.getCellType() ){
            case Cell.CELL_TYPE_BOOLEAN:{
                cNew.setCellValue( cOld.getBooleanCellValue() );
                break;
            }
            case Cell.CELL_TYPE_NUMERIC:{
                cNew.setCellValue( cOld.getNumericCellValue() );
                break;
            }
            case Cell.CELL_TYPE_STRING:{
                cNew.setCellValue( cOld.getStringCellValue() );
                break;
            }
            case Cell.CELL_TYPE_ERROR:{
                cNew.setCellValue( cOld.getErrorCellValue() );
                break;
            }
            case Cell.CELL_TYPE_FORMULA:{
                cNew.setCellFormula( cOld.getCellFormula() );
                break;
            }
        }

    }