Added CDI to the application

This commit is contained in:
2014-05-23 10:24:33 +02:00
parent 2af2f56ade
commit 615d277359
19 changed files with 239 additions and 177 deletions

View File

@@ -1,85 +0,0 @@
/*
* Copyright (c) 2013, Andreas Billmann <abi@geofroggerfx.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.geofroggerfx.application;
import de.geofroggerfx.gpx.GPXReader;
import de.geofroggerfx.gpx.GroundspeakGPXReader;
import de.geofroggerfx.plugins.PluginService;
import de.geofroggerfx.plugins.PluginServiceImpl;
import de.geofroggerfx.service.CacheService;
import de.geofroggerfx.service.CacheServiceImpl;
import de.geofroggerfx.sql.DatabaseService;
import de.geofroggerfx.sql.DatabaseServiceImpl;
/**
* @author Andreas
*/
public class ServiceManager {
private static final ServiceManager INSTANCE = new ServiceManager();
private GPXReader gpxReader;
private DatabaseService databaseService;
private CacheService cacheService;
private PluginService pluginService;
private ServiceManager() {
// private for singleton pattern
}
public static ServiceManager getInstance() {
return INSTANCE;
}
public synchronized GPXReader getGPXReader() {
if (gpxReader == null) {
gpxReader = new GroundspeakGPXReader();
}
return gpxReader;
}
public synchronized DatabaseService getDatabaseService() {
if (databaseService == null) {
databaseService = new DatabaseServiceImpl();
}
return databaseService;
}
public synchronized CacheService getCacheService() {
if (cacheService == null) {
cacheService = new CacheServiceImpl();
}
return cacheService;
}
public synchronized PluginService getPluginService() {
if (pluginService == null) {
pluginService = new PluginServiceImpl();
}
return pluginService;
}
}

View File

