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.

using doxygen for java with Doxywizard

Doxywizard Doxygen not scanning the packages for java files

Need help on Doxygen/Doxywizard

These are my Doxywizard settings:

Working directory from where doxygen will run:

C:/Program Files/doxygen

In 'Wizard' tab, the below values are set. Source code directory:

C:/workspace/git/employeeapp/src/main/java

Destination directory:

C:/Doxy-docs/1

In 'Expert' tab, under Topics-'Build' , selected the 'EXTRACT_ALL'

I installed Doxywizard, open the wizard, set the above values, went to 'Run' tab and clicked 'Run doxygen', I expected that all the folders/packages inside the 'src/main/java' will be scanned and a project default documentation would be created.

Problem: However I see that 'C:/Doxy-docs/1/html/index.html' is blank and no other pages were created.

If I just navigate to a folder where there is a '.java' file [say src/main/java/com/app/], documentation is created for the '.java' files inside that folder. But as in the above scenario where 'src/main/java' is mentioned, the tool is not scanning for packages/folders inside for the '*.java' files.

Question: Am I missing some configuration? or is this the expected functionality of Doxygen that it cannot scan inside folder-folder etc?

Note: This link shows thefeatures of Doxygen and from that I think it support the feature that I am expecting. http://ift.tt/1cnoUo8

Note: I added java tag only because I am using the wizard to scan java files

Memory leaks in Android handler

I am trying to read data from a serial bluetooth stream in my android application. The data is send to a handler to display it. It works fine for a few minutes and then it stops showing data (The app keeps running however). I think it has to do with memory leaks in my handler but I don't know how to solve it..

This is where I found the code

I will be so happy if someone can help me. Thanks in advance

public class MainActivity extends ActionBarActivity {

    static BluetoothAdapter mBluetoothAdapter = null;
    static Handler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Does the device support bluetooth?
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Device does not support Bluetooth",Toast.LENGTH_LONG).show();
        }

        //Turn on Bluetooth if disabled
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

        //Get the Bluetooth module device
        BluetoothDevice mDevice = null;
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if(device.getName().equals("HC-06")) {
                    mDevice = device;
                }
            }
        }
        if(mDevice == null){
            Toast.makeText(this,"Device not found",Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(this,"connected to " + mDevice.getName(),Toast.LENGTH_LONG).show();

            ConnectThread mConnectThread = new ConnectThread(mDevice);
            mConnectThread.start();

            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    byte[] writeBuf = (byte[]) msg.obj;
                    int begin = (int)msg.arg1;
                    int end = (int)msg.arg2;
                    switch(msg.what) {
                        case 1:
                            String writeMessage = new String(writeBuf);
                            writeMessage = writeMessage.substring(begin, end);

                            ScrollView scrollView1 = (ScrollView) findViewById(R.id.scroll);
                            TextView textView1 = (TextView) findViewById(R.id.statusText);
                            textView1.append(writeMessage + "\n");
                            scrollView1.fullScroll(View.FOCUS_DOWN);

                            break;
                    }
                }
            };
    }
}

Jquery script to call Servlet - can't get corret URL of Servlet

Below, there is jquery script which calls Servlet by URL. At first i need to say that i have 2 separate projects. First is Dynamic Web Project which contains servlets etc. Second is simple Ratchet HTML-CSS-JS Project which of course contains some pages, scripts and css.

        <script>
            $(document).ready(function() {                        // When the HTML DOM is ready loading, then execute the following function...
                $('#button').click(function() {               // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
                    $.get('http://localhost:8080/testuje/text', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                        $('#div').text(responseText);         // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                    });
                });
            });
        </script>

Here is my Servlet code:

package pl.javastart.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/text")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = "some text";

        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
        response.getWriter().write(text);
        // Write response body.
    }
}

The problem is, what should i put in $.get('http://localhost:8080/testuje/text', function(responseText)

to get servlet content after button click.

Java: Error creating bean with name 'loadTimeWeaver'?

I am currently working on a maven project but every time i try to deploy my war i get the exception below:

ERROR [DispatcherPortlet:276] Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.weaving.AspectJWeavingEnabler#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver': Initialization of bean failed;  nested exception is java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransforme r)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1097)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:661)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
        at org.springframework.web.portlet.FrameworkPortlet.createPortletApplicationContext(FrameworkPortlet.java:356)
        at org.springframework.web.portlet.FrameworkPortlet.initPortletApplicationContext(FrameworkPortlet.java:294)
        at org.springframework.web.portlet.FrameworkPortlet.initPortletBean(FrameworkPortlet.java:268)
        at org.springframework.web.portlet.GenericPortletBean.init(GenericPortletBean.java:120)

I simply don't understand when i have everything in place properly why this error. Please checkout my declaration in POM.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.4</version>
    <configuration>
            <forkMode>once</forkMode>
            <argLine>
                 -javaagent:"path\spring-instrument-3.1.0.RELEASE.jar"
            </argLine>
            <useSystemClassloader>true</useSystemClassloader>
    </configuration>
</plugin>

Please guide.

Creating EntityManagerFactory from hibernate Configuration

In our current application (java se) we use Hibernate specific api, but we kind of want to migrate to JPA wherever possible (but slowly). For that, I need EntityManagerFactory instead of SessionFactory (and I would like to keep this an axiom without dispute).

Where is the problem is, that currently our session factory is being created from org.hibernate.cfg.Configuration and I would like to keep it as it for now - as this configuration is passed thru different parts of our software which can and do configure the persistence as they want.

So the question is: how can I make

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( hibConfiguration.getProperties() ).buildServiceRegistry();
SessionFactory sessionFactory = hibConfiguration.buildSessionFactory( serviceRegistry );

equivalent resulting in EntityManagerFactory ?

Get Request Parameters from XML using WebFilter

I´m developing a Web Service, using Glassfish, using SOAP. I have several web methods, and I want to get introduce my webmethod name and his parameters to http head request.

For example:

I have this path:

context: WebServices

webMethod: makeSomething

parameters:a=2

So I create a class named ProfilingFilter:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, javax.servlet.ServletException {

    if (request.getContentLength() != -1 && context != null) {
        ((HttpServletResponse) response).addHeader("Operation", -->PATH+PARAMETERS);
        //  ((HttpServletResponse) response).addHeader("Operation", -->makeSomething?a=2);
    }

}

It´s possible to use servlet response or servlet request to get this information?

If not, How can I do this?

Mock a method call from another class

My code structure :

class A {
    void methodA() {
        //some code
        B b = new B();
        response = b.methodB(arg1, arg2);
        //some code using "response"
    }
}

I am UNIT testing class A and don't want to actually call methodB(). Is there any way to mock this method call by a custom response. I tried Mockito to mock this method call as below:

B classBMock = Mockito.mock(B.class);
Mockito.when(classBMock.methodB(arg1, arg2)).thenReturn(customResponse);
A objA = new A();
objA.methodA();

On calling methodA() the above way I don't get customResponse when methodB() is called within A. But when I call methodB() with classBMock, I get the customResponse. Is there anyway I can get customResponse from methodB() while calling methodA().

Why Am I Getting an IllegalStateException While Adding Bcrypt to my Spring-Security.XML file?

I have implemented bCrypt encoding on a small app I am doing. Currently, I can create a user, and encrypt the password. Prior to encryption, I could have the user login with their email address, and a plain text password stored in the DB. Now I am getting a 404 error when I simply run the application out of Eclipse.

The error only started occurring after I added the following line in my spring-security.xml file

        <password-encoder ref="encoder" />  

The error I am seeing in the console is the following.

Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder] to required type [org.springframework.security.authentication.encoding.PasswordEncoder] for property 'passwordEncoder': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)

