samedi 25 avril 2015

Make JAVA code efficient


I am trying to solve a problem and I am getting time limit errors, can someone help improving my code? Thanks.

Link for the problem: http://ift.tt/1vdOQVb My code:

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        String aux;
        String input;
        int contador;
        while((input = in.readLine()) != null) {
            StringTokenizer tokens = new StringTokenizer(input);
            contador = 0;
            for (int i = 0; i < tokens.countTokens(); i++) {
                aux = tokens.nextToken();
                for (int j = 0; j < aux.length() - 1; j++) {
                    if (Character.isLetter(aux.charAt(j)) && Character.isLetter(aux.charAt(j + 1))) {
                        contador++;
                    }
                }
            }
            out.write(contador);
        }
        out.flush();
        in.close();
        out.close();
    }
}


Why SpringSecurity, after a logout, keeps giving the same authenticated Principal


So I am using Spring Security with Spring Boot. I wanted to make my own AuthenticationProvider, that was using the db in my very own way, so I did it with this authenticate method:

@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String email = authentication.getName();
        String password = authentication.getCredentials().toString();


        UserWithEmail userWithEmail = authService.getUserByEmail(email);
        if (userWithEmail == null)
            return null;
        if (userWithEmail.getPassword().equals(password)) {



            UsernamePasswordAuthenticationToken authenticated_user = new UsernamePasswordAuthenticationToken(userWithEmail, password, Arrays.asList(REGISTERED_USER_SIMPLE_GRANTED_AUTHORITY));
            return authenticated_user;
        } else {
            return null;
        }
    }

This, if I use the default /login page with the form, works well and after that if I add the following ModelAttribute to a Controller, it gets correctly filled with the UserWithEmail object:

@ModelAttribute("userwithemail")
    public UserWithEmail userWithEmail(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        Object principal = authentication.getPrincipal();
        if (principal instanceof UserWithEmail)
            return (UserWithEmail) principal;
        else
            return null;

    }

The problem is that if I hit /login?logout, it correctly displays that I am logged out, but if I go through the controller again I still get the same UserWithEmail object as principal and it has the property authenticated=true

This is my Java config for spring security:

http
                .formLogin()
                .defaultSuccessUrl( "/" )
                .usernameParameter( "username" )
                .passwordParameter( "password" )
                .and()

                .logout().invalidateHttpSession(true).deleteCookies("JSESSIONID").permitAll().and()

                .authorizeRequests()
                .antMatchers("*/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/profile").hasRole(MyAuthenticationProvider.REGISTERED_USER_AUTH)

                .and().authenticationProvider(getAuthProvider());

I'm new to Spring Security so maybe I'm missing something... can anyone help?


ajax post call don't show page


I have this code, but this doesn't redirect well to the page results.

This is my code html:

<script type="text/javascript">
    function cargaDatos2(){ 
        var param1= $('#selector2').val();
        var param2= $('#selector3').val();
        //Llamada a la funcion que carga los datos en la base de datos.
        $.ajax({
            type: "POST",
            data: {"param1" : param1, "param2" : param2},
            url: "http://localhost:8080/prueba",
            success: function(data){
                alert("Ejecutado correctamente");
            },
            error: function (data){
                alert("Error en la ejecucion");
            }
        });

    }
</script>    

And this is my code in Java, Spring:

  @RequestMapping(value="/prueba", method=RequestMethod.POST)
  public String checkPersonInfo(@RequestParam (required=false) String param1, @RequestParam (required=false) String param2) {

System.out.printf("1-el nombre seleccionado es: %s \n", param1);
System.out.printf("2-el nombre seleccionado es: %s \n", param2);
return "redirect:/results";

}

why doesn't it redirect? this is my output in console browser:

prueba POST 302 Found application/x-www-form-urlencoded jquery.min.js:19

results GET 200 OK text/html http://localhost:8080/prueba Redirect

What is the problem?


Shell commands are not running using jsch and expcetit library in java


I am following below steps for running commands on ssh server.

  1. Connecting to ssh server
  2. Using devpush command again logging to server (using expectit library for user input prompt).
  3. Finally running remote commands using jsch library.

The issue I am facing is that, my code is going in infinite loop it is able to login to ssh server but not able to run the commands. Can any one please help me on this as I am using both the libraries for first time.