@@ -25,6 +25,7 @@
*/
package de.geofroggerfx.application;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -34,19 +35,12 @@ import java.util.concurrent.ConcurrentHashMap;
/**
* @author Andreas
*/
@Singleton
public class SessionContext {
private static final SessionContext INSTANCE = new SessionContext();
private final Map<String, Object> map = new ConcurrentHashMap<>();
private final Map<String, List<SessionContextListener>> sessionListeners = new HashMap<>();
private SessionContext() {
}
public static SessionContext getInstance() {
return INSTANCE;
}
public void setData(String key, Object value) {
if (value == null && map.containsKey(key)) {
map.remove(key);

View File

@@ -0,0 +1,49 @@
package de.geofroggerfx.fx;
import de.geofroggerfx.fx.utils.StartupScene;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import org.scenicview.ScenicView;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;
/**
* This class is based on the tutorial
* http://blog.matthieu.brouillard.fr/2012/08/fxml-javafx-powered-by-cdi-jboss-weld_6.html
*
* Thanks to Matthieu BROUILLARD
*/
public class FxMain {
@Inject
private FXMLLoader fxmlLoader;
public void start( @Observes @StartupScene Stage stage) throws IOException
{
try (InputStream fxml = getClass().getResourceAsStream( "geofrogger/geofrogger.fxml" )) {
fxmlLoader.setResources(ResourceBundle.getBundle("de.geofroggerfx.fx.geofrogger"));
final Parent root = fxmlLoader.load(fxml);
final Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
scene.setOnKeyPressed(keyEvent -> {
if (isScenicViewShortcutPressed(keyEvent)) {
ScenicView.show(scene);
}
});
}
}
private boolean isScenicViewShortcutPressed(final KeyEvent keyEvent) {
return keyEvent.isAltDown() && keyEvent.isControlDown() && keyEvent.getCode().equals(KeyCode.V);
}
}

View File

@@ -25,38 +25,47 @@
*/
package de.geofroggerfx.fx;
import de.geofroggerfx.application.ServiceManager;
import de.geofroggerfx.fx.utils.ApplicationParametersProvider;
import de.geofroggerfx.fx.utils.StartupScene;
import de.geofroggerfx.sql.DatabaseService;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.scenicview.ScenicView;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import java.util.ResourceBundle;
import javax.enterprise.util.AnnotationLiteral;
/**
* @author Andreas
*/
public class GeoFroggerFXMain extends Application {
private Weld weld;
private WeldContainer weldContainer;
@Override
public void init() throws Exception {
super.init();
// Init Weld CDI
weld = new Weld();
}
@Override
public void start(Stage stage) throws Exception {
loadCustomFonts();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("geofrogger/geofrogger.fxml"), ResourceBundle.getBundle("de.geofroggerfx.fx.geofrogger"));
Parent root = (Parent)fxmlLoader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
scene.setOnKeyPressed(keyEvent -> {
if (isScenicViewShortcutPressed(keyEvent)) {
ScenicView.show(scene);
}
});
weldContainer = weld.initialize();
// Make the application parameters injectable with a standard CDI
// annotation
weldContainer.instance().select(ApplicationParametersProvider.class).get().setParameters(getParameters());
// Now that JavaFX thread is ready
// let's inform whoever cares using standard CDI notification mechanism:
// CDI events
weldContainer.event().select(Stage.class, new AnnotationLiteral<StartupScene>() {}).fire(stage);
}
private void loadCustomFonts() {
@@ -72,13 +81,10 @@ public class GeoFroggerFXMain extends Application {
Font.loadFont(GeoFroggerFXMain.class.getResource("/fonts/FiraSansOT-RegularItalic.otf").toExternalForm(), 12);
}
private boolean isScenicViewShortcutPressed(final KeyEvent keyEvent) {
return keyEvent.isAltDown() && keyEvent.isControlDown() && keyEvent.getCode().equals(KeyCode.V);
}
@Override
public void stop() throws Exception {
ServiceManager.getInstance().getDatabaseService().getEntityManager().close();
weldContainer.instance().select(DatabaseService.class).get().getEntityManager().close();
weld.shutdown();
super.stop();
}

View File

@@ -45,6 +45,7 @@ import javafx.util.Duration;
import jfxtras.labs.map.render.ImageMapMarker;
import jfxtras.labs.map.render.MapMarkable;
import javax.inject.Inject;
import java.net.URL;
import java.time.LocalDate;
import java.util.Arrays;
@@ -97,7 +98,8 @@ public class CacheDetailsController implements Initializable, SessionContextList
private WebView shortDescriptionWebView;
private WebView longDescriptionWebView;
private final SessionContext sessionContext = SessionContext.getInstance();
@Inject
private SessionContext sessionContext;
/**
* Initializes the controller class.

View File

@@ -142,6 +142,6 @@
</TabPane>
</children>
<stylesheets>
<URL value="@../geofrogger.css"/>
<URL value="@/de/geofroggerfx/fx/geofrogger.css"/>
</stylesheets>
</AnchorPane>

View File

@@ -25,7 +25,6 @@
*/
package de.geofroggerfx.fx.cachelist;
import de.geofroggerfx.application.ServiceManager;
import de.geofroggerfx.application.SessionContext;
import de.geofroggerfx.application.SessionContextListener;
import de.geofroggerfx.fx.components.CacheListCell;
@@ -39,10 +38,14 @@ import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import javax.inject.Inject;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
@@ -59,8 +62,12 @@ public class CacheListController implements Initializable, SessionContextListene
private static final String CACHE_LIST_ACTION_ICONS = "cache-list-action-icons";
private final SessionContext sessionContext = SessionContext.getInstance();
private final CacheService cacheService = ServiceManager.getInstance().getCacheService();
@Inject
private SessionContext sessionContext;
@Inject
private CacheService cacheService;
private SortingMenuItem currentSortingButton = null;
@FXML

View File

@@ -26,6 +26,6 @@
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="40.0"/>
</children>
<stylesheets>
<URL value="@../geofrogger.css"/>
<URL value="@/de/geofroggerfx/fx/geofrogger.css"/>
</stylesheets>
</AnchorPane>

View File

@@ -26,7 +26,6 @@
package de.geofroggerfx.fx.geofrogger;
import de.geofroggerfx.application.ProgressEvent;
import de.geofroggerfx.application.ServiceManager;
import de.geofroggerfx.application.SessionContext;
import de.geofroggerfx.gpx.GPXReader;
import de.geofroggerfx.model.Cache;
@@ -45,6 +44,7 @@ import javafx.scene.control.*;
import javafx.stage.FileChooser;
import org.controlsfx.dialog.Dialog;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.net.URL;
@@ -53,8 +53,8 @@ import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import static de.geofroggerfx.service.CacheSortField.*;
import static de.geofroggerfx.service.SortDirection.*;
import static de.geofroggerfx.service.CacheSortField.NAME;
import static de.geofroggerfx.service.SortDirection.ASC;
/**
* FXML Controller class
@@ -97,13 +97,19 @@ public class GeofroggerController implements Initializable {
+ "\t- H2 1.3.173\n"
+ "\t- Icons by http://iconmonstr.com/\n";
private final SessionContext sessionContext = SessionContext.getInstance();
@Inject
private SessionContext sessionContext;
private final LoadCachesFromFileService loadService = new LoadCachesFromFileService();
private final LoadCachesFromDatabaseService loadFromDBService = new LoadCachesFromDatabaseService();
private final GPXReader gpxReader = ServiceManager.getInstance().getGPXReader();
private final CacheService cacheService = ServiceManager.getInstance().getCacheService();
private final PluginService pluginService = ServiceManager.getInstance().getPluginService();
@Inject
private GPXReader gpxReader;
@Inject
private CacheService cacheService;
@Inject
private PluginService pluginService;
@FXML
private Label leftStatus;

View File

@@ -29,10 +29,10 @@
<SplitPane dividerPositions="0.3779342723004695" focusTraversable="true" prefHeight="-1.0" prefWidth="-1.0"
VBox.vgrow="ALWAYS">
<items>
<fx:include source="../cachelist/cache_list.fxml" fx:id="cacheListContent"/>
<fx:include source="/de/geofroggerfx/fx/cachelist/cache_list.fxml" fx:id="cacheListContent"/>
<ScrollPane fitToHeight="true" fitToWidth="true" pannable="false" prefHeight="-1.0" prefWidth="-1.0">
<content>
<fx:include source="../cachedetails/cache_details.fxml" fx:id="cacheDetailsContent"/>
<fx:include source="/de/geofroggerfx/fx/cachedetails/cache_details.fxml" fx:id="cacheDetailsContent"/>
</content>
</ScrollPane>
</items>
@@ -56,6 +56,6 @@
</HBox>
</children>
<stylesheets>
<URL value="@../geofrogger.css"/>
<URL value="@/de/geofroggerfx/fx/geofrogger.css"/>
</stylesheets>
</VBox>

View File

@@ -0,0 +1,25 @@
package de.geofroggerfx.fx.utils;
import javafx.application.Application;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
/**
* This class is based on the tutorial
* http://blog.matthieu.brouillard.fr/2012/08/fxml-javafx-powered-by-cdi-jboss-weld_6.html
*
* Thanks to Matthieu BROUILLARD
*/
@Singleton
public class ApplicationParametersProvider {
private Application.Parameters parameters;
public void setParameters(Application.Parameters p) {
this.parameters = p;
}
public @Produces Application.Parameters getParameters() {
return parameters;
}
}

View File

@@ -0,0 +1,27 @@
package de.geofroggerfx.fx.utils;
import javafx.fxml.FXMLLoader;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
/**
* This class is based on the tutorial
* http://blog.matthieu.brouillard.fr/2012/08/fxml-javafx-powered-by-cdi-jboss-weld_6.html
*
* Thanks to Matthieu BROUILLARD
*/
public class FXMLLoaderProducer {
@Inject
private Instance<Object> instance;
@Produces
public FXMLLoader createLoader()
{
final FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(param -> instance.select(param).get());
return loader;
}
}

View File

@@ -0,0 +1,19 @@
package de.geofroggerfx.fx.utils;
import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This class is based on the tutorial
* http://blog.matthieu.brouillard.fr/2012/08/fxml-javafx-powered-by-cdi-jboss-weld_6.html
*
* Thanks to Matthieu BROUILLARD
*/
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StartupScene {
}

View File

@@ -1,9 +1,10 @@
package de.geofroggerfx.plugins;
import de.geofroggerfx.application.ServiceManager;
import de.geofroggerfx.application.SessionContext;
import de.geofroggerfx.service.CacheService;
import groovy.lang.GroovyClassLoader;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -18,44 +19,49 @@ import java.util.Map;
*/
public class PluginServiceImpl implements PluginService {
private final GroovyClassLoader gcl = new GroovyClassLoader();
private final ServiceManager serviceManager = ServiceManager.getInstance();
private final GroovyClassLoader gcl = new GroovyClassLoader();
@Inject
private CacheService cacheService;
@Inject
private SessionContext sessionContext;
@Override
public List<Plugin> getAllPlugins() {
@Override
public List<Plugin> getAllPlugins() {
List<Plugin> plugins = new ArrayList<>();
List<Plugin> plugins = new ArrayList<>();
try {
File file = new File("./plugins");
if (!file.exists()) {
throw new IllegalArgumentException("plugins folder does not exist");
}
try {
File file = new File("./plugins");
if (!file.exists()) {
throw new IllegalArgumentException("plugins folder does not exist");
}
File[] pluginFiles = file.listFiles((dir, name) -> name.endsWith("Plugin.groovy"));
for (File pluginFile : pluginFiles) {
Class clazz = gcl.parseClass(pluginFile);
for (Class interf : clazz.getInterfaces()) {
if (interf.equals(Plugin.class)) {
plugins.add((Plugin) clazz.newInstance());
break;
}
}
}
} catch (IOException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
File[] pluginFiles = file.listFiles((dir, name) -> name.endsWith("Plugin.groovy"));
for (File pluginFile : pluginFiles) {
Class clazz = gcl.parseClass(pluginFile);
for (Class interf : clazz.getInterfaces()) {
if (interf.equals(Plugin.class)) {
plugins.add((Plugin) clazz.newInstance());
break;
}
}
}
return plugins;
} catch (IOException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
@Override
public void executePlugin(final Plugin plugin) {
Map<String, Object> context = new HashMap<>();
context.put("sessionContext", SessionContext.getInstance());
context.put("cacheService", serviceManager.getCacheService());
plugin.run(context);
}
return plugins;
}
@Override
public void executePlugin(final Plugin plugin) {
Map<String, Object> context = new HashMap<>();
context.put("sessionContext", sessionContext);
context.put("cacheService", cacheService);
plugin.run(context);
}
}

View File

@@ -28,6 +28,7 @@ package de.geofroggerfx.service;
import de.geofroggerfx.application.ProgressListener;
import de.geofroggerfx.model.Cache;
import javax.inject.Singleton;
import java.util.List;
/**

View File

@@ -7,13 +7,13 @@ package de.geofroggerfx.service;
import de.geofroggerfx.application.ProgressEvent;
import de.geofroggerfx.application.ProgressListener;
import de.geofroggerfx.application.ServiceManager;
import de.geofroggerfx.model.Attribute;
import de.geofroggerfx.model.Cache;
import de.geofroggerfx.model.Log;
import de.geofroggerfx.model.TravelBug;
import de.geofroggerfx.sql.DatabaseService;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
@@ -24,7 +24,9 @@ import java.util.List;
public class CacheServiceImpl implements CacheService {
private static final int TRANSACTION_SIZE = 100;
private final DatabaseService dbService = ServiceManager.getInstance().getDatabaseService();
@Inject
private DatabaseService dbService;
private final List<ProgressListener> listeners = new ArrayList<>();
@Override
@@ -50,7 +52,7 @@ public class CacheServiceImpl implements CacheService {
(double) currentCacheNumber / (double) numberOfCaches));
// begin transaction if the transaction counter is set to zero
if (transactionNumber == 0) { em.getTransaction().begin(); };
if (transactionNumber == 0) { em.getTransaction().begin(); }
transactionNumber++;
em.merge(cache.getOwner());

View File

@@ -39,8 +39,6 @@ public class DatabaseServiceImpl implements DatabaseService {
private EntityManager em;
public DatabaseServiceImpl() {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = factory.createEntityManager();
}