Here is how I have Bcrypt implemented in my XML.

 <authentication-manager alias="authenticationManager">
    <authentication-provider>
    <password-encoder ref="encoder" />  
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="
            SELECT email as username, passwordConfig as password, active as enabled 
            FROM Employee
            WHERE email=?"
            authorities-by-username-query="
            SELECT email as username, role 
            FROM EmployeeLEFT OUTER JOIN Roles 
            ON Employee.RoleID=Roles.roleId 
            WHERE email=?" />
    </authentication-provider>
</authentication-manager>

<beans:bean id="encoder" 
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />

Here are my spring libraries.

antlr-2.7.6.jar
aopalliance-1.0.jar
com.springsource.org.aopalliance-1.0.0.jar
commons-beanutils-1.9.2.jar
commons-collections-3.2.1.jar
commons-digester-2.0.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-validator-4.2.0.Final.jar
javassist-3.12.0.GA.jar
javax.servlet.jar
jbcrypt-0.3m.jar
jcl-over-slf4j-1.5.8.jar
jstl-1.2.jar
jta-1.1.jar
mail-1.4.7.jar
org.springframework.aop-3.0.5.RELEASE.jar
org.springframework.asm-3.0.5.RELEASE.jar
org.springframework.aspects-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.context.support-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
org.springframework.expression-3.0.5.RELEASE.jar
org.springframework.instrument.tomcat-3.0.5.RELEASE.jar
org.springframework.instrument-3.0.5.RELEASE.jar
org.springframework.jdbc-3.0.5.RELEASE.jar
org.springframework.jms-3.0.5.RELEASE.jar
org.springframework.orm-3.0.5.RELEASE.jar
org.springframework.oxm-3.0.5.RELEASE.jar
org.springframework.test-3.0.5.RELEASE.jar
org.springframework.transaction-3.0.5.RELEASE.jar
org.springframework.web.portlet-3.0.5.RELEASE.jar
org.springframework.web.servlet-3.0.5.RELEASE.jar
org.springframework.web.struts-3.0.5.RELEASE.jar
org.springframework.web-3.0.5.RELEASE.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-core-2.5.6.jar
spring-security-acl-3.0.5.RELEASE.jar
spring-security-aspects-3.0.5.RELEASE.jar
spring-security-cas-client-3.0.5.RELEASE.jar
spring-security-config-3.0.5.RELEASE.jar
spring-security-core-3.0.5.RELEASE.jar
spring-security-crypto-3.1.1.RELEASE.jar
spring-security-ldap-3.0.5.RELEASE.jar
spring-security-openid-3.0.5.RELEASE.jar
spring-security-taglibs-3.0.5.RELEASE.jar
spring-security-web-3.0.5.RELEASE.jar
spring-web-2.5.6.jar
spring-webmvc-portlet-2.5.6.jar
sqljdbc4.jar
tiles-api-2.2.2.jar
tiles-core-2.2.2.jar
tiles-jsp-2.2.2.jar
tiles-servlet-2.2.2.jar
tiles-template-2.2.2.jar
validation-api-1.0.0.GA.jar

Android : Error receiving data on real device using WCF webservice, java.net.socketexception recvfrom failed ebadf

I m totally new to android & have a strange problem here. I m working on an application which receives data from the server running a WCF web-service.

Steps I m following :

  1. Calling the webservice.
  2. Web Service returns data in JSONArray format, thus i retrieve the HttpEntity and Response in String format.
  3. Convert the String to JSONObject and then to JSONArray to dislay in the list.

Everything is running perfect the data is retrieved, converted to JSONObject , then to JSONArray & then in listView using the BaseAdapter.

Now the problem is data gets loaded well in the emulater but when i transfer the apk file on my device/devices it starts throwing exception.

Strange fact, it runs well on the real device also till my JSONArray has like 3 to 4 objects on it. More than that if 5 to 6 objects, the app on the phone throws a java.net.socketexception recvfrom failed ebadf(Bad File Number) but the same with many objects runs flawless on the emulator *

Any Help would be great, m on a deadline and i m trying my best to learn and solve it.

Here is the class where i call the server and retrieve the string data.

public class ConnectToDB
{
    private static final String SVC_URL = "http://ift.tt/1ImcWrV";

    int statusCode = 400;
    JSONArray jsonArray;
    String result;

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String getStories()
    {
        HttpGet request = new HttpGet(SVC_URL +"liststory");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");


        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            HttpEntity responseEntity = response.getEntity();

            response = httpClient.execute(request);
            result="1";

            InputStream stream = responseEntity.getContent();
            result="2";
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(stream));
            result="3";
            StringBuilder builder = new StringBuilder();
            String line;
            result="4";
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            stream.close();
            result="5";  // Error Occurs here, cause the error log,doesn't reach 5, it prints till 4 only
            result = builder.toString();

        } catch (Exception e)
        {
            result="Error :"+e+"at "+result;
        }

        return result;


    }
}

here is the fragment which has the listview, its BaseAdapter & the AysncTask Call to call to server, here i retrieve the data from the server in String format, convert it to JSONObject to JSONArray and pass it to the adapter