package com.dmotorworks.cdk;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import net.sf.expectit.*;
import net.sf.expectit.matcher.Matchers;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ShellClient {

    public void loginToPabloServer() throws IOException, JSchException{
        String hostname="pablo.dmotorworks.com";
        String username="gaikwasu";
        String password="Nexus@80900";
        final String  endLineStr=" # ";

        JSch jsch = new JSch();     
        Session session = jsch.getSession(username, hostname, 22);
        session.setPassword(password);
        jsch.setKnownHosts("C://Users//gaikwasu//.ssh//known_hosts");

        session.connect();
        System.out.println("Connected");


        Channel channel=session.openChannel("shell");
        channel.connect();

        Expect expect=new ExpectBuilder()
                .withOutput(channel.getOutputStream())
                .withInputs(channel.getInputStream(), channel.getExtInputStream())
                .withEchoOutput(System.out)
                .withEchoInput(System.err)
                .withExceptionOnFailure()
                .build();

        expect.expect(Matchers.contains("-bash-4.1$"));    
        expect.send("devpush\n");
        expect.expect(Matchers.contains("[sudo] password for"));
        expect.send(password+"\n");


        DataInputStream dataIn = new DataInputStream(channel.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
        BufferedReader bufferReader= new BufferedReader(new InputStreamReader(dataIn));

        dataOut.writeBytes("cd custom\n");
        dataOut.writeBytes("ls -lrt\n");
        dataOut.flush();

        String line=bufferReader.readLine();
        while(!line.endsWith(endLineStr)) {
               System.out.println(line);
          }

        channel.disconnect();
        session.disconnect();
        expect.close();


    }

    public static void main(String[] args) {
        ShellClient shellClient=new ShellClient();
        try {
            shellClient.loginToPabloServer();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


Android Rest Api Post 400 bad request


I'm working on an app that will send a password to the server to check if it's correct, the server will return 0,1,2,3 representing different statuses I'm not sure where this 400 bad request is coming from. I've called the server and received the json file but I'm suspecting it's how I parsed it? Any help is greatly appreciated.

AN UPDATE

an update. I realize part of the mistake here is that I'm trying to send a string without converting it to a JSON file first. That is why I've been receiving "status:0" which stands for an error occurred. I've converted my string into a RegisterRequest object which contains a string variable. Now I'm receiving status 2 which stands for incorrect password. However my bad request 400 still remains. PLEASE any help or suggestion will be very helpful to me

 @Headers("Content-Type: application/json")
 @POST("removed/{id}")
 RegisterResponse registerEvent(@Path("id") int ID, @Body RegisterRequest password)throws NetworkException;

RegisterResponse class:

public class RegisterResponse {
public String               status;
}

RegisterRequest class

public class RegisterRequest {

    String passcode ;

    public RegisterRequest(String passcode)
    {
        this.passcode=passcode;
    }
}

call to server:

try {
       RegisterResponse response = NetworkHelper.makeRequestAdapter(this)
               .create(testApi.class).register(ID, pass);

        if(response.status=="1"||response.status=="3")
        {
            return true;
        }
        else
            return false;
    } catch (NetworkException e) {
        e.printStackTrace();
    }
   return false;
}

Make Request Adapter

private static RestAdapter.Builder makeRequestAdapterBuilder(final Context context, ErrorHandler errorHandler, String dateTimeFormat)
    {
        RequestInterceptor requestInterceptor = new RequestInterceptor()
        {
            @Override
            public void intercept(RequestInterceptor.RequestFacade request)
            {
                request.addHeader("Authorization", AppPrefs.getInstance(context).getSessionToken());
            }
        };

        Gson gson = new GsonBuilder().setDateFormat(dateTimeFormat).create();
        GsonConverter gsonConverter = new GsonConverter(gson);

        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setRequestInterceptor(requestInterceptor).setConverter(gsonConverter)
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("Boom!"))
                .setEndpoint(BASE_URL);

        if(errorHandler != null)
        {
            builder.setErrorHandler(errorHandler);
        }

        if(instance == null)
        {
            instance = new OkClient(makeTimeoutClient(READ_TIMEOUT, CONNECT_TIMEOUT));
        }
        builder.setClient(instance);

        return builder;
    }

Error code:

-13257/AndroidCall D/Boom!﹕ ---> HTTP POST https://serverurl/29522
04-24 23:18:04.957  13257-13257/AndroidCall  D/Boom!﹕ Authorization: Token 127e7r122y9dyq89ye2
04-24 23:18:04.957  13257-13257/AndroidCall  D/Boom!﹕ Content-Type: application/json
04-24 23:18:04.957  13257-13257/AndroidCall  D/Boom!﹕ Content-Length: 6
04-24 23:18:04.957  13257-13257/AndroidCall  D/Boom!﹕ "1444"
04-24 23:18:04.957  13257-13257/AndroidCall  D/Boom!﹕ ---> END HTTP (6-byte body)
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ <--- HTTP 400 https://serverurl/29522 (97ms)
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Allow: POST, OPTIONS
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Content-Type: application/json
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Date: Sat, 25 Apr 2015 03:17:52 GMT
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Server: Apache/2.4.7 (Ubuntu)
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Vary: Accept,Cookie
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ X-Frame-Options: SAMEORIGIN
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ transfer-encoding: chunked
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ Connection: keep-alive
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ OkHttp-Selected-Protocol: http/1.1
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ OkHttp-Sent-Millis: 1429931884981
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ OkHttp-Received-Millis: 1429931885065
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ {"status": "2"}
04-24 23:18:05.058  13257-13257/AndroidCall  D/Boom!﹕ <--- END HTTP (15-byte body)
04-24 23:18:05.058  13257-13257/AndroidCall  D/AndroidRuntime﹕ Shutting down VM
04-24 23:18:05.058  13257-13257/AndroidCall  W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415c7ba8)
04-24 23:18:05.278  13257-13280/AndroidCall  D/dalvikvm﹕ GC_FOR_ALLOC freed 429K, 5% free 10221K/10684K, paused 21ms, total 21ms
04-24 23:18:05.358  13257-13280/AndroidCall  D/dalvikvm﹕ GC_FOR_ALLOC freed 479K, 5% free 10250K/10764K, paused 21ms, total 21ms
04-24 23:18:05.378  13257-13257/AndroidCall  E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: AndroidCall , PID: 13257
    retrofit.RetrofitError: 400 BAD REQUEST
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:388)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            at $Proxy2.register(Native Method)
            at AndroidCall .app.ui.activities.ListActivity.matchPasscode(ListActivity.java:386)
            at AndroidCall .app.ui.activities.ListActivity.access$200(ListActivity.java:48)
            at AndroidCall .app.ui.activities.ListActivity$6.onClick(ListActivity.java:301)
            at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)


AVL Tree traversals in JTextArea


public class AVLTree
{
   public static String inorderTraversal = " ";

   private static void inorder(AVLNode btree)
    {
       if (btree != null)
       {
         inorder(btree.left);
         inorderTraversal += btree.value + " ";
         inorder(btree.right);
       }
    } 

    /**
       This inorder method is the public interface to
       the private inorder method. It calls the private 
       inorder method and passes it the root of the tree.
    */

    public static void inorder()
    {
        inorder(root);
    }
}

class AVLTreeDemo extends JFrame
implements ActionListener
{

    public void actionPerformed(ActionEvent evt)
    {
        String cmdStr = cmdTextField.getText();
          int size = Integer.parseInt(cmdStr);
        int[] array = new int[size];

        // input validation


        // Random number method
          randNum(array, size);

        // for loop adds numbers to AVL Tree        
        for (int i = 0; i < size; i++)
        {
            int value = array[i];
            avlTree.add(value);
        }
          if (view != null)
                remove(view);
            view = avlTree.getView();            
            add(view);
            pack();
            validate(); 
            cmdResultTextField.setText(" ");

        // inorder method
        AVLTree.inorder();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < size; i++)
        {
            sb.append(String.format(" %2d", size)); // Formats right justified
            if ((i + 1) % 10 == 0)
            {
                sb.append(System.lineSeparator()); // Adds a new line after 10 values
            }
        }
        //inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal));

        // display the array in inorder to the inorder text field
        inorderTextArea.setText(AVLTree.inorderTraversal);
    } 

    /**
      The randNum method randomly selects numbers
      in a given range.
      @param array The array.
      @param num The integer numbers.
   */

     public static void randNum(int[] array, int num)
     {                
        Random rand = new Random();

        // Selection sort method
          selectionSort(array);

        // display duplicates
        /*int last = array[0];
        int count = -1;

        for (int i : array)
        {
            if (i == last)
            {
               count++;
               continue;
            }
            System.out.println("Number " + last + " found " + count + " times.");
            count = 1;
            last = i;
         }*/

        for(int i = 0; i < num; i++)
        {
           // display duplicates
           /*if(num == num - 1)
           {
               System.out.print("Duplicate: " + num);
           }*/

           array[i] = rand.nextInt(500);
        }        
    }
}

