vendredi 8 mai 2015

How to implement a draggable ExtendedOverlayItem on OSMDroid?

I'm developing a feature to drag a map overlay (using ExtendedOverlayItem class), using osmdroid and OSMBonusPack.

This question talks about a possible solution:

Unable to implement onTouchEvent (Drag & Drop) with Osmdroid

So, my questions are:

1 - Where do I put that code?

2 - Should I create a new class? extending from which other class?

Additional Similar questions:

How do you implement OverlayItem to be draggable? (Using ItemizedIconOverlays if possible)

confusion between overlay, overlayitem and itemizedoverley

MouseListener on a drawString() Method

How can I detect if the text ("Resume", "Restart", "Quit") that I drew with a drawString() method is being clicked?

My code so far:

public class Pause {

    public Pause() {

    }


    public void draw(Graphics2D g) {

        g.setFont(new Font("Arial", Font.BOLD, 14));
        int intValue = Integer.parseInt( "ff5030",16);      
        g.setColor(new Color(intValue));

        g.drawString("Resume", 200, 156);
        g.drawString("Restart", 200, 172);
        g.drawString("Quit", 200, 188);    
    }
}

I hope you can help me. Thanks

@aioobe I tried with your solution:

public void draw(Graphics2D g) {

    g.setFont(new Font("Arial", Font.BOLD, 14));
    int intValue = Integer.parseInt( "ff5030",16);      
    g.setColor(new Color(intValue));

    g.drawString("Resume", 200, 156);
    setResumeRect(g.getFontMetrics().getStringBounds("Resume", g));

    g.drawString("Restart", 200, 172);
    g.drawString("Quit", 200, 188);
}

public void mouseClicked(MouseEvent e) {
    if (getResumeRect().contains(e.getPoint())) {
        System.out.println("clicked");
    }
    System.out.println(getResumeRect());
    System.out.println(e.getPoint());
}

But getResumeRect().contains(e.getPoint()) throws a NullPointerExcpetion.

I also printed resumeRect.contains and mouseEvent.getPoint() with the following result:

java.awt.geom.Rectangle2D$Float[x=0.0,y=-12.902832,w=57.0,h=16.098633] java.awt.Point[x=549,y=470]

Can't open executable installed after running Netbeans generated installer

I have created an installer for my Java project using the tools provided with Netbeans. I have created both a .msi and a .exe using the instructions from Netbeans' documentation. The installers themselves work fine, they install the program and give me uninstall support through the Windows uninstaller. The problem lies with the fact that when I run the program that it installs nothing happens. I click it, the computer hangs for a split second like it is going to open something, and then nothing. I have checked the applications and processes that are running and there is not indication that anything is running either. Is there something else that I need to do after I use Netbeans' tools to create these installers?

To create the .msi, Netbeans uses WiX. For the .exe it uses Inno Setup. I am running Windows 7 Professional.

How to handle transaction rollback with JMS and JPA in a Java EE environment?

The default rollback behavior for a CMT MDB is to return the message to the destination so it may be processed again.

Is it possible to avoid redelivering a message handled by a managed MDB even if the the transaction is rolled back? (Or maybe configure the acknowledgement behavior handled by the container).

So far I came up with the following alternatives:

  1. Isolate the business transaction from the message transaction - I could use TransactionAttributeType.REQUIRES_NEW on the business method but it creates a scenario where the business event MAY be processed twice, since the message could potentially not be acknowledged after business transaction success.
  2. Use BMT - Same problem as above since the transaction will be separated from the message transaction.
  3. Handle delivery failures using the JMS Server proprietary configuration - I would like to keep this logic inside the application if possible. Also I would have to handle it for all Queues since WebLogic default config is to redeliver the message forever.

After reading this tutorial I am still not sure on how to solve this, but so far controlling message delivery failure using proprietary WebLogic Console seems the correct option. In this case, set a limit to the redelivery on Queues - for example: 3 attempts. It will have a processing overhead since an invalid business event is likely to fail all 3 times, but I can guarantee the system integrity.

What do you guys think?

Details

I have an MDB that integrates with a business transaction and it uses JPA (EclipseLink in WebLogic 10.3.6). Everything is running with CMT and the transaction is distributed. Transaction and message acknowledgement is controlled by the container.

If an exception occurs within the JPA provider (example: null value for a not null column) the message is being redelivered since the provider is rolling back the transaction and the message is not acknowledged. It doesn't matter if I catch the exception or not, EclipseLink is rolling back the transaction anyway. I understand that this is the correct behavior for JPA.

Also, using the MessageDrivenContext.getRollbackOnly() returns false. I would expect it to be true.

If I execute my business method with TransactionAttributeType.REQUIRES_NEW the transaction is rolledback and message is not redelivered BUT the message processing transaction would be separate and that is also not desired. I did set up a JDBC store to persist the messages in a database.

I will leave some dummy classes to illustrate my point.

MDB message processing

After extracting the payload I forward it to a session bean to handle persistence logic.

public void onMessage(Message message) {

    try {
        // Extract the payload
        TextMessage txtMsg = (TextMessage) message;
        String employeeName = txtMsg.getText();

        // Call service
        service.createEmployee(employeeName);

    } catch (Exception e) {
        e.printStackTrace();            
    } finally {
        // When the JPA provider rollbacks back the transaction, this value
        // is still "false"
        log.info(String.format("Rollback only: [%s]", mdContext.getRollbackOnly()));
    }
}

Forcing an exception to the JPA provider

Forcing the error by leaving null in the not null field.