public class Entertainment extends Fragment {

    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.cat_entertainment_fragment, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView = (ListView) getActivity().findViewById(R.id.entertainmentList);
        new getStoryData().execute(new ConnectToDB());

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            }
        });
    }

    public class EntertainmentListAdapter extends BaseAdapter {
        JSONArray entertainmentListArray;
        private Activity activity;
        private LayoutInflater layoutInflater;

        private EntertainmentListAdapter(JSONArray jsonArray, Activity activity) {
            this.entertainmentListArray = jsonArray;
            this.activity = activity;
            layoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return this.entertainmentListArray.length();
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            ListCell cell;
            if (view == null) {
                view = layoutInflater.inflate(R.layout.row_published_stories, null);
                cell = new ListCell();
                cell.storyID = ((TextView) view.findViewById(R.id.storyID));
                cell.storyHeader = ((TextView) view.findViewById(R.id.post_header));
                cell.storyContent = ((TextView) view.findViewById(R.id.post_description));
                cell.likes = ((TextView) view.findViewById(R.id.storyLikes));
                cell.dislikes = ((TextView) view.findViewById(R.id.storyDislike));
                cell.byline = ((TextView) view.findViewById(R.id.storyBy));
                cell.storyDate = ((TextView) view.findViewById(R.id.storyPublishedDate));
                cell.imageString = ((TextView) view.findViewById(R.id.storyImage));
                view.setTag(cell);
            } else {
                cell = (ListCell) view.getTag();
            }

            try {
                JSONObject jsonObject = this.entertainmentListArray.getJSONObject(i);
                cell.storyID.setText(jsonObject.getString("Id"));
                cell.storyHeader.setText(jsonObject.getString("StoryHeader"));
                cell.storyContent.setText(jsonObject.getString("StoryContent"));
                cell.likes.setText(jsonObject.getString("Likes"));
                cell.dislikes.setText(jsonObject.getString("Dislikes"));
                cell.byline.setText(jsonObject.getString("ByLine"));
                cell.storyDate.setText(jsonObject.getString("StoryDate"));
                cell.imageString.setText(jsonObject.getString("ImageUrl"));

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return view;
        }
    }


    void setAdapter(JSONArray array) {
        listView.setAdapter(new EntertainmentListAdapter(array, getActivity()));
    }

    private class ListCell {
        TextView likes, dislikes, storyHeader, storyContent, byline, storyID, storyDate, imageString;
        CircularImageView storyImage;
    }

    class getStoryData extends AsyncTask<ConnectToDB, Void, String> {

        private final ProgressDialog dialog = new ProgressDialog(getActivity());

        @Override
        protected String doInBackground(ConnectToDB... params) {
            return params[0].getStories();

        }

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Loading data");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            try {
                if (result.startsWith("E")) {
                    Toast.makeText(getActivity(), "Check Your Internet Connection.", Toast.LENGTH_LONG).show();
                    this.dialog.dismiss();
                } else {

                    this.dialog.dismiss();
                    JSONObject jObject = new JSONObject(result);
                    JSONArray jArray = jObject.getJSONArray("ListStoryResult");
                    setAdapter(jArray);
                    Toast.makeText(getActivity(), jArray.length() + " Stories Loaded.", Toast.LENGTH_LONG).show();
                }

            } catch (Exception e) {
                Toast.makeText(getActivity(), "Error :" + e, Toast.LENGTH_LONG).show();
            }

        }


    }

}

Meaning of AllowableActions in Apache Chemistry

I can't seem to find any proper explanation of the members of org.apache.chemistry.opencmis.commons.enums.Action. E.g. the CMIS spec has three definitions for canMoveObject in sec. 2.1.12.3.2.2 which one does CAN_MOVE_OBJECT refer to? Anybody got a clue?

Groeten,

Friso

Spike in Memory utilization for java multithreaded application

Environment: OS: RHEL 6.4(Santigo) Java: 1.7 RAM : 6GB

Problem: The application(Multi Threaded) is running with above system configuration. Now we are into performance testing. Actual performance test scenario is, Application will be receiving 20 Transactions Each Second. For each transactions application will be sending Packets through UDP and TCP/IP and it will be expecting responses back. We observed in all the Loads, first 1 to 3 hrs load is going is fine without any failure and application was consuming around 340MB Residual memory and 70-80% CPU. When this fine transaction in progress, in small time difference may be in 5 to 15 Seconds, application memory utilization reaching upto around 600MB and 120% of Residual and CPU respectively and after certain time memory is not coming down and CPU% came down to normal stage. During this spike in memory communication failure in between servers are started to happen. After certain time, memory came down some what(For eg 500MB) and stabling in that point. Again load moves fine without any failure. And again certain hours, it reaching to around 600MB and started to fail. Again moves fine. This case is happening at least 4 to 5 times in 12 hour load.

Need Suggestions/ideas: Need suggestion on what will cause this issue?. I am not able to conclude it is application problem since it is running fine for hours without any issue and in next 5 to 15 secs there is spike in Memory immediately. So i assume this should not be application problem. I need valuable yours suggestion/ideas to figure it out. Whether it can be server environment issue or something else? Thanks in advance.

how to read lines with java.io.File [duplicate]

This question already has an answer here:

I got a txt file and I'm using java.io.File on my code, I want to read the txt of each line, each line could has more than one word Ie

23

10

23

C34

Crew Quarters

1

1

4

false

Save Date variable by RandomAccesFile

how can I write a Date variable using RandomAccesFile in java? I know Date var is 7 bytes, but I don't know how to write it. Thanks

using Hibernate numeric restriction for a varchar column

I'm using the Hibernate Criteria in order to build queries dynamically. One of these dynamic queries uses a column stored on MySQL as a varchar. But, is a column storing prices of items (only has numeric values with decimals). So I would like to generate queries using ge le or between.

Is there a way to tell to hibernate something like "hey, this column is of type varchar, but its content is numeric so apply my numeric restrictions (please)"?

Selenium/ Java how to verify the this complex text on page

I want to verify below text(HTML code) is present on page which as // characters , etc using selenium /jav

<div class="powatag" data-endpoint="http://ift.tt/1cukko9" data-key="b3JvYmlhbmNvdGVzdDErYXBpOjEyMzQ1Njc4" data-sku="519" data-lang="en_GB" data-type="bag" data-style="bg-act-left" data-colorscheme="light" data-redirect=""></div>

Appreciate any help on this

Use WebServiceContext outside WebService

In my Web service, I have:

@WebService(serviceName = "myservice")
public class ServiceName{

    @Resource
    private WebServiceContext context;

In a stateless class I want to use the same operation:

@Stateless
public class MakeHappen{