I'm trying to display the output of an AVL Tree inorder, preorder, and postorder traversals on multiple lines in the JTextArea, preferably 10 numbers to a line. I tried the 'for' loop I've provided, but I'm getting a compile error. The problem is with inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal));.

Error:

AVLTree.java:527: error: no suitable method found for toString(String) inorderTextArea.setText(sb.toString(AVLTree.inorderTraversal)); ^ method StringBuilder.toString() is not applicable (actual and formal argument lists differ in length) method AbstractStringBuilder.toString() is not applicable (actual and formal argument lists differ in length) method Object.toString() is not applicable (actual and formal argument lists differ in length) 1 error

How can I re-write this line of code to make it work? Thank you for all your help.


Spring MVC From - Request method 'GET' not supported


I am trying to learn Spring MVC but I don't know how to solve this problem. I'm thankful for all the help I can get! Why do I get "Request method 'GET' not supported" when I got to URL "http://localhost:8080/SpringTest3/addStudent.html"

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://ift.tt/ra1lAU"
         xmlns="http://ift.tt/nSRXKP"
         xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP"
         version="3.0">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

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

    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/addStudent.jsp</url-pattern>
        <url-pattern>/addStudent.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>

mvc-servlet.xml:

<beans xmlns="http://ift.tt/GArMu6"
   xmlns:context="http://ift.tt/GArMu7"
   xmlns:xsi="http://ift.tt/ra1lAU"
   xsi:schemaLocation="
   http://ift.tt/GArMu6     
   http://ift.tt/1cnl1uo
   http://ift.tt/GArMu7 
   http://ift.tt/1ldEMZY">

   <context:component-scan base-package="com.springtest3"/>

   <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
   </bean>

   </beans>

StudentController.java:

package com.springtest3;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
public class StudentController {

   @RequestMapping(value = "/students", method = RequestMethod.GET)
   public ModelAndView showStudent() {
      return new ModelAndView("student", "command", new Student());
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("student") Student student, BindingResult result/*, final ModelMap model*/) {
       if (result.hasErrors()) {
           System.out.println("ERROR ERROR ERROR");
       }

       /*model.addAttribute("name", student.getName());
       model.addAttribute("age", student.getAge());
       model.addAttribute("id", student.getId());*/

       System.out.println("Name: " + student.getName());

      return "redirect:students.html";
   }
}

addStudent.html:

<%@taglib uri="http://ift.tt/IED0jK" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Student Information</h2>
<form:form method="post" action="addStudent.html">
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td><form:label path="age">Age</form:label></td>
        <td><form:input path="age" /></td>
    </tr>
    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>


Java + Jersey + Gradle - java.sql.SQLException: No suitable driver found


Having trouble getting SQL working in a Java WebApp that I'm working on. It seems to be an issue with jersey not loading my sql driver.

Getting a java.sql.SQLException: No suitable driver found for jdbc:h2:testDbName when I call my endpoint.

Note that:

  1. the connection string is valid and works when not being run in the WebContainer.

  2. gradle script is configured to correctly place sqldriver (h2 in this case) in lib directory

I've simplified the code to the following:

TestResource.java

@Path("/user")
public class TestResource {

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createForm(@FormParam("name") String name) throws Exception{

        Connection connection = DriverManager.getConnection("jdbc:h2:testDbName");
        connection.close();

        return Response.status(SC_ACCEPTED).build();
    }
}

build.gradle

apply plugin: 'war'

repositories {
    mavenCentral()
}

dependencies {
    compile 'javax.servlet:servlet-api:2.5'
    compile "javax.ws.rs:jsr311-api:1.1.1"
    compile 'com.sun.jersey:jersey-bundle:1.19'

    compile 'com.h2database:h2:1.3.175'
}

webapp.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://ift.tt/ra1lAU" xmlns="http://ift.tt/nSRXKP" xmlns:web="http://ift.tt/LU8AHS" xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/LU8AHS" id="WebApp_ID" version="2.5">

    <servlet>
        <servlet-name>Jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>testPackage</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>


Hibernate is using wrong table name for order by expression with three level inheritance


In our project we have different user types presented by different classes. And we have a BaseEntity class as @MappedSuperclass. When we try to use user classes with InheritanceType.JOINED hibernate creates an sql that we think it is wrong.

Base Entity :

@MappedSuperclass
public abstract class BaseEntity implements java.io.Serializable {


private Integer id;

private Date createdDate = new Date();


public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED_DATE", nullable = true)
public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}

}

Base User

@Entity
@Table(name = "BASE_USER")
@Inheritance(strategy = InheritanceType.JOINED)
@AttributeOverride(name = "id", column = @Column(name = "ID", nullable = false, insertable = false, updatable = false))
public abstract class BaseUser extends BaseEntity{


@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
@SequenceGenerator(name = "seq", sequenceName = "USER_SEQ", allocationSize = 1)
public Integer getId() {
    return super.getId();
}

}

User

@Entity
@Table(name = "FIRM_USER")
public class FirmUser extends BaseUser {

private String name;

@Column(name = "name")
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

Sample Code

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
    try {
        sessionFactory = new AnnotationConfiguration()
                .addAnnotatedClass(FirmUser.class)
                .addAnnotatedClass(BaseUser.class)
                .addAnnotatedClass(BaseEntity.class)
                .configure()
                .buildSessionFactory();
    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
}

public static Session getSession() throws HibernateException {
    return sessionFactory.openSession();
}

public static void main(String[] args) {
    getSession().save(new FirmUser());

    Query query = getSession().createQuery("select distinct a from FirmUser a ORDER BY a.id");
    query.list();

}
}

For this hql

select distinct a from FirmUser a ORDER BY a.id

hibernate creates this sql

select distinct firmuser0_.ID as ID1_0_, firmuser0_1_.CREATED_DATE as CREATED_2_0_, firmuser0_.name as name1_1_ from FIRM_USER firmuser0_ inner join BASE_USER firmuser0_1_ on firmuser0_.ID=firmuser0_1_.ID order by firmuser0_1_.ID

