java – ResponseStatusException – Spring boot – Retorno da massagem

Sou novo em java e estou criado um API afim de treinamento e mim deparei com o seguinte problema:

Faça a requisição via postman, o retorno do JSON esta ok, mas se faço uma busca que não retorna nada o modelo de mensagem abaixo e retornado:

{
    "timestamp": "2020-06-04T23:52:13.722+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/api/produtos/2"
}

Ate aqui tudo bem, o que acontece é que a atributo message não e preenchido.

Uso o org.springframework.web.server.ResponseStatusException.ResponseStatusException do Spring.

    @RestController
    @RequestMapping("/api/produtos/")
    public class ProdutoController {
        @Autowired
        ProdutoService produtoService;

        @GetMapping("{id}")
        public Produto getById(@PathVariable Integer id) {
            return produtoService.findById(id)
                    .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Produto não encontrado."));

        }
    }



    @Service
    public class ProdutoService {
       @Autowired
       ProdutoRepository produtoRepository;

       public Optional<Produto> findById(Integer id){
          return produtoRepository.findById(id);
        }
    }

spring – Layered architecture horizontal dependencies

I’m working on a spring boot REST service.

It’s divided into three layers: REST controllers, services, persistence/DAO.

We have multiple services and persistence repositories. We have the following situation:
Service-1 needs to access the persistence layer under Service-2. One of our colleagues added a direct dependency from Service-1 to the persistence layer of Service-2 (red arrow).

I would have added the dependency so that Service-1 depends on Service-2, and not the persistence layer under Service-2 (green arrow). I cannot really explain the reasoning, but it I feel like it’s a more “proper” way to introduce a dependency (to depend on higher level component in essence).

Can you give some input on the subject, and provide a good explanation in terms of software design.

enter image description here

How to generate confirmation code without conflict in Spring Boot API?

I am making an website that has register and login functionality which works fine. However, I want to add confirmation code process after the registration process.

I can create a random confirmation code in frontend(Angular) side and send with SMTP protocol to user email account and user should enter this confirmation code in 2 minutes. However when I think more, it can cause a conflict(very slight possibility but not impossible) like it can be generated same confirmation code in 2 minutes.

So, now I decided to generate confirmation code in backend side(Spring Boot) and make the confirmation checking in backend side. So, in backend side I should control the generated confirmation code is generated already in 2 minutes.

So, I can use a dynamic list that has active confirmation codes and search the generated confirmation code in the list. If the code exist in the list, then create another one until the list doesn’t have.

How can I create a dynamic global list that can be visible among all different request in Spring Boot?
Or there is another way(best practice) for this confirmation process?

Spring Batch what is the scope of slave step

In Spring Batch when using a partitioner, What is the scope for slave step? Is there a new bean of slave step created for each execution context?

Cannot render JSP or ThymeLeaf html with Spring

I am a new to using Spring and have a simple application in which I would like to render a simple JSP/Thymeleaf file. When I add the needed dependencies with these corresponding artifact ids to my pom.xml file for JSP (tomcat-embed-jasper, jstl) or for ThymeLeaf (spring-boot-starter-thymeleaf) my IDE indicates that none of these dependencies can be found. When I run my application I get the default error message for when I try to render these pages. I have checked that my view resolver is working as I can see that my return statement in my application controller class directs to the correct .jsp file under my WEB-INF directory. I am running the project directly from intellij. Does anyone know if not having these dependencies is the issue or if it is something else? How do I get the dependencies to actually work? Thanks!

Example of open api 3.0 maven plug-in spring boot using the smallest amount of external dependencies

I’ve used swagger codegen (now open api codegen) for a few years now (in my professional and personal projects). I am looking to create a tutorial on open api maven plugin, and in order to not confuse others, I would like it to use as little dependencies as possible (i.e. use the http client from the jdk instead of bringing in Apache http client). Additionally, I would like the dependencies that are brought in to be dependencies managed by the spring boot (version 2.3.0) parent BOM wherever possible.

Can someone please provide an example of this? For reference, I am using java 14 and spring boot version 2.3.0

Thanks,
Connor

java – Migrar proyecto Maven Spring boot de Netbeans a Intellij Idea

Actualmente trabajo con Java Maven Spring Boot y Spring Cloud, la cosa es que uso el IDE Netbeans y cada proyecto tiene varios archivos xml de configuración propios de Netbeans. Como nbactions-api-demo-local.xml, otro nb-configurations-xml. Pero quiero migrar a usar Intellij Idea pero no encuentro mayor información de como replicar esas mismas configuraciones. Si alguien ya ha podido hacer eso o conoce mejor el ide de Intellij Idea que me pudera orientar ya que la documentación que encuentor no me dice mucho.

