aboutsummaryrefslogtreecommitdiff
path: root/src/org
diff options
context:
space:
mode:
Diffstat (limited to 'src/org')
-rw-r--r--src/org/traccar/Context.java11
-rw-r--r--src/org/traccar/api/resource/ReportResource.java123
-rw-r--r--src/org/traccar/database/DataManager.java4
-rw-r--r--src/org/traccar/database/MailManager.java146
-rw-r--r--src/org/traccar/notification/NotificatorManager.java18
-rw-r--r--src/org/traccar/notificators/NotificatorMail.java107
-rw-r--r--src/org/traccar/web/WebServer.java114
7 files changed, 294 insertions, 229 deletions
diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java
index b310d6740..ca2091148 100644
--- a/src/org/traccar/Context.java
+++ b/src/org/traccar/Context.java
@@ -41,6 +41,7 @@ import org.traccar.database.DeviceManager;
import org.traccar.database.DriversManager;
import org.traccar.database.IdentityManager;
import org.traccar.database.LdapProvider;
+import org.traccar.database.MailManager;
import org.traccar.database.MaintenancesManager;
import org.traccar.database.MediaManager;
import org.traccar.database.NotificationManager;
@@ -141,6 +142,12 @@ public final class Context {
return ldapProvider;
}
+ private static MailManager mailManager;
+
+ public static MailManager getMailManager() {
+ return mailManager;
+ }
+
private static MediaManager mediaManager;
public static MediaManager getMediaManager() {
@@ -378,6 +385,8 @@ public final class Context {
ldapProvider = new LdapProvider(config);
}
+ mailManager = new MailManager();
+
mediaManager = new MediaManager(config.getString("media.path"));
if (dataManager != null) {
@@ -397,7 +406,7 @@ public final class Context {
}
if (config.getBoolean("web.enable")) {
- webServer = new WebServer(config, dataManager.getDataSource());
+ webServer = new WebServer(config);
}
permissionsManager = new PermissionsManager(dataManager, usersManager);
diff --git a/src/org/traccar/api/resource/ReportResource.java b/src/org/traccar/api/resource/ReportResource.java
index 7c472e84d..d371cf987 100644
--- a/src/org/traccar/api/resource/ReportResource.java
+++ b/src/org/traccar/api/resource/ReportResource.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org)
+ * Copyright 2016 - 2018 Andrey Kunitsyn (andrey@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.traccar.api.resource;
import java.io.ByteArrayOutputStream;
@@ -6,6 +22,10 @@ import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
+import javax.activation.DataHandler;
+import javax.mail.MessagingException;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.util.ByteArrayDataSource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -15,6 +35,9 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.traccar.Context;
import org.traccar.api.BaseResource;
import org.traccar.helper.DateUtil;
import org.traccar.model.Event;
@@ -33,9 +56,43 @@ import org.traccar.reports.Stops;
@Consumes(MediaType.APPLICATION_JSON)
public class ReportResource extends BaseResource {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ReportResource.class);
+
private static final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private static final String CONTENT_DISPOSITION_VALUE_XLSX = "attachment; filename=report.xlsx";
+ private interface ReportExecutor {
+ void execute(ByteArrayOutputStream stream) throws SQLException, IOException;
+ }
+
+ private Response executeReport(
+ long userId, boolean mail, ReportExecutor executor) throws SQLException, IOException {
+ final ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ if (mail) {
+ new Thread(() -> {
+ try {
+ executor.execute(stream);
+
+ MimeBodyPart attachment = new MimeBodyPart();
+
+ attachment.setFileName("report.xlsx");
+ attachment.setDataHandler(new DataHandler(new ByteArrayDataSource(
+ stream.toByteArray(), "application/octet-stream")));
+
+ Context.getMailManager().sendMessage(
+ userId, "Report", "The report is in the attachment.", attachment);
+ } catch (SQLException | IOException | MessagingException e) {
+ LOGGER.warn("Report failed", e);
+ }
+ }).start();
+ return Response.noContent().build();
+ } else {
+ executor.execute(stream);
+ return Response.ok(stream.toByteArray())
+ .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ }
+ }
+
@Path("route")
@GET
public Collection<Position> getRoute(
@@ -50,13 +107,12 @@ public class ReportResource extends BaseResource {
@Produces(XLSX)
public Response getRouteExcel(
@QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
- @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException, IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Route.getExcel(stream, getUserId(), deviceIds, groupIds,
- DateUtil.parseDate(from), DateUtil.parseDate(to));
-
- return Response.ok(stream.toByteArray())
- .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ @QueryParam("from") String from, @QueryParam("to") String to, @QueryParam("mail") boolean mail)
+ throws SQLException, IOException {
+ return executeReport(getUserId(), mail, stream -> {
+ Route.getExcel(stream, getUserId(), deviceIds, groupIds,
+ DateUtil.parseDate(from), DateUtil.parseDate(to));
+ });
}
@Path("events")
@@ -75,13 +131,12 @@ public class ReportResource extends BaseResource {
public Response getEventsExcel(
@QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
@QueryParam("type") final List<String> types,
- @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException, IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Events.getExcel(stream, getUserId(), deviceIds, groupIds, types,
- DateUtil.parseDate(from), DateUtil.parseDate(to));
-
- return Response.ok(stream.toByteArray())
- .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ @QueryParam("from") String from, @QueryParam("to") String to, @QueryParam("mail") boolean mail)
+ throws SQLException, IOException {
+ return executeReport(getUserId(), mail, stream -> {
+ Events.getExcel(stream, getUserId(), deviceIds, groupIds, types,
+ DateUtil.parseDate(from), DateUtil.parseDate(to));
+ });
}
@Path("summary")
@@ -98,13 +153,12 @@ public class ReportResource extends BaseResource {
@Produces(XLSX)
public Response getSummaryExcel(
@QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
- @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException, IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Summary.getExcel(stream, getUserId(), deviceIds, groupIds,
- DateUtil.parseDate(from), DateUtil.parseDate(to));
-
- return Response.ok(stream.toByteArray())
- .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ @QueryParam("from") String from, @QueryParam("to") String to, @QueryParam("mail") boolean mail)
+ throws SQLException, IOException {
+ return executeReport(getUserId(), mail, stream -> {
+ Summary.getExcel(stream, getUserId(), deviceIds, groupIds,
+ DateUtil.parseDate(from), DateUtil.parseDate(to));
+ });
}
@Path("trips")
@@ -122,13 +176,12 @@ public class ReportResource extends BaseResource {
@Produces(XLSX)
public Response getTripsExcel(
@QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
- @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException, IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Trips.getExcel(stream, getUserId(), deviceIds, groupIds,
- DateUtil.parseDate(from), DateUtil.parseDate(to));
-
- return Response.ok(stream.toByteArray())
- .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ @QueryParam("from") String from, @QueryParam("to") String to, @QueryParam("mail") boolean mail)
+ throws SQLException, IOException {
+ return executeReport(getUserId(), mail, stream -> {
+ Trips.getExcel(stream, getUserId(), deviceIds, groupIds,
+ DateUtil.parseDate(from), DateUtil.parseDate(to));
+ });
}
@Path("stops")
@@ -146,14 +199,12 @@ public class ReportResource extends BaseResource {
@Produces(XLSX)
public Response getStopsExcel(
@QueryParam("deviceId") final List<Long> deviceIds, @QueryParam("groupId") final List<Long> groupIds,
- @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException, IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Stops.getExcel(stream, getUserId(), deviceIds, groupIds,
- DateUtil.parseDate(from), DateUtil.parseDate(to));
-
- return Response.ok(stream.toByteArray())
- .header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_XLSX).build();
+ @QueryParam("from") String from, @QueryParam("to") String to, @QueryParam("mail") boolean mail)
+ throws SQLException, IOException {
+ return executeReport(getUserId(), mail, stream -> {
+ Stops.getExcel(stream, getUserId(), deviceIds, groupIds,
+ DateUtil.parseDate(from), DateUtil.parseDate(to));
+ });
}
-
}
diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java
index f28041fc3..c3a53f4b6 100644
--- a/src/org/traccar/database/DataManager.java
+++ b/src/org/traccar/database/DataManager.java
@@ -91,10 +91,6 @@ public class DataManager {
initDatabaseSchema();
}
- public DataSource getDataSource() {
- return dataSource;
- }
-
private void initDatabase() throws Exception {
String jndiName = config.getString("database.jndi");
diff --git a/src/org/traccar/database/MailManager.java b/src/org/traccar/database/MailManager.java
new file mode 100644
index 000000000..e64aa638a
--- /dev/null
+++ b/src/org/traccar/database/MailManager.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2016 - 2018 Anton Tananaev (anton@traccar.org)
+ * Copyright 2017 - 2018 Andrey Kunitsyn (andrey@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.database;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.traccar.Context;
+import org.traccar.model.User;
+import org.traccar.notification.PropertiesProvider;
+
+import javax.mail.BodyPart;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+import java.util.Date;
+import java.util.Properties;
+
+public final class MailManager {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(MailManager.class);
+
+ private static Properties getProperties(PropertiesProvider provider) {
+ Properties properties = new Properties();
+ String host = provider.getString("mail.smtp.host");
+ if (host != null) {
+ properties.put("mail.transport.protocol", provider.getString("mail.transport.protocol", "smtp"));
+ properties.put("mail.smtp.host", host);
+ properties.put("mail.smtp.port", String.valueOf(provider.getInteger("mail.smtp.port", 25)));
+
+ Boolean starttlsEnable = provider.getBoolean("mail.smtp.starttls.enable");
+ if (starttlsEnable != null) {
+ properties.put("mail.smtp.starttls.enable", String.valueOf(starttlsEnable));
+ }
+ Boolean starttlsRequired = provider.getBoolean("mail.smtp.starttls.required");
+ if (starttlsRequired != null) {
+ properties.put("mail.smtp.starttls.required", String.valueOf(starttlsRequired));
+ }
+
+ Boolean sslEnable = provider.getBoolean("mail.smtp.ssl.enable");
+ if (sslEnable != null) {
+ properties.put("mail.smtp.ssl.enable", String.valueOf(sslEnable));
+ }
+ String sslTrust = provider.getString("mail.smtp.ssl.trust");
+ if (sslTrust != null) {
+ properties.put("mail.smtp.ssl.trust", sslTrust);
+ }
+
+ String sslProtocols = provider.getString("mail.smtp.ssl.protocols");
+ if (sslProtocols != null) {
+ properties.put("mail.smtp.ssl.protocols", sslProtocols);
+ }
+
+ String username = provider.getString("mail.smtp.username");
+ if (username != null) {
+ properties.put("mail.smtp.username", username);
+ }
+ String password = provider.getString("mail.smtp.password");
+ if (password != null) {
+ properties.put("mail.smtp.password", password);
+ }
+ String from = provider.getString("mail.smtp.from");
+ if (from != null) {
+ properties.put("mail.smtp.from", from);
+ }
+ }
+ return properties;
+ }
+
+ public void sendMessage(
+ long userId, String subject, String body) throws MessagingException {
+ sendMessage(userId, subject, body, null);
+ }
+
+ public void sendMessage(
+ long userId, String subject, String body, MimeBodyPart attachment) throws MessagingException {
+ User user = Context.getPermissionsManager().getUser(userId);
+
+ Properties properties = null;
+ if (!Context.getConfig().getBoolean("mail.smtp.ignoreUserConfig")) {
+ properties = getProperties(new PropertiesProvider(user));
+ }
+ if (properties == null || !properties.containsKey("mail.smtp.host")) {
+ properties = getProperties(new PropertiesProvider(Context.getConfig()));
+ }
+ if (!properties.containsKey("mail.smtp.host")) {
+ LOGGER.warn("No SMTP configuration found");
+ return;
+ }
+
+ Session session = Session.getInstance(properties);
+
+ MimeMessage message = new MimeMessage(session);
+
+ String from = properties.getProperty("mail.smtp.from");
+ if (from != null) {
+ message.setFrom(new InternetAddress(from));
+ }
+
+ message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
+ message.setSubject(subject);
+ message.setSentDate(new Date());
+
+ if (attachment != null) {
+ Multipart multipart = new MimeMultipart();
+
+ BodyPart messageBodyPart = new MimeBodyPart();
+ messageBodyPart.setContent(body, "text/html; charset=utf-8");
+ multipart.addBodyPart(messageBodyPart);
+ multipart.addBodyPart(attachment);
+
+ message.setContent(multipart);
+ } else {
+ message.setContent(body, "text/html; charset=utf-8");
+ }
+
+ try (Transport transport = session.getTransport()) {
+ Context.getStatisticsManager().registerMail();
+ transport.connect(
+ properties.getProperty("mail.smtp.host"),
+ properties.getProperty("mail.smtp.username"),
+ properties.getProperty("mail.smtp.password"));
+ transport.sendMessage(message, message.getAllRecipients());
+ }
+ }
+
+}
diff --git a/src/org/traccar/notification/NotificatorManager.java b/src/org/traccar/notification/NotificatorManager.java
index 41678d65c..a4080a38d 100644
--- a/src/org/traccar/notification/NotificatorManager.java
+++ b/src/org/traccar/notification/NotificatorManager.java
@@ -25,20 +25,20 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.Context;
import org.traccar.model.Typed;
+import org.traccar.notificators.NotificatorFirebase;
+import org.traccar.notificators.NotificatorMail;
import org.traccar.notificators.NotificatorNull;
import org.traccar.notificators.Notificator;
+import org.traccar.notificators.NotificatorSms;
+import org.traccar.notificators.NotificatorWeb;
public final class NotificatorManager {
private static final Logger LOGGER = LoggerFactory.getLogger(NotificatorManager.class);
- private static final String DEFAULT_WEB_NOTIFICATOR = "org.traccar.notificators.NotificatorWeb";
- private static final String DEFAULT_MAIL_NOTIFICATOR = "org.traccar.notificators.NotificatorMail";
- private static final String DEFAULT_SMS_NOTIFICATOR = "org.traccar.notificators.NotificatorSms";
- private static final String DEFAULT_FIREBASE_NOTIFICATOR = "org.traccar.notificators.NotificatorFirebase";
+ private static final Notificator NULL_NOTIFICATOR = new NotificatorNull();
private final Map<String, Notificator> notificators = new HashMap<>();
- private static final Notificator NULL_NOTIFICATOR = new NotificatorNull();
public NotificatorManager() {
final String[] types = Context.getConfig().getString("notificator.types", "").split(",");
@@ -46,16 +46,16 @@ public final class NotificatorManager {
String defaultNotificator = "";
switch (type) {
case "web":
- defaultNotificator = DEFAULT_WEB_NOTIFICATOR;
+ defaultNotificator = NotificatorWeb.class.getCanonicalName();
break;
case "mail":
- defaultNotificator = DEFAULT_MAIL_NOTIFICATOR;
+ defaultNotificator = NotificatorMail.class.getCanonicalName();
break;
case "sms":
- defaultNotificator = DEFAULT_SMS_NOTIFICATOR;
+ defaultNotificator = NotificatorSms.class.getCanonicalName();
break;
case "firebase":
- defaultNotificator = DEFAULT_FIREBASE_NOTIFICATOR;
+ defaultNotificator = NotificatorFirebase.class.getCanonicalName();
break;
default:
break;
diff --git a/src/org/traccar/notificators/NotificatorMail.java b/src/org/traccar/notificators/NotificatorMail.java
index 7aa1a2968..6b9774c58 100644
--- a/src/org/traccar/notificators/NotificatorMail.java
+++ b/src/org/traccar/notificators/NotificatorMail.java
@@ -16,121 +16,22 @@
*/
package org.traccar.notificators;
-import java.util.Properties;
-
-import javax.mail.Message;
-import javax.mail.MessagingException;
-import javax.mail.Session;
-import javax.mail.Transport;
-import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeMessage;
-import java.util.Date;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.traccar.Context;
import org.traccar.model.Event;
import org.traccar.model.Position;
-import org.traccar.model.User;
import org.traccar.notification.FullMessage;
import org.traccar.notification.MessageException;
import org.traccar.notification.NotificationFormatter;
-import org.traccar.notification.PropertiesProvider;
-
-public final class NotificatorMail extends Notificator {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(NotificatorMail.class);
- private static Properties getProperties(PropertiesProvider provider) {
- Properties properties = new Properties();
- String host = provider.getString("mail.smtp.host");
- if (host != null) {
- properties.put("mail.transport.protocol", provider.getString("mail.transport.protocol", "smtp"));
- properties.put("mail.smtp.host", host);
- properties.put("mail.smtp.port", String.valueOf(provider.getInteger("mail.smtp.port", 25)));
-
- Boolean starttlsEnable = provider.getBoolean("mail.smtp.starttls.enable");
- if (starttlsEnable != null) {
- properties.put("mail.smtp.starttls.enable", String.valueOf(starttlsEnable));
- }
- Boolean starttlsRequired = provider.getBoolean("mail.smtp.starttls.required");
- if (starttlsRequired != null) {
- properties.put("mail.smtp.starttls.required", String.valueOf(starttlsRequired));
- }
-
- Boolean sslEnable = provider.getBoolean("mail.smtp.ssl.enable");
- if (sslEnable != null) {
- properties.put("mail.smtp.ssl.enable", String.valueOf(sslEnable));
- }
- String sslTrust = provider.getString("mail.smtp.ssl.trust");
- if (sslTrust != null) {
- properties.put("mail.smtp.ssl.trust", sslTrust);
- }
-
- String sslProtocols = provider.getString("mail.smtp.ssl.protocols");
- if (sslProtocols != null) {
- properties.put("mail.smtp.ssl.protocols", sslProtocols);
- }
+import javax.mail.MessagingException;
- String username = provider.getString("mail.smtp.username");
- if (username != null) {
- properties.put("mail.smtp.username", username);
- }
- String password = provider.getString("mail.smtp.password");
- if (password != null) {
- properties.put("mail.smtp.password", password);
- }
- String from = provider.getString("mail.smtp.from");
- if (from != null) {
- properties.put("mail.smtp.from", from);
- }
- }
- return properties;
- }
+public final class NotificatorMail extends Notificator {
@Override
public void sendSync(long userId, Event event, Position position) throws MessageException {
- User user = Context.getPermissionsManager().getUser(userId);
-
- Properties properties = null;
- if (!Context.getConfig().getBoolean("mail.smtp.ignoreUserConfig")) {
- properties = getProperties(new PropertiesProvider(user));
- }
- if (properties == null || !properties.containsKey("mail.smtp.host")) {
- properties = getProperties(new PropertiesProvider(Context.getConfig()));
- }
- if (!properties.containsKey("mail.smtp.host")) {
- LOGGER.warn("No SMTP configuration found");
- return;
- }
-
- Session session = Session.getInstance(properties);
-
- MimeMessage message = new MimeMessage(session);
-
try {
- String from = properties.getProperty("mail.smtp.from");
- if (from != null) {
- message.setFrom(new InternetAddress(from));
- }
-
- message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
- FullMessage fullMessage = NotificationFormatter.formatFullMessage(userId, event, position);
- message.setSubject(fullMessage.getSubject());
- message.setSentDate(new Date());
- message.setContent(fullMessage.getBody(), "text/html; charset=utf-8");
-
- Transport transport = session.getTransport();
- try {
- Context.getStatisticsManager().registerMail();
- transport.connect(
- properties.getProperty("mail.smtp.host"),
- properties.getProperty("mail.smtp.username"),
- properties.getProperty("mail.smtp.password"));
- transport.sendMessage(message, message.getAllRecipients());
- } finally {
- transport.close();
- }
+ FullMessage message = NotificationFormatter.formatFullMessage(userId, event, position);
+ Context.getMailManager().sendMessage(userId, message.getSubject(), message.getBody());
} catch (MessagingException e) {
throw new MessageException(e);
}
diff --git a/src/org/traccar/web/WebServer.java b/src/org/traccar/web/WebServer.java
index 90ea74a3b..c657f9aec 100644
--- a/src/org/traccar/web/WebServer.java
+++ b/src/org/traccar/web/WebServer.java
@@ -22,18 +22,15 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.HandlerList;
-import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.webapp.WebAppContext;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.Config;
-import org.traccar.Context;
import org.traccar.api.AsyncSocketServlet;
import org.traccar.api.CorsResponseFilter;
import org.traccar.api.MediaFilter;
@@ -42,12 +39,10 @@ import org.traccar.api.ResourceErrorHandler;
import org.traccar.api.SecurityRequestFilter;
import org.traccar.api.resource.ServerResource;
-import javax.naming.InitialContext;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.sql.DataSource;
import java.io.IOException;
import java.io.Writer;
import java.net.InetSocketAddress;
@@ -58,12 +53,8 @@ public class WebServer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebServer.class);
private Server server;
- private final Config config;
- private final DataSource dataSource;
- private final HandlerList handlers = new HandlerList();
- private int sessionTimeout;
- private void initServer() {
+ private void initServer(Config config) {
String address = config.getString("web.address");
int port = config.getInteger("web.port", 8082);
@@ -74,39 +65,42 @@ public class WebServer {
}
}
- public WebServer(Config config, DataSource dataSource) {
- this.config = config;
- this.dataSource = dataSource;
- sessionTimeout = config.getInteger("web.sessionTimeout");
+ public WebServer(Config config) {
- initServer();
- initApi();
- if (config.getBoolean("web.console")) {
- initConsole();
+ initServer(config);
+
+ ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
+
+ int sessionTimeout = config.getInteger("web.sessionTimeout");
+ if (sessionTimeout > 0) {
+ servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout);
}
- switch (config.getString("web.type", "new")) {
- case "old":
- initOldWebApp();
- break;
- default:
- initWebApp();
- break;
+
+ initApi(config, servletHandler);
+
+ if (config.getBoolean("web.console")) {
+ servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*");
}
- initClientProxy();
- server.setHandler(handlers);
- server.addBean(new ErrorHandler() {
+ initWebApp(config, servletHandler);
+
+ servletHandler.setErrorHandler(new ErrorHandler() {
@Override
protected void handleErrorPage(
HttpServletRequest request, Writer writer, int code, String message) throws IOException {
writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>"
+ code + " - " + HttpStatus.getMessage(code) + "</body></html>");
}
- }, false);
+ });
+
+ HandlerList handlers = new HandlerList();
+ initClientProxy(config, handlers);
+ handlers.addHandler(servletHandler);
+ server.setHandler(handlers);
}
- private void initClientProxy() {
- int port = Context.getConfig().getInteger("osmand.port");
+ private void initClientProxy(Config config, HandlerList handlers) {
+ int port = config.getInteger("osmand.port");
if (port != 0) {
ServletContextHandler servletHandler = new ServletContextHandler() {
@Override
@@ -125,70 +119,38 @@ public class WebServer {
}
}
- private void initWebApp() {
- ResourceHandler resourceHandler = new ResourceHandler();
- resourceHandler.setResourceBase(config.getString("web.path"));
+ private void initWebApp(Config config, ServletContextHandler servletHandler) {
+ ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
+ servletHolder.setInitParameter("resourceBase", config.getString("web.path"));
if (config.getBoolean("web.debug")) {
- resourceHandler.setWelcomeFiles(new String[] {"debug.html", "index.html"});
+ servletHandler.setWelcomeFiles(new String[] {"debug.html", "index.html"});
} else {
String cache = config.getString("web.cacheControl");
if (cache != null && !cache.isEmpty()) {
- resourceHandler.setCacheControl(cache);
+ servletHolder.setInitParameter("cacheControl", cache);
}
- resourceHandler.setWelcomeFiles(new String[] {"release.html", "index.html"});
+ servletHandler.setWelcomeFiles(new String[] {"release.html", "index.html"});
}
- handlers.addHandler(resourceHandler);
+ servletHandler.addServlet(servletHolder, "/*");
}
- private void initOldWebApp() {
- try {
- javax.naming.Context context = new InitialContext();
- context.bind("java:/DefaultDS", dataSource);
- } catch (Exception error) {
- LOGGER.warn("JNDI context error", error);
- }
-
- WebAppContext app = new WebAppContext();
- app.setContextPath("/");
- if (sessionTimeout > 0) {
- app.getSessionHandler().setMaxInactiveInterval(sessionTimeout);
- }
- app.setWar(config.getString("web.application"));
- handlers.addHandler(app);
- }
-
- private void initApi() {
- ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
- servletHandler.setContextPath("/api");
- if (sessionTimeout > 0) {
- servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout);
- }
-
- servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/socket");
+ private void initApi(Config config, ServletContextHandler servletHandler) {
+ servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/api/socket");
if (config.hasKey("media.path")) {
- ServletHolder servletHolder = new ServletHolder("media", DefaultServlet.class);
+ ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
servletHolder.setInitParameter("resourceBase", config.getString("media.path"));
servletHolder.setInitParameter("dirAllowed", config.getString("media.dirAllowed", "false"));
servletHolder.setInitParameter("pathInfoOnly", "true");
- servletHandler.addServlet(servletHolder, "/media/*");
- servletHandler.addFilter(MediaFilter.class, "/media/*", EnumSet.allOf(DispatcherType.class));
+ servletHandler.addServlet(servletHolder, "/api/media/*");
+ servletHandler.addFilter(MediaFilter.class, "/api/media/*", EnumSet.allOf(DispatcherType.class));
}
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.registerClasses(JacksonFeature.class, ObjectMapperProvider.class, ResourceErrorHandler.class);
resourceConfig.registerClasses(SecurityRequestFilter.class, CorsResponseFilter.class);
resourceConfig.packages(ServerResource.class.getPackage().getName());
- servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");
-
- handlers.addHandler(servletHandler);
- }
-
- private void initConsole() {
- ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
- servletHandler.setContextPath("/console");
- servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/*");
- handlers.addHandler(servletHandler);
+ servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/api/*");
}
public void start() {