"order by firmuser0_1_.ID" causes

 HSQLDB  : ORDER BY item should be in the SELECT DISTINCT list:

or

 ORACLE : ORA-01791: not a SELECTed expression

But firmuser0_.ID is in select clause and we actually try to order by ID of FirmUser (firmuser0_) not BaseUser (firmuser0_1_)

If we do not use BaseEntity it works as expected.

Why does hibernate use joined class for ordering in case of it also inherits from another class?


sometimes move to element and click event is not working


I am new to selenium web driver and stuck with follows problem. I have written code for hover on Menu and click sub menu in jsp page.in this i have 3 anchor tags that are used to click and redirect to another page.

But the problem is first and last anchors are working properly not second tag. first and last tag action can achieve. But when driver moves to seconds tag which is not respond and says Exception as "No such Element".

How it is possible. Don't know why it doesn't move to that particular tag and trigger that.Kindly help me. Thanks in advance.

    <li style="z-index:1"><a href="welcome.jsp">Business</a>
    <ul><li><a href="ChainPerformance.jsp">Chain Performance</a>
<li><a href="TopXReport.jsp">Top X Report</a><li>
    <a href="ChainTop.jsp">Chain Top</a><li></ul></li>

Code for mouse hover and click:

@Then ("^I hover on (.+) menu and (.+) submenu$")
            public void mousehover(String elementName,String subMenu) throws InterruptedException{
                Actions actions = new Actions(webdriver);
                WebElement menuHoverLink = webdriver.findElement(By.xpath("//a[text() = '" + elementName + "']"));
                actions.moveToElement(menuHoverLink).perform();
                Thread.sleep(2000);
                actions.moveToElement(menuHoverLink).moveToElement(webdriver.findElement(By.xpath("//a[text() = '" + subMenu + "']")));
                Thread.sleep(2000);
                actions.click().perform();
                System.out.println("Sub menu "+subMenu+" Has been clicked");
            }


Post too Large Issue


I'm using Apache 2.4 with Glassfish 2.1 and I keep getting this error with large posts:

java.lang.IllegalStateException: Post too large

I've already tried to change the property maxPostSize of the Glassfish http-listener to a lot of values (and even 0, to accept everything) but nothing seems to work.

Do you guys know of any other thing that might be an issue here?

PS: The post has only 4MB. I think that anything bigger than 2Mb is being rejected.


Greater Than Operator Undefined on Generic Type, Despite extending and implementing Comparable


I searched and found several instances of similar problems but the obvious solutions have already been implemented, so I'm at a bit of a loss. FYI: This is a homework assignment, if it matters.

public class Entry<K extends Comparable<K>, V> implements 
    Comparable<Entry<K, V>> {

    protected K key;
    protected V value;

    protected Entry(K k, V v) {
        key = k;
        value = v;
    }

    public K key() {
        return key;
    }

    public V value() {
        return value;
    }

    // override toString method
    // toString method should print the entry as:
    // <key,value>
    @Override
    public String toString() {
        return "<>" + key.toString() + ", " + value.toString();
    }

    public int compareTo(Entry<K, V> other) {
        if (this.key > other.key)
            return 1;
        else if (this.key == other.key)
            return 0;
        else
            return -1;
    }
}

The error that I'm getting is:

The operator > is undefined for the argument type(s) K, K"

in the first line of the compareTo method.


How are related maven GAV naming an jar naming?


for the following GAV defined in my pom.xml: groupID : org.test artifactID : test-spring-kie version : 0.1.8-SNAPSHOT

I have an exception when my java program looks for a maven resource :

org.eclipse.aether.resolution.ArtifactResolutionException: Could not find artifact org.test:test-spring-kie:pom:0.1.8-SNAPSHOT in local (file:///home/superseed77/.m2/repository)

or

org.eclipse.aether.resolution.ArtifactResolutionException: Could not find artifact org.test:test-spring-kie:jar:0.1.8-SNAPSHOT in local (file:///home/superseed77/.m2/repository)

I believe it's a reference to a jar named test-spring-kie[some separator]0.1.8-SNAPSHOT.jar in the directory .m2/repository/http://ift.tt/1broTOP

Am I right ? What is the mechanism (transformation rules) to find jar name and location against this org.test:test-spring-kie:jar:0.1.8-SNAPSHOT ?

Please help

Thanks a lot


Android Studio – Which .java file is executed when I run tests?


Where can I choose which .java to execute when running an Android Studio test?

I have 3 .java files and only one is being executed.

When searching the project for references for the specific .java which runs every time, I've only found the file name in workspace.xml file which is probably irrelevant.


What is the LocalDate Utils like StringUtils


  private ClientIdentifier(final Client client, final CodeValue documentType, final String documentKey,final LocalDate validity, final String description) {
    this.client = client;
    this.documentType = documentType;
    this.documentKey = StringUtils.defaultIfEmpty(documentKey, null);
    i am confused in this part //this.validity = LocaleUtils.defaultIfEmpty(validity,null);
    this.description = StringUtils.defaultIfEmpty(description, null);
}

I am passing LocalDate but don't know which utility to use for checking defualtIfEmpty


jasper subreport is not getting printed inside main report


i have mainreport and subreport , where main report is getting printed in jasper, but not the subreport, see below code for subreport

<jr:list xmlns:jr="http://ift.tt/1cl9b3L" xsi:schemaLocation="http://ift.tt/1cl9b3L http://ift.tt/1cl9b3P" printOrder="Vertical">
                    <datasetRun subDataset="customerOrderList" uuid="38a2e0f4-ae87-42ad-b3b4-61853d9a2e23">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{customerOrderList})]]></dataSourceExpression>
                    </datasetRun>
                    <jr:listContents height="39" width="590">
                        <frame>
                            <reportElement x="0" y="0" width="590" height="39" uuid="609e3e45-03f6-48d0-8776-e6e393d0dbaf"/>
                            <subreport>
                                <reportElement x="0" y="0" width="590" height="39" uuid="d4ef2aed-7826-49e5-9bb1-7642cbd01279"/>
                                <subreportExpression><![CDATA["src/main/java/com/crafart/reports/customerOrders.jasper"]]></subreportExpression>
                            </subreport>
                        </frame>
                    </jr:listContents>
                </jr:list>

i have debugged the code and see there are no issues in generating the report.

i am passing customer order which contains customer details and list of orders. snippet of my customer bean