// Message and business will run in the same transaction
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public void createEmployee(String name) {

    Employee employee = new Employee();
    employee.setName(null); // Null value to force constraint error

    try {
        // This part triggers the exception within the JPA provider, and the
        // Java EE transaction is rolledback and forces the JMS message to be
        // redelivered.
        em.persist(employee);

    } catch (Exception e) {
        // Capturing the exception does not affect the rollback behavior
        e.printStackTrace();
    }
}

This is the error thrown by EclipseLink. It is wrapped in a RuntimeException so it is a System exception and the transaction will rollback.

javax.ejb.EJBTransactionRolledbackException: EJB Exception: ; nested exception is: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.1.v20111018-r10243): org.eclipse.persistence.exceptions.DatabaseException

Check for differences between two (large) files

I want to write a relatively simple program, that can backup files from my computer to a remote location and encrypt them in the process, while also computing a diff (well not really...I'm content with seeing if anything changed at all, not so much what has changed) between the local and the remote files to see which ones have changed and are necessary to update.

I am aware that there are perfectly good programs out there to do this (rsync, or others based on duplicity). I'm not trying to reinvent the wheel, it's just supposed to be a learning experience for myself

My question is regarding to the diff part of the project. I have made some assumptions and wrote some sample code to test them out, but I would like to know if you see anything I might have missed, if the assumptions are just plain wrong, or if there's something that could go wrong in a particular constelation.

Assumption 1: If files are not of equal length, they can not be the same (ie. some modification must have taken place)
Assumption 2: If two files are the same (ie. no modification has taken place) any byte sub-set of these two files will have the same hash
Assumption 3: If a byte sub-set of two files is found which does not result in the same hash, the two files are not the same (ie. have been modified)

The code is written in Java and the hashing algorithm used is BLAKE-512 using the java implementation from Marc Greim.
_File1 and _File2 are 2 files > 1.5GB of type java.io.File

public boolean compareStream() throws IOException {
    int i = 0;
    int step = 4096;
    boolean equal = false;

    FileInputStream fi1 = new FileInputStream(_File1);      
    FileInputStream fi2 = new FileInputStream(_File2);

    byte[] fi1Content = new byte[step];
    byte[] fi2Content = new byte[step];

    if(_File1.length() == _File2.length()) { //Assumption 1
        while(i*step < _File1.length()) {   

            fi1.read(fi1Content, 0, step); //Assumption 2
            fi2.read(fi2Content, 0, step); //Assumption 2

            equal = BLAKE512.isEqual(fi1Content, fi2Content); //Assumption 2

            if(!equal) { //Assumption 3
                break;
            }

            ++i;
        }
    }

    fi1.close();
    fi2.close();
    return equal;
}

The calculation for two equal 1.5 GB files takes around 4.2 seconds. Times are of course much shorter when the files differ, especially when they are of different length since it returns immediately.

Thank you for your suggestions :)
..I hope this isn't too broad

How to stop while loop after back button is hit

I have tried so many ways of solving my problem, but still no success.

I have a method, which returns me a string value and I am using it to update textView on my screen like this:

outCPU.setText(getCpuInfo());

Which would be fine, but I need to update this textView until back button was pressed.

I guess I need a while loop which starts after activity has been created and stops after back button was pressed. This loop should be in a new thread, because I have to load the activity first and execute the loop in another thread so the executing won't affect main thread and loading of the activity.

As I've already said, I don't know how to do this properly even though I have spent few hours on it.

Could someone show me an example how to get this done? Thanks!

Application takes very long to terminate

We have writen a console application (will be used as service) that starts several worker threads for handling requests coming in via mina. The application leaves the main loop when a stop signal is received on a specific network port. This is the intended way of stoping the service. That works quite ok, but when the stop signal is received the process of the application does not terminate immediatly (takes up to 5 minutes). We verified via log messages that the main function is left quickly and as expected and all threads created by the application are also terminated. But the application keeps on running.

The threads still running before leaving the main function are:

Signal Dispatcher (java.lang.Thread)
Finalizer (java.lang.ref.Finalizer$FinalizerThread)
Abandoned connection cleanup thread (com.mysql.jdbc.AbandonedConnectionCleanupThread)
main (java.lang.Thread)
pool-2-thread-1 (java.lang.Thread)
Reference Handler (java.lang.ref.Reference$ReferenceHandler)

We are currently using the following java version:

java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)

The operation system is ubuntu 14.04 LTS.

I have no clue about this behaviour and i hope for some hints on how to investigate that problem further.

Addtional Information

I have produced a Full thread dump as suggested. Four threads are waiting:

"pool-2-thread-1" prio=10 tid=0x00007fd7fc51f000 nid=0x16200 waiting on condition [0x00007fd800318000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000000cceaf660> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:226)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:359)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:942)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

"Abandoned connection cleanup thread" daemon prio=10 tid=0x00007fd7fc23d800 nid=0x161e2 in Object.wait() [0x00007fd800cbb000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000dc2af720> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
    - locked <0x00000000dc2af720> (a java.lang.ref.ReferenceQueue$Lock)
    at com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:41)

"Finalizer" daemon prio=10 tid=0x00007fd7fc066000 nid=0x161d6 in Object.wait() [0x00007fd801bd6000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000dc03c060> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
    - locked <0x00000000dc03c060> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" daemon prio=10 tid=0x00007fd7fc064000 nid=0x161d5 in Object.wait() [0x00007fd801cd7000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000dc03c108> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:503)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
    - locked <0x00000000dc03c108> (a java.lang.ref.Reference$Lock)

Can someone confirm, that I should investigate towards pool-2-thread-1? I'm unsure how to interpret the result.