 @Resource
        private WebServiceContext context;

But I receive an EJB exception. How can I inject this resource, outside webservice?

How to show a tables rows when an item is clicked Ina listView?

So I am working on an android app, which works with SQLite. I have a table with grade information(_id, category, itemNumber, description, grade, date). From my MainActivity, when I press a button, it takes me to gradeListActivity. This activity has a listView, which shows all the row's category(i.e. Exam, Exam, Homework, Quiz, Lab, Exam. Note I entered in my table three exams, a homework, a quiz and a lab). Upto this point works. Now when I click on an item in the ListView, it takes me to GradeDetailActivity, this is suppose to show all the other colums of the category I selected in the previous activity. My question is how can I achieve that?

Repaint method isn't working in time

I'm making a game in Java, and the repaint() method is misbehaving in a very odd way. Basically, I need to repaint the board before getting the AI's move. Here is my method where I'm calling it:

public void mouseClicked(MouseEvent e) {
    mouseX = e.getX();
    mouseY = e.getY();

    int button = e.getButton();
    if (button == MouseEvent.BUTTON1 || button == MouseEvent.BUTTON3) {
        int mouseR = (mouseY / SIZE);
        int mouseC = (mouseX / SIZE);

        if (mouseR >= 0 && mouseC >= 0 &&
                mouseR < board.length && mouseC < board[0].length) {
            if (board[mouseR][mouseC] == 3) {
                makeMove(mouseR, mouseC, playerColor);
                getValidMoves((playerColor % 2) + 1);
                repaint();
                getAIMove();
            }
        }

    }
    repaint();
}

getAIMove() is designed so it waits for a couple of seconds before making the move, so the player can see the results of their move before they see those of the AI. Unfortunately, although I call repaint() before getAIMove(), what happens is more like this: the player clicks where they want to move. Nothing appears to happen for a few seconds, then the results of the player's move AND the AI's move are displayed on the screen. What's going on?

Does it always make sense to "program to an interface" in Java?

I've seen the discussion at this question regarding how a class that implements from an interface would be instantiated. In my case, I'm writing a very small program in Java that uses an instance of TreeMap, and according to everyone's opinion there, it should be instantiated like:

Map<X> map = new TreeMap<X>();

In my program, I'm calling the function map.pollFirstEntry(), which is not declared in the Map interface (and a couple others who are present in the Map interface too). I've managed to do this by casting to a TreeMap everywhere I call this method like:

someEntry = ((TreeMap<X>) map).pollFirstEntry();

I understand the advantages of the initialization guidelines as described above for large programs, however for a very small program where this object would not be passed to other methods, I would think it is unnecessary. Still, I'm writing this sample code as part of a job application, and I don't want my code to look badly nor cluttered. What would be the most elegant solution?

shooting a bullet from tank java

I'm writing a tank game . I want to have a method called shoot that when I press Space the tank have to shoot . my problem is that when the program calls this method it goes through the while loop and after that it prints the end location of the ball . I need to implement something in the while loop that every time it calculates dx and dy it goes to the paint method and paint the new location of the ball. I tried adding paintImmediately() but it throws stackoverflow error. thanks for helping me.

actually I'm changing dx and dy and I want the paint method to draw the ball at that place...

   public void shoot(Image img, double fromx, double fromy, double ydestination, int speed) {
    int time = 0;
    double speedy, speedx;
    while (dy!=ydestination) {
        time++;
        speedy = speed * Math.sin(Math.toRadians(angle));
        speedx = speed * Math.cos(Math.toRadians(angle));

        dy = (int) ((-5) * time * time + speedy * time + fromy);
        dx = (int) (speedx * time + fromx);
        // paintImmediately((int)dx,(int) dy, 10, 10);

        try {
            Thread.sleep(100);

        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }

}

and here is my overrided paint method the last line is for the bullet that is my question :

@Override
public void paint(Graphics g) {

    System.out.println("paint");
    super.paint(g);

    render(bufferedGraphics);

    g.drawImage(bufferedScreen, 0, 0, null);
    // System.out.println(x1);
    BufferedImage buff = rotateImage(mile1, angle);
    BufferedImage buf = rotateImage(mile2, angle);
    g.drawImage(buff, mx1 - 40, my1, null);
    g.drawImage(buf, mx2 , my2, null);
    g.drawImage(bullet, (int) dx, (int) dy, null);
    //setVisible(true);
}

Overhead of threads on performance

I'm trying to increase the performance of an app by adding threads to do concurrent tasks. The results I've gotten are very confusing to me and make me think there is some kind of thread related overhead of which I am not aware. Below are two copies of the same code with the exception that one uses threads and the other doesn't. The one that doesn't use threads runs four times faster than the one that uses threads. I'm testing using my device which is a Samsung note 4 with a quad processor. Any insights will be highly welcome.

Thanks,

cwm

  public void testThreads() throws InterruptedException {
  startMilli = System.currentTimeMillis();
  Thread t1 = new Thread() {
        public void run() {
            load1();
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            load2();
        }
    };
    t1.start();
    t2.start();
    t1.join();
    t2.join();
  //  load1();
  //  load2();
    stopMilli = System.currentTimeMillis();
    diffMilli = stopMilli - startMilli;
    startMilli = System.currentTimeMillis();
}
public void load1() {
    List<Integer> list1 = new ArrayList<Integer>();
    for(i = 0; i<100000; i++) {
        list1.add(i);
    }
}

public void load2() {
    List<Integer> list2 = new ArrayList<Integer>();
    for(j = 100000; j<200000; j++){
        list2.add(j);
    }
}

  public void testThreads() throws InterruptedException {
  startMilli = System.currentTimeMillis();

    load1();
    load2();
    stopMilli = System.currentTimeMillis();
    diffMilli = stopMilli - startMilli;
    startMilli = System.currentTimeMillis();
}
public void load1() {
    List<Integer> list1 = new ArrayList<Integer>();
    for(i = 0; i<100000; i++) {
        list1.add(i);
    }
}

public void load2() {
    List<Integer> list2 = new ArrayList<Integer>();
    for(j = 100000; j<200000; j++){
        list2.add(j);
    }
}

Maven does not execute browser

I am using maven integration in my selenium project.Below is my pom.xml configuration-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javacodegeeks.testng.spring</groupId>
    <artifactId>testNGSpring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.45.0</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-firefox-driver</artifactId>
    <version>2.45.0</version>
</dependency>

    </dependencies>

    <properties>
        <spring.version>4.1.5.RELEASE</spring.version>
    </properties>
</project>

On execution this,build is successful but firefox does not invoke.Below is stacktrace of error-

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.020 s
[INFO] Finished at: 2015-05-08T18:26:49+05:30
[INFO] Final Memory: 7M/18M
[INFO] ------------------------------------------------------------------------
Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook
Picked up _JAVA_OPTIONS: -Xrunjvmhook -Xbootclasspath/a:"C:\Program Files (x86)\HP\Unified Functional Testing\bin\java_shared\classes";"C:\Program Files (x86)\HP\Unified Functional Testing\\bin\java_shared\classes\jasmine.jar"

I have done all the necessary changes like browser update and selenium jar update.Still facing same issue. Thanks in advance.

java iterator with index parameter

hi a normal iterator for a LinkedList would be the following, however, how do we build an iterator that returns an iterator starting at a specified index? How do we build:

public Iterator<E>iterator(int index)???  

thanks! normal Iterator:

    public Iterator<E> iterator( )
    {
        return new ListIterator();
    }

private class ListIterator implements Iterator<E>
    {
        private Node current;

        public ListIterator()
        {
            current = head; // head in the enclosing list
        }
        public boolean hasNext()
        {
            return current != null;
        }
        public E next()
        {
            E ret = current.item;
            current = current.next;
            return ret;
        }
        public void remove() { /* omitted because optional */ }
    }

Java mapping for COBOL comp and comp-3 fields

I am invoking DB2 stored procedure created using COBOL from my java application.

input macro (type varchar):

01 SP1-INPUTS.
    05 FIELD-1      PIC X(03).
    05 FIELD-2      PIC S9(09) COMP.
    05 FIELD-3      PIC S9(15)V9(02) COMP-3.
    05 FIELD-3X     REDEFINES  FIELD-3 PIC X(09)

To test the stored procedure, I know only value for FIELD-1. For other fields, to fill the packed portions how many zeros should I put? Please see the code which I wrote and confused in passing dummy values.

String field1="abc";
String field2="000000000"; // 9 zeroes, correct?
String field3="00...0" // should I give 18 zeroes or 9 zeroes?

How much characters totally for the input macro ?

spring-amqp with RabbitMQ does not shutdown properly

When consumer not finishes execution within SimpleMessageListenerContainer shutdownTimeout after AnnotationConfigApplicationContext.close() invocation, my Spring application hangs.

Listener:

public class LongRunningMessageListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        System.out.println("Got " + new String(message.getBody()));
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
            Thread.currentThread().interrupt();
        }
        System.out.println("Finished execution");
    }
}