public class Customer {
    private String customerName;
    private List<Order> customerOrderList
}

and below code used to generate the report

    List<OrderDeclarationBO> orderDeclarationBOLst = new ArrayList<>();
    orderDeclarationBOLst.add(orderDeclarationBO);
    InputStream in = this.getClass().getResourceAsStream("order.jrxml");
    InputStream jasperIn = this.getClass().getResourceAsStream("order.jasper");
    JasperCompileManager.compileReport(in);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperIn, new HashMap<String, Object>(), new JRBeanCollectionDataSource(orderDeclarationBOLst));
    JasperExportManager.exportReportToPdfFile(jasperPrint, "orderInvoice.pdf");

need help, and dont know what is still required to print subreport.

EDIT :- Adding image of the report, where i am getting null values inside sub report, and not aligned properly

enter image description here


How to use Observable java


I have the following:

abstract class A extends Class C (abstract class C extends D).

private String name="";

public void setFff(double val) {

    double old = fff.getAvg();
    fff.update(val);

    ListIterator<Observer> it = fffListeners.listIterator();
    String ss;

    while (it.hasNext()) {
      ss = name + this.toString();
      it.next().update("fff", fff.getValue(), fff.getAvg(), ss);
    }
}

class B extends D implements Observable

private String name="";
public void notifyObservers() {
        for(Observer observer:fffListeners){
            v=fff.getValue();
             m=fff.getAvg();
            observer.update("fff", v, m, (name+this.getName()));
        }       
    }

interface Observer:

void update(String nn, double bbb, double aaa, String nameThraed);

abstract class E implements Observer

class G extends E.

update in class G is the following

public void update(String string, double v, double m, String s) {

        if ((B.getClass == "G")
                && string.equals("fff")&& (s.equals("B"))) {

             this.fffList.add(m);
            System.out.println("List of fff :" + fffList);

        }
    myMethod(fffList);
}

I want to get all the value of m and put theme in the list fffList when I get a notification from E. How can i do that?


Java how does HashMap identify the key object if hashCode are the same and equals is true?


I always thought hat HashMap is identifying its keys by using hasCode and equals. But this code still does not give me the value back. What am I missing?

import java.util.HashMap;
import java.util.Map;

/**
 * Created by kic on 25.04.15.
 */
public class TypePair {
    private final Class a;
    private final Class b;

    public TypePair(Class a, Class b) {
        this.a = a;
        this.b = b;
    }

    public TypePair(Object a, Object b) {
        this.a = a.getClass();
        this.b = b.getClass();
    }

    public boolean isPair (Object a, Object b) {
        return this.a.isAssignableFrom(a.getClass()) && this.b.isAssignableFrom(b.getClass());
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof TypePair) {
            return a.isAssignableFrom(((TypePair) obj).a) && b.isAssignableFrom(((TypePair) obj).b);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return 1;
    }

    public static void main(String[] args) {
        TypePair a = new TypePair(Number.class, String.class);
        TypePair b = new TypePair(12, "hello");

        Map<TypePair, Boolean> test = new HashMap<>();
        test.put(a, true);

        System.out.println(a.hashCode() == b.hashCode());
        System.out.println(a.equals(b));
        System.out.println("und? " + test.get(a));
        System.out.println("und? " + test.get(b));
    }
}


Prints
true
true
und? true
und? null


SimpleXML java staying in strict mode even if I use strict/required=false


I am trying to use SimpleXML in non strict mode but the only thing that seems to work is to put required=false on every single field. Using false in read or in @Root doesn't seem to turn off strict mode.

MyClass myclass = serializer.read(MyClass.class, new File(args[0]), false);

Results in..

org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.Attribute(name=, required=true, empty=)

I am using SimpleXML java v2.7.1 under Java 1.8.

Any ideas why?


Why can there be an ArrayOutOfBounds Exception when you are opening a file in java using FileInputStream?


Why is there a need to check ArrayIndexOutOfBounds in FileInputStream in java? This same code is given as an example in a book for core java.

FileInputStream fis;
try{
    fis=new FileInputStream("inputFIle.txt");       
}catch(FileNotFoundException e){
    System.out.println("File was not found");
}catch(ArrayIndexOutOfBoundsException e){
    e.printStackTrace();
}


mongodb's text search functionality using java


I need to insert set of news article documents into mongodb database using java.Then for each document j and for each word i, i need to count the number of articles in document j that has used the word i (use mongodb's text search functionality)using java


java file not working when sent over a network


so I was implementing client and socket for java. I wanted to send huge files on tcp through sockets and i was able to send files too but the only problem was the files on the other end were either not complete or not working. I checked the bits are being transfered then what is the error. client code

   Socket sock = new Socket("127.0.0.1", 1056);
    byte[] mybytearray = new byte[1024];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("abc.mp3");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    int len = 0;
    while((len = is.read(mybytearray)) != -1)
    {
    bos.write(mybytearray, 0, len);
    System.out.println("sending");
    }
  
    bos.close();
    sock.close();
  ServerSocket ss = new ServerSocket(1056);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String info = null;
      String request = null;
      System.out.println("sending");      
          String filename = "abc.mp3";
        File fi = new File(filename);
        InputStream fs = new FileInputStream(fi);
        int n = fs.available();
        byte buf[] = new byte[1024];
        out.println("Content_Length:" + n);
        out.println("");
        while ((n = fs.read(buf)) >= 0) {
          out.write(buf, 0, n);
             System.out.println("sending");
        }
        out.close();
        s.close();
        in.close();
                
                }

What are some of the best examples of lock free practices in Java?


I read Brian Goetz's Java concurrency in practice and I started to read some articles and slides of Lock-free programming: Compare-And-Swap, RingBuffer, etc.

I was very glad to see the JDK's ConcurrentHashMap is one good example of replacing one single lock by multiple locks to reduce the lock impact.

I was wondering if there are any other Lock-free programming examples / source code / or best practices in real life, that I can draw more understanding and inspiration from?

Thanks so much!


Very simple calculator?


I'm trying to make a very simple calculator. No GUI yet. The bit I'm stuck on is how to change the user input into numbers that the computer can read and calculate and then print the answer back out. Any help?

import java.util.Scanner;