Spring Sale! – KVM – OpenVZ – 3.7Ghz Core | 1Gbps | SSD | RAID10 | DDOS – $12/yr | NewProxyLists

Over 25 years in business, Watta Server has the experience in the hosting industry to know how to do it right.

We do a lot more than just hosting, we are a full service hosting company. If you need a control panel installed like cpanel, webmin or tcadmin: we can do it for you. If you need us to secure your server, setup and config a firewall, or just monitor your server security or uptime: we can do it for you. If you need us to migrate your data or systems, or create a cluster for more computing power: we can do it for you. 38 Datacenters worldwide with 100+ available servers, we have what you need. Everything from web servers, domain servers, game servers, database servers, voice servers, web design, web development, or an ecommerce web site: we have the knowledge and experience to take care of you.

We have been around since 1994 because we genuinely care about our customers. We are here for YOU! Our USA Based support and tech staff are online 24/7 available to support you, and will work with you through the entire process from start to finish. Give us a try, test us! Submit a support ticket today and see how fast our response time is!

Pride in our Network!
We maintain facilities located across the US and Europe to ensure the best response times and latency times. Our highly scalable network with more than 1000+ Gigabit per second network capacity has diverse paths from each of our datacenters to provide for industry-leading quality fiber optic connectivity through such providers as Internap, Level3, Savvis, Spectrum, Comcast, Telia, Zayo, Hibernia, GTT, Time Warner Cable, Qwest, CenturyLink, Abovenet, and Cogent. Our fully redundant, load balanced, core network and backbone connectivity is unsurpassed in its efficiency and performance. This unique combination provides a superior network infrastructure with an unmatched quality of service.

Thousands of clients around the globe choose Watta Server for the superior reliability our world-class data centers provide, with unparalleled security, network availability, capacity, processing power and operations management. With your IT infrastructure safe in our data centers, you can focus on cutting operational costs and on managing your core business success, not its servers.

WattaServer.com
Watta OpenVZ VPS
Watta KVM VPS
Watta Dedicated Server

Available Data Center Locations:
Seattle, WA = OpenVZ
Dallas, TX = KVM

What’s included with your VPS:
SolusVM Control Panel to manage your VPS.
CentOS, Fedora, Ubuntu, Debian and many other OS available!
Windows Server 2012 Available for KVM VPS!
CPanel, DirectAdmin, and Webmin Control Panels Available!
Managed Server Services Available!
Offsite Backup Available!
Additional IPs Available!
1Gbps Uplink Port On All VPS Containers
10Gbps Uplink Port On All VPS Nodes
SSD Hard Drives On All Nodes
RAID-10 Redundancy On All Nodes
DDoS Protection up to 10Gbps – Automated Null Route at 10+Gbps spike
SLA 99.99% Uptime at all our datacenters

====================================================

OpenVZ Virtual Private Servers

OVZ-VPS-128
128MB RAM / 128MB vSwap
5GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
250GB Transfer
10Gbps DDoS Protection Included
$12.00/yr
(ORDER NOW)

OVZ-VPS-256
256MB RAM / 256MB vSwap
10GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
500GB Transfer
10Gbps DDoS Protection Included
$18.00/yr
(ORDER NOW)

OVZ-VPS-512
512MB RAM / 512MB vSwap
20GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
1TB Transfer
10Gbps DDoS Protection Included
$36.00/yr
(ORDER NOW)

——————————————————
Network Info:
Seattle, WA Datacenter

Test IPv4:
ping 74.121.188.138
ping 207.244.149.242
Test File: 100MB.test / 1000MB.test

==============================================

KVM Virtual Private Servers

KVM-VPS-128
128MB RAM / 128MB vSwap
5GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
250GB Transfer
10Gbps DDoS Protection Included
$18.00/yr
(ORDER NOW)

KVM-VPS-256
256MB RAM / 256MB vSwap
10GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
500GB Transfer
10Gbps DDoS Protection Included
$24.00/yr
(ORDER NOW)

KVM-VPS-512
512MB RAM / 512MB vSwap
20GB RAID-10 SSD Storage
1 CPU Core @ 3.70Ghz
1Gbps Uplink
1TB Transfer
10Gbps DDoS Protection Included
$48.00/yr
(ORDER NOW)

KVM-VPS-1024
1GB RAM / 1GB vSwap
40GB RAID-10 SSD Storage
2 CPU Cores @ 3.70Ghz
1Gbps Uplink
2TB Transfer
10Gbps DDoS Protection Included
$6.00/mo
(ORDER NOW)

KVM-VPS-2048
2GB RAM / 2GB vSwap
80GB RAID-10 SSD Storage
2 CPU Cores @ 3.70Ghz
1Gbps Uplink
4TB Transfer
10Gbps DDoS Protection Included
$12.00/mo
(ORDER NOW)