Configuration:

@Configuration
public class Config {

    @Bean
    public MessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer(connectionFactory());
        messageListenerContainer.setQueueNames("myqueue");
        messageListenerContainer.setMessageListener(new LongRunningMessageListener());
        messageListenerContainer.setShutdownTimeout(1000);
        return messageListenerContainer;
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        return new CachingConnectionFactory("localhost");
    }
}

Main:

public static void main(String[] args) throws InterruptedException {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
    Thread.sleep(1000L);
    applicationContext.close();
}

Output:

мая 08, 2015 3:43:21 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a86f2f1: startup date [Fri May 08 15:43:21 MSK 2015]; root of context hierarchy
мая 08, 2015 3:43:22 PM org.springframework.context.support.DefaultLifecycleProcessor start
INFO: Starting beans in phase 2147483647
мая 08, 2015 3:43:22 PM org.springframework.amqp.rabbit.connection.CachingConnectionFactory createBareConnection
INFO: Created new connection: SimpleConnection@4025f2f5 [delegate=amqp://guest@127.0.0.1:5672/]
Got foo1
мая 08, 2015 3:43:23 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a86f2f1: startup date [Fri May 08 15:43:21 MSK 2015]; root of context hierarchy
мая 08, 2015 3:43:23 PM org.springframework.context.support.DefaultLifecycleProcessor stop
INFO: Stopping beans in phase 2147483647
мая 08, 2015 3:43:23 PM org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer doShutdown
INFO: Waiting for workers to finish.
мая 08, 2015 3:43:24 PM org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer doShutdown
INFO: Workers not finished.  Forcing connections to close.
Finished execution
мая 08, 2015 3:43:27 PM org.springframework.amqp.rabbit.connection.CachingConnectionFactory createBareConnection
INFO: Created new connection: SimpleConnection@260da64e [delegate=amqp://guest@127.0.0.1:5672/]
мая 08, 2015 3:43:27 PM org.springframework.amqp.rabbit.connection.CachingConnectionFactory shutdownCompleted
SEVERE: Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - unknown delivery tag 1, class-id=60, method-id=80)

After that application is working infinitely.

Working threads:

Live threads: 14
Daemon threads: 10

Non daemon threads:

"pool-1-thread-10" #22 prio=5 os_prio=31 tid=0x00007fd48c93c800 nid=0x5a07 waiting on condition [0x0000000129eb3000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000796333168> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
    - None

"pool-1-thread-9" #21 prio=5 os_prio=31 tid=0x00007fd48b9d8000 nid=0x540b waiting on condition [0x0000000129db0000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000079633dfb0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
    - None

"AMQP Connection 127.0.0.1:5672" #20 prio=5 os_prio=31 tid=0x00007fd48d186000 nid=0x530b runnable [0x0000000129cad000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:170)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
    - locked <0x000000079632e8f0> (a java.io.BufferedInputStream)
    at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:288)
    at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:95)
    at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:139)
    - locked <0x000000079632e8d0> (a java.io.DataInputStream)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:534)
    at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
    - None

"DestroyJavaVM" #19 prio=5 os_prio=31 tid=0x00007fd48d002000 nid=0x1303 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
    - None

Everything is fine if I increase shutdownTimeout, but timeout behavior looks like a bug.

Spring versions:

<dependencies>
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-amqp</artifactId>
        <version>1.4.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
        <version>1.4.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.5.RELEASE</version>
    </dependency>
</dependencies>

Why is this program which loops many times taking time when there is a `println` after the loops?

Here is the small code which I am trying. This program takes good amount of time to execute. While running, if I try to kill it through the terminate button in eclipse, it returns Terminate Failed. I can kill it from terminal using kill -9 <PID>.

But, when I don't print the variable result in the last line of the program (Please check the commented portion of the code), the program exits immediately.

I am wondering :

  1. Why is it taking time to execute when the value of result is being printed?
    Please note, if I don't print value, the same loop gets over immediately.

  2. Why is eclipse not able to kill the program?

Update 1 : It seems JVM is optimize the code during the runtime (not in compile time). This thread is helpful.

Update 2 : When I print the value of value, jstack <PID> is not working. Only jstack -F <PID> is working. Any possible reason?

    public class TestClient {

        private static void loop() {
            long value =0;

            for (int j = 0; j < 50000; j++) {
                for (int i = 0; i < 100000000; i++) {
                    value += 1;
                }
            }
            //When the value is being printed, the program 
            //is taking time to complete
            System.out.println("Done "+ value);

            //When the value is NOT being printed, the program 
            //completes immediately
            //System.out.println("Done ");
        }

        public static void main(String[] args) {
            loop();
        }
    }

Associative table - QuerySyntaxException: Userapp is not mapped - hibernate

My Tools :

  • Netbeans 8.x
  • Hibernate plugin
  • PHP my admin

I have 3 tables :

User ->>- many to many ->>- Userapp ->>- many to many ->>- Application

User have :

  • userId

  • userName

UserApp :

  • userId

    -applicationId

Applicaiton :

  • applicationId

  • applicaitonName

HQL Query :

SELECT a.applicaitonName
FROM UserApp ua
    LEFT JOIN Application a On ua.applicationId= a.applicationId
WHERE
    ua.userId = ?

Error :

org.hibernate.hql.internal.ast.QuerySyntaxException: Userapp is not mapped [SELECT a.applicaitonName
FROM Userapp ua
    LEFT JOIN Application a On ua.applicationId= a.applicationId
WHERE
    ua.userId = 1]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)