public class calculator2 {

/**
 * @param args
 */
public static void main(String[] args) {
    Scanner calculation = new Scanner(System.in);
    String calc;
    //application version
    System.out.println("iCalcPro Pre-Alpha");
    //how to use
    System.out.println("Times = *");
    System.out.println("Divide = /");
    System.out.println("Traditional symbols for add and minus.");
    System.out.print("Calculation:");
    calc = calculation.next();
    //print out the input
    System.out.println("Your input: " + calc);
    }
}


issues with a for loop in a user entered array


This is obviously homework but I am having issues with part of the assignment here is that part

"Start by asking the user for how many double values do they want you to read in. Then allows them to input them one at a time. An exception should be thrown if given faulty values. You will store the values read in into an array."

The issue I am having is with the for loop that asks for the user to input the numbers that they want it throws 5 errors I can't figure out or is there an easier way to get user input?. Here is that code for that

//import statements
import java.util.*;     //for scanner class


// class beginning
class  StandardDev {
public static void main(String[] args ) {
    //Declare variables area
    Scanner input = new Scanner (System.in);


    //Collect inputs from user or read in data here
    System.out.println("Welcome to my Standard Deviation and average program!");
    System.out.println("how many numbers do you want to enter? ");
    int number =input.nextInt();
    double [] value = new double [number];


    //Echo input values back to user here
    System.out.println("you want to enter in "+number+" numbers, lets start");


    //main code and calculations to do

    int i;
    for ( i = 0;, i <number;, i++){
        value[i] = input.nextDouble();
        System.prinln("here are the numbers you have entered "+value+"!");
    }
    //Output results here

and if anyone can tell me how to check if the number entered isn't a valid input (is it any different if this wasn't an array?) and am I correctly entering in doubles for the program?


Why JBoss EAP 6.4 fail to load the session using the http session replication mechanism?


I have been using session replication successfully in JBoss EAP 6.1 in Windows. But then I changed to JBoss EAP 6.4 for dev testing in ubuntu and the same code stopped working.

There's not much to it, I just added the <distributable/> tag and didn't added any manual serialVersionUID value to the serialized class Logged.java (it stays annotated to ignore the warnings).

I store the instance of the class in the http session, shutdown the server using jboss-cli.sh --connect command=:shutdown (NOPAUSE=true environment variable), then startup the server again. After server is started, when I try to access the session again I cannot retrieve the class instance and the following error occurs in the console:

...

21:47:13,852 WARN  [org.jboss.as.clustering.web.infinispan] (http-/0.0.0.0:80-1)
 JBAS010322: Failed to load session 9OQtRW3Vgc-uf8w3DmRHD+PK: java.lang.RuntimeE
xception: JBAS010333: Failed to load session attributes for session: 9OQtRW3Vgc-
uf8w3DmRHD+PK
        at org.jboss.as.clustering.web.infinispan.DistributedCacheManager$2.invo
ke(DistributedCacheManager.java:229)
        at org.jboss.as.clustering.web.infinispan.DistributedCacheManager$2.invoke(DistributedCacheManager.java:212)
        at org.jboss.as.clustering.infinispan.invoker.SimpleCacheInvoker.invoke(SimpleCacheInvoker.java:34)
        at org.jboss.as.clustering.infinispan.invoker.BatchCacheInvoker.invoke(BatchCacheInvoker.java:48)
        at org.jboss.as.clustering.infinispan.invoker.RetryingCacheInvoker.invoke(RetryingCacheInvoker.java:85)
        at org.jboss.as.clustering.web.infinispan.DistributedCacheManager$ForceSynchronousCacheInvoker.invoke(DistributedCacheManager.java:550)
        at org.jboss.as.clustering.web.infinispan.DistributedCacheManager.getData(DistributedCacheManager.java:238)
        at org.jboss.as.clustering.web.infinispan.DistributedCacheManager.getSessionData(DistributedCacheManager.java:196)
        at org.jboss.as.web.session.DistributableSessionManager.loadSession(DistributableSessionManager.java:1429) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
        at org.jboss.as.web.session.DistributableSessionManager.findSession(DistributableSessionManager.java:688) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
 at org.jboss.as.web.session.DistributableSessionManager.findSession(DistributableSessionManager.java:84) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
        at org.apache.catalina.connector.Request.doGetSession(Request.java:2661) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
        at org.apache.catalina.connector.Request.getSession(Request.java:2382) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
        at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:791) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
        at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:801) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
        at org.webstories.core.auth.AuthSession.from(AuthSession.java:12) [classes:]
...

I have no idea where to start looking into because I have no knowledge of JBoss internals, except for what is widely documented throughout the web. In this case what is documented is that you just need to add <distributable/> into the web.xml and then session replication will "magically" start working. Of course, you need to declare a class instance as serializable to be able to be serialized, but besides that I see no reason for why it is not working in JBoss EAP 6.4 in Ubuntu.

lsb_release -a:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.2 LTS
Release:        14.04
Codename:       trusty

java -version:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) Client VM (build 25.45-b02, mixed mode)


How to update JList and JTextfield with database HSQLDB?


I use Eclipse and my database is hsqldb. I have a JFrame with 3 JPanel.

In my first JPanel, I have 3 JList, Category, Brands and Product.

In my database, I have a table category (id, name) brands (id, name) product (id, product, price, description, quantity + foreign key on category and Brands).

I started coding but I can not do that when I select one item in JList category and brand, I have to bring up the result in product (one item or multiple) and when I select one item in Jlist Product, I have to bring up the result in the JPanel Informations (price, description and quantity).

Thanks for you help,

Nikolas


Need Java Equivalent of this C# Encryption code


I have the following c# code but need the exact same algorithm in Java. Whether the c# code is quality, I can do nothing about. I only care if the Java encoded string is equivalent.

    //Run GetToken to get encrypted string
    var token = GetToken(AMessage, account_name, api_key);

    private static byte[] GetBytes(string value, byte[] salt, int length)
    {
        var deriveBytes = new Rfc2898DeriveBytes(value, salt);
        return deriveBytes.GetBytes(length);
    }

    private static string GetToken(string session, string accountName, string apiKey)
    {
        byte[] encrypted;

        using (AesManaged aes = new AesManaged())
        {
            var salt = Encoding.Default.GetBytes(apiKey);
            var key = GetBytes(accountName, salt, aes.KeySize / 8);
            var vector = GetBytes(accountName, salt, aes.BlockSize / 8);

            aes.Key = key;
            aes.IV = vector;

            var memoryStream = new MemoryStream();
            using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    using (var writer = new StreamWriter(cryptoStream))
                    {
                        writer.Write(session);
                    }
                }
            }
            encrypted = memoryStream.ToArray();
        }

        return Convert.ToBase64String(encrypted);
    }


