2

I have a User class like this :

@Data
@Entity
public class User {
    @Id
    @GeneratedValue
    Long userID;

    String eMail;

    String passwordHash;

    //ArrayList<ClassRoom>adminOf=new ArrayList<>();

    User() {}

    public User(String eMail, String passwordHash) {
        this.eMail = eMail;
        this.passwordHash = passwordHash;
    }
}

And in a LoadDatabase class I have :

@Bean
CommandLineRunner initDatabase(UserRepository userRepository) {
    return args -> {
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "asdasd")));
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "12345")));
    };
}

Which give me this :

spring boot pre-loading

Now in when I give curl -v localhost:8080/user this command it gives me this :

spring-boot curl get

Which is pretty correct, although it gives me email instead of eMail.

But when I give

curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"admin1@admin.com"}'

it says :

spring-boot curl post

Which is pretty horrific. I'm following this tutorial.

And here is my UserController class:

package com.mua.cse616.Controller;


import com.mua.cse616.Model.User;
import com.mua.cse616.Model.UserNotFoundException;
import org.springframework.web.bind.annotation .*;

import java.util.List;

@RestController
class UserController {

    private final UserRepository repository;

    UserController(UserRepository repository) {
        this.repository = repository;
    }

    // Aggregate root

    @GetMapping("/user")
    List<User> all() {
        return repository.findAll();
    }

    @PostMapping("/user")
    User newUser(@RequestBody User newUser) {
        return repository.save(newUser);
    }

    // Single item

    @GetMapping("/user/{id}")
    User one(@PathVariable Long id) {

        return repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }

    @PutMapping("/user/{id}")
    User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

        return repository.findById(id)
                .map(employee -> {
                    employee.setEMail(newUser.getEMail());
                    employee.setPasswordHash(newUser.getPasswordHash());
                    return repository.save(employee);
                })
                .orElseGet(() -> {
                    newUser.setUserID(id);
                    return repository.save(newUser);
                });
    }

    @DeleteMapping("/user/{id}")
    void deleteUser(@PathVariable Long id) {
        repository.deleteById(id);
    }
}

Put method after updating :

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

    return repository.findById(id)
            .map(employee -> {
                employee.setEMail(newUser.getEMail());
                employee.setPasswordHash(newUser.getPasswordHash());
                return repository.save(employee);
            })
            .orElseGet(() -> {
                newUser.setUserID(id);
                return repository.save(newUser);
            });
}

Now there arise two questions.

  • Why email instead of eMail, what to do to get eMail instead of email
  • How to POST correctly, what I'm doing wrong?
Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
  • "*Why `email` instead of `eMail`, what to do to get `eMail` instead of email*" - That is how jackson behaves. There are annotations, e.g. `@JsonProperty`, to control its behaviour. See [this question](https://stackoverflow.com/questions/12583638/when-is-the-jsonproperty-property-used-and-what-is-it-used-for) for details. --- "*How to `POST` correctly, what I'm doing wrong?*" - Have you tried to set `@PutMapping(..., consumes = MediaType.APPLICATION_JSON_VALUE, ...)`? --- A remark: please limit yourself to one question per post in the future. – Turing85 Jul 28 '19 at 06:56
  • 1
    which operating system you are using? – rimonmostafiz Jul 28 '19 at 07:11
  • From next time I will try to keep that in mind... I'm on windows 10... – Maifee Ul Asad Jul 28 '19 at 07:15

2 Answers2

3

"Why email instead of eMail" - That is just the default behavior of Jackson.

"what to do to get eMail instead of email" - You can control Jackson's behavior through annotations on the POJO. The relevant here is @JsonProperty. See this question for details.

"How to POST correctly, what I'm doing wrong?" - You mean PUT instead of POST, don't you? Define the content type consumed by the method:

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
    ...
}

Also, as was pointed out by @rimonmostafiz, you need to redefine your curl call, escaping the quotation:

curl -X PUT -H "Content-Type: application/json" -d "{ \"email\": \"asd\", \"passwordHash\": \"sad\" }"

As an aside: Please limit yourself to one question per post in the future.

Turing85
  • 18,217
  • 7
  • 33
  • 58
-1

Add missing consumes attribute on @PutMapping annotation,

@PutMapping(path= "/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

although it gives me email instead of eMail

It all depends on your getter/setter of property eMail in your User entity. I think your getter must be getEmail() and hence conventionally you get in response email as JSON property.

ScanQR
  • 3,740
  • 1
  • 13
  • 30
  • The `path` setting worked but ...still gives me error .. Please see [here](https://i.stack.imgur.com/92ZMT.png) Command was : `curl -X POST localhost:8080/user -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"adminasd@admin.com"}'` – Maifee Ul Asad Jul 28 '19 at 07:21
  • @MaifeeUlAsad you are `PUT`ing on the wrong endpoint (`/3` is missing in the url...) – Turing85 Jul 28 '19 at 07:24
  • You are not using correct API. Your logs says you are using API /user with POST method. Your questions is for /user/{id} and PUT. – ScanQR Jul 28 '19 at 07:24
  • `PUT` doesn't work too... [Here](https://i.stack.imgur.com/SxhO2.png) is the result... It says : `"status":405,"error":"Method Not Allowed","message":"Request method 'PUT' not supported","path":"/user"` – Maifee Ul Asad Jul 28 '19 at 07:28
  • @MaifeeUlAsad please elaborate and show us what you mean exactly – ScanQR Jul 28 '19 at 07:28
  • @MaifeeUlAsad again, you are `PUT`ing on the wrong enpoint. Try `curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"adminasd@admin.com"}'` – Turing85 Jul 28 '19 at 07:29
  • @Turing85 it gives me : `{"timestamp":"2019-07-28T07:30:16.766+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/user/3"}` – Maifee Ul Asad Jul 28 '19 at 07:30
  • @MaifeeUlAsad again you are not using correct API endpoint. Please refer to correct API. /user/{id} with PUT method is correct API. – ScanQR Jul 28 '19 at 07:31
  • Both doesn't work... Please see [here](https://i.stack.imgur.com/N2eWI.png)... One says `Request method 'POST' not supported`, other says `Content type 'application/x-www-form-urlencoded' not supported` – Maifee Ul Asad Jul 28 '19 at 07:34
  • @MaifeeUlAsad have you tried substituting `'` with `"` in your `curl` command as was suggested by @rimonmostafiz? – Turing85 Jul 28 '19 at 07:35
  • ... and this is why we do not post speculative answers. All this discussion should be on the question, not on this answer... – Turing85 Jul 28 '19 at 07:37
  • @MaifeeUlAsad ' is not an issue. Show your PUT API after suggested answer. – ScanQR Jul 28 '19 at 07:40
  • try substituting `Content-type`with `Content-Type` in your `curl` call. – Turing85 Jul 28 '19 at 07:43
  • I have given the new API in question , please see... as is is quite big and messy for question .. – Maifee Ul Asad Jul 28 '19 at 07:46
  • @MaifeeUlAsad your update to PUT is fine. Check rimonmostafiz suggestion for curl command. I think after that it should solve your issue. – ScanQR Jul 28 '19 at 08:03