64 lines
1.8 KiB
Java
64 lines
1.8 KiB
Java
package ru.akarpov.web4.ejb;
|
|
|
|
import jakarta.ejb.Stateless;
|
|
import jakarta.inject.Inject;
|
|
import jakarta.persistence.EntityManager;
|
|
import jakarta.persistence.PersistenceContext;
|
|
import ru.akarpov.web4.entity.Point;
|
|
import ru.akarpov.web4.entity.User;
|
|
import ru.akarpov.web4.util.AreaChecker;
|
|
import ru.akarpov.web4.mbeans.MBeanManager;
|
|
|
|
import java.time.LocalDateTime;
|
|
import java.util.List;
|
|
|
|
@Stateless
|
|
public class PointService {
|
|
@PersistenceContext(unitName = "web4PU")
|
|
private EntityManager em;
|
|
|
|
@Inject
|
|
private UserService userService;
|
|
|
|
@Inject
|
|
private MBeanManager mBeanManager;
|
|
|
|
public Point addPoint(double x, double y, double r, Long userId) {
|
|
long startTime = System.nanoTime();
|
|
|
|
User user = em.find(User.class, userId);
|
|
if (user == null) {
|
|
throw new RuntimeException("User not found");
|
|
}
|
|
|
|
Point point = new Point(x, y, r);
|
|
point.setUser(user);
|
|
boolean hit = AreaChecker.checkHit(x, y, r);
|
|
point.setHit(hit);
|
|
point.setCreatedAt(LocalDateTime.now());
|
|
point.setExecutionTime((System.nanoTime() - startTime) / 1000000);
|
|
|
|
em.persist(point);
|
|
|
|
// Record metrics through MBeanManager
|
|
mBeanManager.recordPoint(hit);
|
|
mBeanManager.recordRequest(point.getExecutionTime());
|
|
|
|
return point;
|
|
}
|
|
|
|
public List<Point> getUserPoints(Long userId) {
|
|
return em.createQuery(
|
|
"SELECT DISTINCT p FROM Point p LEFT JOIN FETCH p.user WHERE p.user.id = :userId ORDER BY p.createdAt DESC",
|
|
Point.class
|
|
)
|
|
.setParameter("userId", userId)
|
|
.getResultList();
|
|
}
|
|
|
|
public void clearUserPoints(Long userId) {
|
|
em.createQuery("DELETE FROM Point p WHERE p.user.id = :userId")
|
|
.setParameter("userId", userId)
|
|
.executeUpdate();
|
|
}
|
|
} |