spring 4.1.6 Release build issue


I am trying to set up a project using spring 4.1.6. I have tried AbstractAnnotationConfigDispatcherServletInitializer with servlet 3.0 but without any luck. I am using websphere version 8.5.5.

After a lot of search I found out the below post for a similar issue and I was bound to use web.xml based configuration.

Cannot deploy Spring App to Websphere

As per the valuable suggestions I have updated the class loader property of websphere and removed the entries from web.xml after which I am facing the below error.

[4/25/15 17:05:46:985 GST] 00000055 AppManagement W   ADMA0116W: Unable to start: SpringSiteEAR using: WebSphere:name=ApplicationManager,process=server1,platform=proxy,node=Node01,version=8.5.5.0,type=ApplicationManager,mbeanIdentifier=ApplicationManager,cell=Node01Cell,spec=1.0 exception is: javax.management.MBeanException: Exception thrown in RequiredModelMBean while trying to invoke operation startApplication
    at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1299)
    at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:1088)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:831)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:804)
    at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1335)
    at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
    at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1228)
    at com.ibm.ws.management.application.AppManagementImpl._startApplication(AppManagementImpl.java:1482)
    at com.ibm.ws.management.application.AppManagementImpl.startApplication(AppManagementImpl.java:1371)
    at com.ibm.ws.management.application.AppManagementImpl.startApplication(AppManagementImpl.java:1320)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:613)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:68)
    at sun.reflect.GeneratedMethodAccessor12.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:613)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:287)
    at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1256)
    at java.security.AccessController.doPrivileged(AccessController.java:252)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1250)
    at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:1088)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:831)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:804)
    at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1335)
    at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
    at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1228)
    at com.ibm.ws.management.remote.AdminServiceForwarder.invoke(AdminServiceForwarder.java:346)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1497)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:107)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1338)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1430)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:858)
    at javax.management.remote.rmi._RMIConnectionImpl_Tie.invoke(Unknown Source)
    at javax.management.remote.rmi._RMIConnectionImpl_Tie._invoke(Unknown Source)
    at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:669)
    at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:523)
    at com.ibm.rmi.iiop.ORB.process(ORB.java:523)
    at com.ibm.CORBA.iiop.ORB.process(ORB.java:1575)
    at com.ibm.rmi.iiop.Connection.doRequestWork(Connection.java:3039)
    at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2922)
    at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:64)
    at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: com.ibm.ws.exception.RuntimeWarning: com.ibm.ws.webcontainer.exception.WebAppNotLoadedException: Failed to load webapp: Failed to load webapp: javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype
    at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:432)
    at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:718)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1175)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1370)
    at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:968)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:774)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1374)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2179)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:445)
    at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:388)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:116)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:663)
    at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5474)
    at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5600)
    at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:677)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:621)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1266)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:613)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:68)
    at sun.reflect.GeneratedMethodAccessor12.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:613)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:287)
    at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1256)
    at java.security.AccessController.doPrivileged(AccessController.java:252)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1250)
    ... 45 more
Caused by: com.ibm.ws.webcontainer.exception.WebAppNotLoadedException: Failed to load webapp: Failed to load webapp: javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype
    at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:759)
    at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
    at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:426)
    ... 77 more
Caused by: com.ibm.ws.webcontainer.exception.WebAppNotLoadedException: Failed to load webapp: javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype
    at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:176)
    at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
    ... 79 more
Caused by: java.util.ServiceConfigurationError: javax.servlet.ServletContainerInitializer: Provider org.springframework.web.SpringServletContainerInitializer not a subtype
    at java.util.ServiceLoader.fail(ServiceLoader.java:242)
    at java.util.ServiceLoader.access$300(ServiceLoader.java:192)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:380)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:456)
    at com.ibm.ws.webcontainer.webapp.WebAppImpl.initializeServletContainerInitializers(WebAppImpl.java:535)
    at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:409)
    at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
    at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
    ... 80 more

web.xml contents after enabling the class loader property and removing the servlet configs.

  <?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
    xmlns="http://ift.tt/nSRXKP" xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP"
    metadata-complete="false">
    <servlet>
        <display-name>SpringSite</display-name>
        <display-name>SpringSiteStartup</display-name>
        <servlet-name>SpringSiteStartup</servlet-name>
        <servlet-class>main.java.springsite.startup.SpringSiteStartup</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <security-role>
        <role-name>User</role-name>
    </security-role>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>secure connection</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>DELETE</http-method>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>PUT</http-method>
            <http-method>HEAD</http-method>
        </web-resource-collection>
        <user-data-constraint>
            <description>SSL or MSSL not required</description>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

Please find the below pom.xml I am using

    <repositories>
    <repository>
        <id>spring-snasphot</id>
        <url>http://ift.tt/17sHSGD;
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.8.0.RELEASE</version>
        <scope>compile</scope>
        <exclusions>
            <exclusion>
                <artifactId>aspectjrt</artifactId>
                <groupId>org.aspectj</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-tiles2-spring4</artifactId>
        <version>2.1.1.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <scope>compile</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0.20100224</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl-api</artifactId>
        <version>1.2</version>
        <exclusions>
            <exclusion>
                <artifactId>servlet-api</artifactId>
                <groupId>javax.servlet</groupId>
            </exclusion>
        </exclusions>
        <scope>provided</scope>
    </dependency>       
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>${cglib.version}</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>1.1.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Find the below mvn dependency:tree output for my project