KVM-VPS-4096
4GB RAM / 4GB vSwap
160GB RAID-10 SSD Storage
2 CPU Cores @ 3.70Ghz
1Gbps Uplink
4TB Transfer
10Gbps DDoS Protection Included
$22.00/mo
(ORDER NOW)

——————————————————
Network Info:
Dallas, TX Datacenter

Test IPv4:
ping 107.155.96.14
ping 23.227.186.94
Test File: 100MB.test / 1000MB.test

==============================================

● Watta Server is a brand of ONeil Online, founded in 1994 @ Seattle, WA.
● Read what our customers have to say! Customer Testimonials!
● Network Details, Realtime Status, Test IPs, Test File links and more info can be found here
● Sorry, IPv6 only available at our Chicago datacenter.
● Warez-related, Bulk Mail, and Spam-related activities are strictly forbidden. Please review our TOS and AUP prior to ordering.
● We accept PayPal, Stripe, VISA and MasterCard payments. No Bitcoin.
● Promotional offers cannot be combined with other promotional offers.

Do you have a question? Feel free to hop on live chat for a quick talk @ www.WattaServer.com.

Thanks for your interest!

Evitar la creación de registros con valor null en llave foránea al eliminar un registro en spring boot?

Hola estoy trabajando en Java con Spring boot y les comento tengo una tabla factura que tiene una relación de uno a muchos con una tabla factura_items. El problema es que al eliminar registros de la tabla factura_items, se me crea un registro con el valor de null en el campo factura_id y según he estado investigando esto sucede ya que la tabla factura_items vendría a ser la hija de la tabla factura y tienes una relación ManytoOne con factura. Conocen de pronto como evitar que se cree este registro con valor null en el campo foráneo al momento de eliminar un registro?

La clase Factura es:

@Entity

@Table(name = “facturas”)
public class Factura implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty
private String descripcion;

private String observacion;

@Temporal(TemporalType.DATE)
@Column(name = "create_at")
private Date createAt;

@ManyToOne(fetch = FetchType.LAZY)
private Cliente cliente;

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "factura_id",nullable = false)
private List<ItemFactura> items;

@NotNull
@Enumerated(EnumType.ORDINAL)
@Column(name = "estado_factura")
private EEstado eestado;

public Factura() {
    this.items = new ArrayList<ItemFactura>();
}

@PrePersist
public void prePersist() {
    createAt = new Date();
}

public Long getId() {
    return id;
}

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

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public String getObservacion() {
    return observacion;
}

public void setObservacion(String observacion) {
    this.observacion = observacion;
}

public Date getCreateAt() {
    return createAt;
}

public void setCreateAt(Date createAt) {
    this.createAt = createAt;
}

public Cliente getCliente() {
    return cliente;
}

public void setCliente(Cliente cliente) {
    this.cliente = cliente;
}

public List<ItemFactura> getItems() {
    return items;
}

public void setItems(List<ItemFactura> items) {
    this.items = items;
}

public void addItemFactura(ItemFactura item) {
    this.items.add(item);
}

public EEstado getEestado() {
    return eestado;
}

public void setEestado(EEstado eestado) {
    this.eestado = eestado;
}

public Double getTotal() {
    Double total = 0.0;
    int size = items.size();
    for (int i = 0; i < size; i++) {
        total += items.get(i).calcularImporte();
    }
    return total;
}

}

La clase ItemFactura es:

@Entity

@Table(name = “facturas_items”)
public class ItemFactura implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Integer cantidad;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "producto_id")                               
private Equipo producto;

public Long getId() {
    return id;
}

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

public Integer getCantidad() {
    return cantidad;
}

public void setCantidad(Integer cantidad) {
    this.cantidad = cantidad;
}

public Double calcularImporte() {
    return cantidad.doubleValue() * producto.getPrecio();
}

public Equipo getProducto() {
    return producto;
}

public void setProducto(Equipo producto) {
    this.producto = producto;
}

private static final long serialVersionUID = 1L;

}

El metodo que elimina el item en la clase controller es el siguiente:

@RequestMapping(value="/editar/{idfact}/eliminarItemFactura/{id}")
public String eliminarItemFactura(@PathVariable(value = "id") Long id,@PathVariable(value = "idfact") Long idfact, RedirectAttributes flash) {
    Factura factura = clienteService.findFacturaById(idfact);
    ItemFactura itemFactura = clienteService.findItemFacturaById(id);
    if (itemFactura != null) {
        clienteService.deleteItemFactura(id);
        flash.addFlashAttribute("success", "Item de la orden de ingreso eliminado con éxito");
        return "redirect:/factura/editar/" + factura.getId();
    }
    flash.addFlashAttribute("error", "El item de la orden de ingreso no se pudo eliminar");
    return "redirect:/factura/editar/" + factura.getId();
}