JOIN two tables JPQL

@Entity
@Table(name="tblUser")    
public class User {

@Id
@GeneratedValue
@Column(name="id")
private Long id;

@Column(name="email",nullable=false)
private String email;

@Column(name="password",nullable=false)
private String password;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@OneToMany(mappedBy="user")
private List<Address> addresses = new ArrayList<>();
}



@Entity
@Table(name="tblAddress")
public class Address {

@Id
@GeneratedValue
@Column
private Long id;

@Column
private String streat;

@Column
private String number;

@ManyToOne(fetch=FetchType.EAGER)
private User user;
}



public interface UserService {
List<User> findAll(); 
}



@Service
public class JpaUserService implements UserService {
@Autowired
private UserRepository userRepository;

@Override
public List<User> findAll() {
    return userRepository.findAll();
    }
}



@Controller
@RequestMapping(value="/api/users")
public class ApiUserController {

@Autowired
private UserService userService;

@Autowired
private UserDTOToUser toUser;

@Autowired
private UserToUserDTO toDto;

@RequestMapping(method=RequestMethod.GET)
ResponseEntity<List<UserDTO>> getUser()

List<User> users = userService.findAll();

if(users == null || users.isEmpty()){
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<>(toDto.convert(users), HttpStatus.OK);
    }
}



@Repository
public interface UserRepository extends JpaRepository<User, Long> {

@Query("select u.id, a.number FROM User u LEFT JOIN u.addresses a WHERE u.id = a.user")
List<User> findAll();
}

Hi everyone. I am new to Spring/Hibernate concepts and i have some problems with JPQL query. When i try to run my code in RestClient on my localhost, i get this exception:

{

“timestamp”: 1511105123172,

“status”: 500,

“error”: “Internal Server Error”,

“exception”: “java.lang.ClassCastException”,

“message”: “[Ljava.lang.Object; cannot be cast to jwd.wafepa.model.User”,

“path”: “/api/users”

}

Just to mention, that UserDTO is User class without password parameter.

Can you help me how to write proper JOIN query in JPQL?

Querydsl BeanPath.instanceOf() not working on projection

I had a problem when i tried to project instance type of abstract class.

I have 3 classes using Inheritance as Joined.

@Inheritance(strategy = InheritanceType.JOINED)
@Table(name ="abs")
abstract class abs {}

@Table(name="a")
class a extends abs {}

@Table(name="b")
class b extends abs {}

And the Dto to project results like this:

class Dto {private Boolean isTypeA;}

When i execute the query bellow:

new JPAQuery<>(em)
        .select(Projections.bean(Dto.class, Expressions.asBoolean(abs.instanceOf(A.class)).as("isTypeA")))
                .from(a)
        .fecth();

Ocurrs a syntax error after END of case when statament in SQL generated as follow:

SELECT
                CASE
        WHEN a.ID IS NOT NULL
        THEN 1
        WHEN b.ID IS NOT NULL
        THEN 2
        WHEN abs0_.ID IS NOT NULL
        THEN 0
        END=? AS col_0_0_
        FROM ABS abs0_,
                A a,
                B b
        WHERE abs0_.ID=a.ID(+)
        AND abs0_.ID  =b.ID(+)

ORA-00923: keyword FROM not found where expected

To be clearly, when i the instanceOf expression in where claulsule, it’s works fine.

querydsl v.: 4.1.4
hibernate v.: 4.3.11.Final

Error using Netty with Spigot

I want to develop a networksystem for Spigot.
To transfer data I use a packet system, but everytime I try to start the server the following error occurs:

    [16:31:51 WARN]: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:213) ~[spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:232) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:218) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:769) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.channel.AbstractChannel$AbstractUnsafe$5.run(AbstractChannel.java:568) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:341) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.util.concurrent.SingleThreadEventExecutor.confirmShutdown(SingleThreadEventExecutor.java:640) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:358) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116) [spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_151]