How i proceed : - I created hibernate.cfg.xml - I created hibernate.reveng.xml - I created Hibernate Mapping Files and Pojors from database

When i create Hibernate Mapping Files and Pojors from database, it created 2 news object : Application and User. But not Userapp ... I have to create it manually ?

Here the hibernate.reveng.xml :

<hibernate-reverse-engineering>
  <schema-selection match-catalog="allin"/>
  <table-filter match-name="user"/>
  <table-filter match-name="application"/>
  <table-filter match-name="userapp"/>
</hibernate-reverse-engineering>

Thanks for your help !!

How to pass raw parameter using jsoup

I want to call an API which just accepts raw data when you send requests using jsoup.

My code looks like this:

Document res = Jsoup.connect(url)
        .header("Accept", "application/json")
        .header("X-Requested-With", "XMLHttpRequest")
        .data("name", "test", "room", "bedroom")
        .post();

But I know the above code is not right for passing raw data.

Can anybody tell me how can I do it?

Value

I am sending json from servlet to android application , and the following exception occurs : -

 org.json.JSONException: Value <html><head><title>Apache of type java.lang.String cannot be converted to JSONObject

Following is my servlet code , please correct me if anything is wrong here :-

public class LoginCheck extends HttpServlet {

  protected void processRequest(HttpServletRequest request,  HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    PrintWriter out = response.getWriter();


    JSONObject obj1 = new JSONObject();

    long uname =Long.parseLong(request.getParameter("mobile"));
    String pwd = request.getParameter("pass");

    try  {
    Connection con = new MyConnection().connect();
    PreparedStatement ps = con.prepareStatement("select * from bmt_user  where mobile_num=? and password=?");
    ps.setLong(1,uname);
    ps.setString(2,pwd);

     ResultSet rs=ps.executeQuery();

        if(rs.next())
       {
            obj1.accumulate("login","Success");
            out.println(obj1.toString());

       }

        else
        {
            obj1.accumulate("login","Fail");
            out.println(obj1.toString());
        }
       out.write(obj1.toString());     
    }catch(Exception e){out.println(e.toString());}
  }


  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
   }

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     processRequest(request, response);
  }

 }

Plus , when i assign the values to uname and pwd directly , without using request.getParameter() , the servlet runs just fine and returns json i.e

long uname = 48372984;
String pwd = "fabcd"

output -

{"login":"Fail"}

How to configure fonts from Java code in Apache FOP?

The link says that it is not "easily" possible to configure fonts from java code. How do I achieve this? I'm having problems rendering certain HTMLs from international languages like French and Japanese.

WARNING: Font "Symbol,normal,700" not found. Substituting with "Symbol,normal,400".
May 08, 2015 4:45:39 PM org.apache.fop.events.LoggingEventListener processEvent
WARNING: Font "ZapfDingbats,normal,700" not found. Substituting with "ZapfDingbats,normal,400". 

The PDF generated is damaged as a result.

update:

My Html contains French words like "Modifié Créée le Propriétaire"

File file = new File("C:\\Users\\me\\Desktop\\Test.html");


fopFactory = FopFactory.newInstance();
foUserAgent = fopFactory.newFOUserAgent();


String fileName = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\")+1,file.getAbsolutePath().lastIndexOf("."));
        String workspacePath = file.getAbsolutePath().substring(0,file.getAbsolutePath().lastIndexOf("\\"));
        File xsltfile = new File("xhtml2fo.xsl");
        StreamSource source = null;
        source = new StreamSource(file);
        StreamSource transformSource = new StreamSource(xsltfile);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();


        Transformer xslfoTransformer = null;
        TransformerFactory fac = TransformerFactory.newInstance();
        xslfoTransformer = fac.newTransformer(transformSource);
        xslfoTransformer.setErrorListener(this);

        Fop fop;
        fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outStream);
        // Resulting SAX events (the generated FO)
        Result res = new SAXResult(fop.getDefaultHandler());
        xslfoTransformer.transform(source, res);

        output = new File(workspacePath + File.separator + fileName + ".pdf");
        OutputStream out = new java.io.FileOutputStream(output);
        out = new java.io.BufferedOutputStream(out);
        FileOutputStream str = new FileOutputStream(output);
        str.write(outStream.toByteArray());
        str.close();

I'm using an XSLT provided by Antennahouse to convert HTML tags to FO tags.

Can Spring MVC deserialize JSON which can be object or array?

I have controller receiving JSON in request body, which can be object or array of objects. For example:

{
  "id" : 1,
  "name" : "Nick",
  "surname" : "Cave"
}

and

[
 {
   "id" : 1,
   "name" : "Nick",
   "surname" : "Cave"
 },
 {
   "id" : 2,
   "name" : "Jack",
   "surname" : "White"
 }
]

Is there any way to force Spring to deserialize JSON to object in the similar way to object alone?

@RequestMapping(value = "/", method = RequestMethod.POST)
public void postController(@RequestBody User user, ...) {
   ...
}

If not, what is the elegant way of parsing and validating those kind of messages?

Spring app - run method on end of transaction?

I wondering it is possible to configure spring in way to fire particular method on end transaction?

For example I have service class with method

@Service
public class service implements IService
{
    @Resource
    private EntityDao entityDao;

    @Resource
    private SomeService someService;

    @Transactional
    @Override
    public void doThings()
    {
       entityDao.doSmthOnDb();
       someService.thisMethodFiresOnEndOfTransaction();
    }

}

and second service class

@Service
public class secondService implements ISecondService
{
  @Resource
  private IService service;

  @Transactional
  @Override
  public void method()
  {
  service.doThings();
  /*
  some other code that can break transaction
  */
  }
}

so if I call secondService.method() I want that someService.thisMethodFiresOnEndOfTransaction() will be fire only if transaction end successfully.

Is it possible in spring?

Intellij IDEA pluggin cannot be run

I am new to Intellij plugin development. Currently I am working on a project in creating a plugin to Intellij IDEA. When I click on the run button, it builds successfully and shows me the first window of the new IDEA but when I click on Open new project it gives me these errors and exceptions.

[  20681]  ERROR - llij.ide.plugins.PluginManager - null 
java.lang.NullPointerException
    at com.intellij.ide.util.projectWizard.ModuleBuilder.getModuleTypeName(ModuleBuilder.java:384)
    at com.intellij.ide.util.projectWizard.ModuleBuilder.getPresentableName(ModuleBuilder.java:380)
    at com.intellij.ide.util.newProjectWizard.TemplatesGroup.<init>(TemplatesGroup.java:61)
    at com.intellij.ide.projectWizard.ProjectTypeStep.fillTemplatesMap(ProjectTypeStep.java:298)
    at com.intellij.ide.projectWizard.ProjectTypeStep.<init>(ProjectTypeStep.java:136)
    at com.intellij.ide.projectWizard.NewProjectWizard.init(NewProjectWizard.java:50)
    at com.intellij.ide.projectWizard.NewProjectWizard.<init>(NewProjectWizard.java:39)
    at com.intellij.ide.actions.NewProjectAction.actionPerformed(NewProjectAction.java:30)
    at com.intellij.ui.components.labels.ActionLink$1.linkSelected(ActionLink.java:64)
    at com.intellij.ui.components.labels.LinkLabel.doClick(LinkLabel.java:106)
    at com.intellij.ui.components.labels.ActionLink.doClick(ActionLink.java:77)
    at com.intellij.ui.components.labels.LinkLabel$MyMouseHandler.mouseReleased(LinkLabel.java:277)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:734)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:565)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:382)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