[INFO] +- org.springframework.data:spring-data-jpa:jar:1.7.1.RELEASE:compile
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.9.2.RELEASE:compile (version managed from 1.9.1.RELEASE)
[INFO] |  |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.slf4j:slf4j-api:jar:1.7.11:compile - version managed from 1.7.7; omitted for duplicate)
[INFO] |  |  \- (org.slf4j:jcl-over-slf4j:jar:1.7.11:runtime - version managed from 1.7.7; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-orm:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-tx:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.11:compile
[INFO] |  \- (org.slf4j:jcl-over-slf4j:jar:1.7.11:compile - version managed from 1.7.6; scope updated from runtime; omitted for duplicate)
[INFO] +- org.springframework.security:spring-security-config:jar:4.0.1.CI-SNAPSHOT:compile
[INFO] |  +- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework.security:spring-security-core:jar:3.2.7.RELEASE:compile (version managed from 4.0.1.CI-SNAPSHOT)
[INFO] |  |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  \- (org.springframework:spring-expression:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework.security:spring-security-web:jar:4.0.1.CI-SNAPSHOT:compile
[INFO] |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  +- (org.springframework.security:spring-security-core:jar:3.2.7.RELEASE:compile - version managed from 4.0.1.CI-SNAPSHOT; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-expression:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-web:jar:4.1.6.RELEASE:compile - omitted for duplicate)
[INFO] +- org.springframework:spring-aop:jar:4.1.6.RELEASE:compile
[INFO] |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-aspects:jar:4.1.6.RELEASE:compile
[INFO] |  \- org.aspectj:aspectjweaver:jar:1.8.5:compile
[INFO] +- org.springframework:spring-beans:jar:4.1.6.RELEASE:compile
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-context:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-expression:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-context-support:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-core:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework:spring-expression:jar:4.1.6.RELEASE:compile
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-instrument:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework:spring-jdbc:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-tx:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-jms:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- org.springframework:spring-messaging:jar:4.1.6.RELEASE:compile
[INFO] |  |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-tx:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-orm:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-jdbc:jar:4.1.6.RELEASE:compile - omitted for duplicate)
[INFO] |  \- (org.springframework:spring-tx:jar:4.1.6.RELEASE:compile - version managed from 4.0.7.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-oxm:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-test:jar:4.1.6.RELEASE:compile
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-tx:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-web:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-aop:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] +- org.springframework:spring-webmvc:jar:4.1.6.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-expression:jar:4.1.6.RELEASE:compile - version managed from 3.2.13.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-web:jar:4.1.6.RELEASE:compile - omitted for duplicate)

I am stuck with this for the last few days without any luck.


Including trail period and paid version in the software


I am have few questions about the software launch ( I am not sure if this is the correct place to ask but Thank you anyway).

I have built my software using Java, and Converted it to .exe setup using Excelsior.

  1. I want to include trail period/paid version in my software, which includes validating registration codes, etc( Which I am not know). Is there any framework or API or something?

  2. I have searched online for selling software and found websites which offer to sell it ( like 3dcart.com , avangate.com ) which say they only host my software and sell it (with some % of cut) or should I buy my own hosting account (in arvixe.com ) and try to sell my software. Can you please suggest me which I should use like avangate or try to host with my own effort.

Thank You!


Apache Spark TF-IDF Calculation


I am trying to do TF-IDF calculation using spark without the MLIB Library in Java.

I calculate the TF separately for the word and document and IDF separately and then trying to join these two RDDs. But I am getting GC overhead errors. Can someone suggest what I can do to avoid that?

/* links has (document,list(text))  */

    JavaPairRDD<String,String> CommonKey = links
            .flatMapToPair(new PairFlatMapFunction<Tuple2<String, Iterable<String>>, String,String>() {
                @Override
                public Iterable<Tuple2<String,String>> call(Tuple2<String, Iterable<String>> s) {
                    //int urlCount = Iterables.size(s._1);

                    List<Tuple2<String, String>> results = new ArrayList<Tuple2<String, String>>();
                    for (String n : s._2) {

                        String[] itrStrings = n.split("\\s+");
                        for (String a : itrStrings) {
                            if(a != null && !a.isEmpty()) {

                                results.add(new Tuple2<String, String>(a, s._1));
                            }
                        }
                    }
                    return results;
                }
            });


    JavaPairRDD<Tuple2<String,String>, Double> freq = CommonKey
            .mapToPair(new PairFunction<Tuple2<String, String>, Tuple2<String,String>, Double>() {
                @Override
                public Tuple2<Tuple2<String,String>, Double> call(Tuple2<String, String> s) {
                    Tuple2<String, String> TupleKey = new Tuple2<String, String>( s._1,s._2);
                    return new Tuple2<Tuple2<String,String>, Double>(TupleKey,1.0);
                }
            });
    JavaPairRDD<Tuple2<String,String>, Double> wordCount = freq.reduceByKey(new Function2<Double, Double, Double>() {
        public Double call(Double a, Double b) { return  (a + b); }
    });

    /* (word,title),idf */





    JavaPairRDD<Tuple2<String,String>,Double> idffreqCount = CommonKey.distinct().groupByKey()
            .flatMapToPair(new PairFlatMapFunction<Tuple2<String, Iterable<String>>, Tuple2<String,String> ,Double>() {
                @Override
                public Iterable<Tuple2<Tuple2<String,String>,Double>> call(Tuple2<String, Iterable<String>> s) {
                    int dWord = Iterables.size(s._2);

                    List<Tuple2<Tuple2<String, String>,Double>> results = new ArrayList<Tuple2<Tuple2<String, String>,Double>>();

                    for (String n : s._2) {

                        Tuple2<String,String> TupleKey = new Tuple2<String,String>(s._1,n);

                        results.add(new Tuple2<Tuple2<String, String>,Double>(TupleKey, Math.log10(N/dWord)));

                    }

                    return results;
                }
            });



    JavaPairRDD<Tuple2<String,String>,Tuple2<Double,Double>> finalIDF = wordCount.join(idffreqCount);
    JavaPairRDD<Tuple2<String,String>,Double> finalIDFcount = finalIDF.mapValues(new Function<Tuple2<Double,Double>, Double>() {

        public Double call(Tuple2<Double,Double> sum) {
            return sum._1 * sum._2;
        }
    });

Thanks!!


Unable to replicate : "Comparison method violates its general contract!"


I got the error "Comparison method violates its general contract!" when the code was using the following comparator, however I am unable to replicate the exception using jUnit. I'd like to know what caused this issue and how to replicate it. There are examples of others having the same problem but not how to replicate it.

public class DtoComparator implements Comparator<Dto> {

    @Override
    public int compare(Dto r1, Dto r2) {

        int value = 0;

        value = r1.getOrder() - r2.getOrder();

        if (value == 0 && !isValueNull(r1.getDate(), r2.getDate()))
            value = r1.getDate().compareTo(r2.getDate());

        return value;
    }

    private boolean isValueNull(Date date, Date date2) {
        return date == null || date2 == null;
    }
}

The code is called by using:

Collections.sort(dtos, new DtoComparator());

Thanks for any help.

Extra info: The error seemed to occur in the TimSort class inside Java utils and from within a method called mergeLo. Link: http://ift.tt/1z04JGp