Caused by: java.lang.IndexOutOfBoundsException
        at io.netty.buffer.EmptyByteBuf.readInt(EmptyByteBuf.java:470) ~[spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at de.zettee.pixelcloud.client.handler.PacketDecoder.decode(PacketDecoder.java:14) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.decodeLast(ByteToMessageDecoder.java:297) ~[spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:208) ~[spigot_server.jar:git-Spigot-c3c767f-33d5de3]
        ... 9 more

I know it’s in the PacketDecoder, but when the server is starting, nothing is sent to the client which he could decode. I don’t know why the error happens.

If you need the classes:

PacketDecoder:
https://pastebin.com/a96GtaJd

NetworkHandler:
https://pastebin.com/udZypz0j

Mainclass + Client:
https://pastebin.com/WEGDCUXw

Oh and I should say that I’m using Netty 1.4.17
I hope someone can help me with this.
Thanks in advance!

Determine Neo4j database version

The Neo4j Java API automatically updates outdated databases to the current version when I call

new GraphDatabaseFactory().newEmbeddedDatabase(File storeDir)

I would like to check what version the database is before doing that. Is there a way to do that with the Java API? Or alternatively: Where is the database version stored so I can read it out manually?

Getting error that I can’t understand

The below code is giving me a “Cannot invoke nextDouble() on the primitive type double” error. I’m fairly new to Java, can anyone provide some guidance on what’s causing it?

public static double[][] getArray(int row,int column){

    double [][] a = new double[row][column];
    double input;

    for (int x=0; x<a.length; x++){
        for (int y=0; y<a[x].length; y++){
            a[x][y] = input.nextDouble();
        }
    }

    return a;
}

How to test File.delete() function in Junit

I have one method like below:

public final class someTask {
     public void sampleMethod(String filePath) {
         //It is calling Files.delete() method.
         Files.delete(new File(filePath).toPath)
     }
 }

When I test above method(for example ValidRecord in that file, Valid file parameter or not etc) test cases, most of the time my test case failed. Please some one can help me how to test for above cases.

To get file I am using below snippet

@Mock
File f;

@Rule
ExpectedException exception = ExpectedException.none();

PowerMockito.whenNew(File.class).withArguments(VALID_Path).thenReturn(fileMock);
PowerMockito.when(fileMock.exists()).thenReturn(true);
PowerMockito.when(fileMock.isFile()).thenReturn(true);

WHILE loop. Issue when trying to allow the game (guess the number between 1-1000) to be replayed without re-running the code, by inputting ‘q’

The problem I believe lies in this piece of code, I included the game at the bottom for context. To re-iterate, when I input ‘q’ at any point when running the code it should restart the game. I appreciate any constructive criticism.

public static void main(String []args)
{
    Scanner input = new Scanner(System.in);

    int number = (int) (Math.random() * 1000) + 1;
    int guess = 0;
    int count = 0;
    String quit = "";
    //string input = "";

    while(!(quit.equals("q")))
    {
        Integer.toString(guess);

        guess = guess + quit; // issue arrises when trying to convert String to int
        //use guess - convert to suitable datatype to compare

        //save input as guess

This is the code for the guessing the number game:

while(guess != number)

{

System.out.println("Guess the number: ");

guess = input.nextInt();


if(guess > number)

{

System.out.println("The number is lower.");

}

else if (guess < number)

{

System.out.println("The number is higher.");

}

else

{

System.out.println("Well done! You guessed the lucky number.");

}

}   

count++;

}    


}
}

Java Spring: Form Data Binding

I am working on a Spring Boot web application which is to create a form with multiple fields related to other objects (AKA nested objects). I want to bind the data to those objects such that the object is created if it does not exist but should be referenced if it does. My current implementation is:

Form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <body>    
        <div>
            <ul id="messages" th:with="notifyMessages=${session[T(personregistrationform.services.NotificationServiceImpl).NOTIFY_MSG_SESSION_KEY]}">
                <li th:each="msg : ${notifyMessages}" th:text="${msg.text}" th:class="${#strings.toLowerCase(msg.type)}"></li>
                <span th:if="${notifyMessages}" th:remove="all" th:text="${session.remove(T(personregistrationform.services.NotificationServiceImpl).NOTIFY_MSG_SESSION_KEY)}"></span>
            </ul>
            <div>
                <form th:object="${person}" th:action="@{/person}" method="post">
                <input type="hidden" th:field="*{id}"/>
                <div class="form-group">
                <label>Name*</label>
                <div class="col-sm-12">
                <input type="text" class="form-control" th:field="*{name}"/>
            </div>

            <div class="form-group">
                <label class="col-sm-6 control-label">Degree*</label>
                    <div class="col-sm-12">
                        <input type="text" class="form-control" th:field="*{degree}" id="degreeName"/>
                    </div>
            </div>

            <div class="col-sm-12 p-0 my-3 w-100" align="center">
                <button type="submit" id="submitButton">Submit
                </button>
            </div>
        </div>
    </body>
</html>

Here the person object is the main entity in which i want to insert data with a reference to the degree object.

Person.java