[  20694]  ERROR - llij.ide.plugins.PluginManager - IntelliJ IDEA 14.1.2  Build #IC-141.713.2 
[  20694]  ERROR - llij.ide.plugins.PluginManager - JDK: 1.8.0_25 
[  20695]  ERROR - llij.ide.plugins.PluginManager - VM: Java HotSpot(TM) 64-Bit Server VM 
[  20695]  ERROR - llij.ide.plugins.PluginManager - Vendor: Oracle Corporation 
[  20695]  ERROR - llij.ide.plugins.PluginManager - OS: Windows 8.1 
[  20696]  ERROR - llij.ide.plugins.PluginManager - Last Action:  
[  28044]   WARN - api.vfs.impl.local.FileWatcher - Watcher terminated with exit code 0 
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=250m; support was removed in 8.0

Please help me to get out of this and run my plugin if anyone has any idea.. thanks...

NoSuchBeanDefinitionException occurring while running junit tests

Here's the setup:

I'm unit testing an email notification service that I wrote using Java Mail shown here:

@Service
public class EmailNotificationService implements NotificationService {
    @Autowired
    private CertificateService service;

    @Override
    public boolean sendFeedback(String title, String feedback) throws NotificationException {

    // Code here
    }
    @Override
    public boolean sendQuestion(String title, String question) throws NotificationException {

    // Code here
    }
}

My unit test class is as such:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:/service-commons/src/test/resources/mockUserProviderContext.xml")
public class TestEmailNotificationService extends TestCase {

@Autowired
private EmailNotificationService emailServ;
@Resource
private WebApplicationContext context;

@Test
public void testSendFeedback() {
    try {
        boolean bool = emailServ.sendFeedback("feedbackTitle", "someFeedback");
        assertTrue(bool);
    } catch (NotificationException e) {
        e.printStackTrace();
        fail();
    }
}

@Test
public void testSendQuestion() {
    try {
        boolean bool = emailServ.sendQuestion("questionTitle", "someQuestion");
        assertTrue(bool);
    } catch (NotificationException e) {
        e.printStackTrace();
        fail();
    }
}

}

My application context is as such:

<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="
http://ift.tt/GArMu6
http://ift.tt/1jdM0fG">

<bean id="simpleCertService" class="service.commons.defaults.CertificateService" />
<bean id="service" class="service.commons.defaults.EmailNotificationService" />

I'm getting the following exception whenever I try to run this unit test:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'service': Injection of resource dependencies failed; nested exception is    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
    ... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:457)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:435)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
    ... 41 more

The original problem I ran into was that whenever I ran the unit test, I would get a NullPointerException from EmailNotificationService when any of the methods associated with CertificateService were run. I added a bean for it the application context, and set the @ContextConfiguration to point the application context file to fix this issue. I was hoping that spring would be able to figure out which bean wanted to inject from there, but I haven't been able to make it work. Any suggestions?

Updated

public class CertificateService implements CertificateUserService {

private static final Logger log = Logger.getLogger(SimpleCertificateService.class);

@Override
public User fetchUser(final X509Certificate certificate) {
    log.info("Fetching user for " + certificate.getSubjectDN().getName());
    return new SimpleUser(certificate.getSubjectDN().getName());
}

@Override
public User fetchUser(String name) {
    log.info("Fetching user for " + name);
    return new SimpleUser(name);
}

public class SimpleUser extends AbstractUser {


    private static final long serialVersionUID = 1L;


    public SimplUser(String username) {
        super(username, "User", "thing", "User", "T1222", false);
        this.emailAddress = "some@example.com";
        this.phoneNumber = "(123)123-1234";
    }

    @Override
    public void clearCache() {
        super.clearCache();
    }

}

}

Issue in hornetq: java.lang.IllegalStateException: Invalid logic on buffer allocation

I am using hornetq-2.0. IllegalStateException occured when my jms queue gets piled up. Below is the stack trace for the exception.

java.lang.IllegalStateException: Invalid logic on buffer allocation

    at org.hornetq.core.journal.impl.JournalImpl.appendRecord(JournalImpl.java:2820)

    at org.hornetq.core.journal.impl.JournalImpl.appendAddRecordTransactional(JournalImpl.java:968)

    at org.hornetq.core.persistence.impl.journal.JournalStorageManager.storeMessageTransactional(JournalStorageManager.java:567)

    at org.hornetq.core.postoffice.impl.PostOfficeImpl.processRoute(PostOfficeImpl.java:900)

    at org.hornetq.core.postoffice.impl.PostOfficeImpl.route(PostOfficeImpl.java:665)

    at org.hornetq.core.postoffice.impl.PostOfficeImpl.route(PostOfficeImpl.java:539)

    at org.hornetq.core.paging.impl.PagingStoreImpl.onDepage(PagingStoreImpl.java:1006)

    at org.hornetq.core.paging.impl.PagingStoreImpl.readPage(PagingStoreImpl.java:698)

    at org.hornetq.core.paging.impl.PagingStoreImpl.access$200(PagingStoreImpl.java:64)

    at org.hornetq.core.paging.impl.PagingStoreImpl$DepageRunnable.run(PagingStoreImpl.java:1181)

    at org.hornetq.utils.OrderedExecutorFactory$OrderedExecutor$1.run(OrderedExecutorFactory.java:96)

    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)

    at java.lang.Thread.run(Thread.java:662)

After this error occurred the hornetq had to be restarted and the pages and journals had to be cleared.

Jackson conflicting property and getter definitions

I'm extending following third-party class which I can't change:

public class Page {
    @JsonProperty("content")
    private String content;

    public String getContent() {};
}

My implementation of Page looks like this:

public class MyPage extends Page {
    @JsonProperty("my-content")
    public String getContent() {return super.getContent()};
}

When I'm trying to serialize instance of MyPage class I get the following exception:

java.lang.IllegalStateException: Conflicting property name definitions:  
'content' (for [field com.test.Page#content]) 
vs
'my-content' (for [method com.test.MyPage#getContent(0 params)])

Is there an easy way to force serializer to produce 'my-content' property?

How to get access to all information, passed within the response from a RestEasy service to a RestEasy client?

i´m implementing a Restful service using Jax-RS 2.0 (Resteasy 3.0.7.Final) and share the interface between client and service.

The interface i´m sharing has several create Methods. The return value is void because ClientResponse is deprecated since RestEasy introduced JAX-RS 2.0 in version 3+.

To return the location of the new created object i inject the response, using the @Context annotation, and add the Content-Location header.

A simple example:

Shared Interface:

   @Path("/")
   @Consumes("application/xml")
   @Produces("application/xml")
   interface Resource {

        @Path("createSomething")
        void createSomething(AnyObject object);

        ...
   }

Implementation:

    class ResourceImpl {

         ...
         @Context org.jboss.resteasy.spi.HttpResponse response;
         ...

         @Override
         void createSomething(AnyObject object) throws AnyException {

             String id = service.create(object);

             response.getOutputHeaders().putSingle("Content-Location",
                  "/createSomething/" + id);

             response.setStatus(Response.Status.CREATED.getStatusCode());
         }

    }

The client (build with the Resteasy Proxy Framework):

     ...
     ResteasyClient client = new ResteasyClientBuilder().build();
     ResteasyWebTarget target = client.target(baseUrl);

     Resource resource = (Resource) target.proxy(Resource.class);   

     resource.createSomething(anyObject);
     ...

How can i retrieve Header information (and others, like Atom Links) which injected by the service?

Is it reasonable to use client side Filters and Interceptors?

Thank You

While using ModelMapper, how do I specify custom mappings for specific properties on my source class?

To be specific, I want to convert a String in my Source class (PurchaseOrderFilterViewModel) to an org.joda.time.LocalDate in my Destination class (PurchaseOrderFilter).

I tried using PropertyMap<Source, Destination> in accordance with the documentation but it doesn't work. The dates in the Destination class are always assigned to the current date which is the default LocalDate when null is passed in as the constructor parameter.

    PurchaseOrderFilterViewModel purchaseOrderFilterViewModel1 = new PurchaseOrderFilterViewModel();
    purchaseOrderFilterViewModel.setStartReceiptDate("2015-04-15");
    purchaseOrderFilterViewModel.setEndReceiptDate("2015-04-17");

    ModelMapper modelMapper = new ModelMapper();

    modelMapper.createTypeMap(PurchaseOrderFilterViewModel.class, PurchaseOrderFilter.class);
    modelMapper.addMappings(new PropertyMap<PurchaseOrderFilterViewModel, PurchaseOrderFilter>()
    {
        @Override
        protected void configure()
        {
            map().setStartReceiptDate(new LocalDate(source.getStartReceiptDate()));
            map().setEndReceiptDate(new LocalDate(source.getEndReceiptDate()));
        }
    });

    PurchaseOrderFilter purchaseOrderFilter = modelMapper.map(purchaseOrderFilterViewModel, PurchaseOrderFilter.class);

How to show output from console in a GUI

I want to show output console in JAVA into a GUI but I don't know how here is my output, it looks like an xml file but I want to just show the result not all the output. please help me.

Set Type of ArrayList Dynamically

Currently I have this set of code:

package com.sdqn.shared.property;

import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Misc_ReturnValue {
    public String message;
    public int total;
    public boolean success;
    public ArrayList results;

    public Misc_ReturnValue(){
        this.success = false;
        this.total = 0;
    }
}

The problem is, I need the results to accept any type. I try to follow the answer from here but it seem like I don't understand how to use it in my code. Can anybody explain to me how I can achieve this?

Tomcat, java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

I'm trying to use spring-mvc. Create maven project, add dependency. I am using tomcat 7, and eclipse luna. And I have this exception:

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:506) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:488) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:115) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5262) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5550) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)

I tried to find solution of this problem. But all solutions that I found are identical, something like this: http://ift.tt/1cukmMJ but this didn't help me. May be I did something wrong?

it's my pom file dependency:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.4.RELEASE</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.4.RELEASE</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
        <scope>provided</scope>
    </dependency>

and my web.xml :

<servlet>
    <servlet-name>HelloWeb</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

How to pass a structure as an argument to java function or return to java from jni

I have two questions Say I have some structure in jni say

struct X
{
    Type_A x;
    Type_B y;
}

Now how do I?

  1. Pass this structure as an argument to a java call back function
  2. How do I return this structure to a Java function.

If possible, please give an example.

Cannot connect Java to CONNX: java.sql.SQLException: Connection refused: connect

I'm trying to connect a Java based program running through Tomcat to a CONNX database, but I'm getting the error in the title. This is the code I have, with some identifying information removed:

  String driver = "com.Connx.jdbc.TCJdbc.TCJdbcDriver";
  String connectionString = "jdbc:connx:DD=praxav11;Gateway=<server name>";
  String user = "<user>";
  String pass = "<pass>";
  Class.forName(driver); 
  dbConnection = java.sql.DriverManager.getConnection(connectionStr, user, password);

I've been using instructions from:

http://ift.tt/1FTkn8e

"praxav11" I got from the DSNR tool, according to which is the CDD-DSN for the CDD I want so I'm pretty confident that is right.

For the gateway I've tried both the server name and the server IP. Username and password I'm quite confident are correct and I would get a different error for those anyway I guess.

Does anybody have any ideas for what is wrong or suggestions for what to try? I'm really drawing a blank on this and have tried brute forcing it but I just can't get it to work.

The full error is:

com.$company.DBDataSetException: java.sql.SQLException: Connection refused: connect
at com.$company.DBDatabase.setConnection(DBDatabase.java:43)
at em.cabbench.$client.ERPInterface$client.connectToConnx(ERPInterface$client.java:137)
at em.cabbench.$client.ERPInterface$client.getERPRawMaterialPrice(ERPInterface$client.java:167)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at em.cabbench.RequestTypes.call(RequestTypes.java:1120)
at em.cabbench.CabBenchSrv.processRequest(CabBenchSrv.java:988)
at em.cabbench.CabBenchSrv.doGet(CabBenchSrv.java:828)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

Caused by: java.sql.SQLException: Connection refused: connect
at com.Connx.jdbc.TCJdbc.TCJdbcDriver.connect(TCJdbcDriver.java:251)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.$company.DBDatabase.setConnection(DBDatabase.java:40)
... 23 more

Couldn't connect to CONNX
java.lang.NullPointerException
at com.$company.DBDatabase.closeConnection(DBDatabase.java:66)
at em.cabbench.$client.ERPInterface$client.getERPRawMaterialPrice(ERPInterface$client.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at em.cabbench.RequestTypes.call(RequestTypes.java:1120)
at em.cabbench.CabBenchSrv.processRequest(CabBenchSrv.java:988)
at em.cabbench.CabBenchSrv.doGet(CabBenchSrv.java:828)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)