@Entity
@Table(name = "Persons")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "degree_id", columnDefinition="integer", foreignKey = @ForeignKey(name = "person_degree"))
    private Degree degree;

    public Integer getId() {
        return id;
    }

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

    public Degree getDegree() {
        return degree;
    }

    public void setDegree(Degree degree) {
        this.degree = degree;
    }
}

Degree.java

@Entity
@Table(name = "Degrees")
public class Degree {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "degree_id")
    private Integer id;

    @NotNull
    private String name;

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

    public String getName() {
        return name;
    }

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

    public Integer getId() {
        return id;
    }
}

PersonController.java

@Controller
public class PersonController {

    @Autowired
    private DegreesService degreesService;

    @Autowired
    @Qualifier("personValidator")
    private Validator personValidator;

    @InitBinder
    public void initBinderAll(WebDataBinder binder) {
            binder.registerCustomEditor(Degree.class, new DegreePropertyEditor(degreesService));
            binder.registerCustomEditor(String.class, new ReplaceEmptyStringsWithNullPropertyEditor());
            binder.addValidators(personValidator);
    }

    private PersonService personService;

    @Autowired
    public void setPersonService(PersonService personService) {
            this.personService = personService;
    }

    @RequestMapping("/")
    public String newPerson(Model model) {
            model.addAttribute("person", new Person());
            return "form";
    }

    @RequestMapping(value = "person", method = RequestMethod.POST)
    public String savePerson(@Valid Person person, BindingResult personRegistrtionResult) {
        if (personRegistrationResult.hasErrors()) {
                notifyService.addErrorMessage("Unable to complete registration, make sure all fields marked with an asterisk (*) are filled");
            List<FieldError> errors = personRegistrationResult.getFieldErrors();
            for(int i=0; i<errors.size(); i++)
                notifyService.addErrorMessage(errors.get(i).getDefaultMessage());
            return "form";
        } else {
            personService.saveperson(person);
            notifyService.addInfoMessage("Registration successful");
            return "formresult";
        }
    }

DegreePropertyEditor.java

public class DegreePropertyEditor extends PropertyEditorSupport {

    private DegreesService degreesService;

    public DegreePropertyEditor(DegreesService degreesService) {
            this.degreesService = degreesService;
    }

    @Override
    public void setAsText(String name) {
            if (name == null || name.equals("")) {
                    setValue(null);
            } else {
                    boolean exists = false;
                    int index = -1;
                    List<Degree> degrees = degreesService.getAllDegrees();
                    for (int i = 0; i < degrees.size(); i++) {
                            if (degrees.get(i).getName().equals(name)) {
                                    exists = true;
                                    index = i;
                                    break;
                            }
                    }

                    Degree degree;
                    if (exists) {
                            degree = degrees.get(index);
                    } else {
                            degree = new Degree();
                            degree.setName(name);
                    }
                    setValue(degree);
            }
    }
}

Problem:

All this code works fine and the data is inserted successfully. However, if the form validation fails and the page is reloaded with the error message, the degree text input shows the object reference of the degree object instead of the name. This is due to the fact that the DegreePropertyEditor replaces the text value with the object.

For example, if Bachelor’s of engineering is typed in the degree field, and the form validation passes since the other fields are also correctly entered, this degree is inserted in the database and the id of this degree is inserted in the person table. Next time if the same degree is typed, the reference to this degree is inserted in the new person and the degree object is not created anew. However, if the validation fails, the page is reloaded with the error message on the top and the degree field now contains something like application.domain.Degree@69a4171a instead of “Bachelor’s of engineering”.

Tried solutions:

After much searching, I found a few solutions but none of them worked hence asking this question. These were:

  1. Tried changing the th:field="*{degree}" to th:field="*{degree.name}" which then handles the conversion itself and does not require/use the property editor. However in this case the degree object is always newly created and a new row is added to the database with the same degree. Also, I am performing a few operations on the names of some other fields (like adding/deleting text before creating the object) which wont be possible in this case.
  2. Tried implementing Converters but they dont get called after being registered (I am sure they get registered because I placed a breakpoint on the addFormatters method and it did register them but when I placed breakpoints inside the convert method of my custom converters, they were never hit and the code did not pause.

I think i have elaborated my problem enough. I am not much experienced in spring so any help would be appreciated.

Cheers

JEE webapp supporting login in other websites

i want to developp a jee webapp to compare prices between my supplier and my e-commerce website running Magento. the problem is that i need to log in my suplier website first to get my reseller prices. so my app will need to login in their website and then explore their pages to gather reseller prices instead of regular prices that i get if i parse the website directly.

how can i realize this ??

Thanks in advance .

This is my supplier website : Disway