All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.agrosense.api.session.Connection Maven / Gradle / Ivy

/**
 * Copyright (C) 2008-2013 LimeTri. All rights reserved.
 *
 * AgroSense is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * There are special exceptions to the terms and conditions of the GPLv3 as it
 * is applied to this software, see the FLOSS License Exception
 * .
 *
 * AgroSense is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * AgroSense. If not, see .
 */
package eu.agrosense.api.session;

import eu.agrosense.shared.model.AgroURI;
import eu.agrosense.shared.model.AgroURIFactory;
import eu.agrosense.shared.model.AgroEntity;
import eu.agrosense.shared.model.ItemIdType;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opendolphin.core.PresentationModel;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;

/**
 * Helper class to find and manage connections.
 *
 * A client needs to provide a local authorization method like this:
 *
 * @ServiceProvider(service=AuthorizationMethod.class) public class
 * LocalAuthorizationMethod implements AuthorizationMethod{
 *
 * @author Timon Veenstra 
 */
public class Connection {

    private static final Map SERVICES = new HashMap<>();
    private static UserConnection connection;
    private static final Logger LOGGER = Logger.getLogger(Connection.class.getName());

    private static final Queue USER_CONNECTION_QUEUE = new ArrayBlockingQueue<>(10);

    /**
     * Create an {@link UserConnection} from an URL
     *
     * @param url
     * @return
     */
    public static UserConnection create(URL url) {
        if (connection == null) {

            UserConnectionFactory factory = Lookup.getDefault().lookup(UserConnectionFactory.class);
            if (factory == null) {
                throw new IllegalStateException("No UserConnectionFactory implementation found!");
            }
            if (url == null) {
                url = factory.getDefaultURL();
            }

            LOGGER.log(Level.INFO, "creating connection to {0}", url.toExternalForm());
            connection = factory.create(url);

            new UserConnectionThread(connection).start();
        } else {
            //TODO implement UserConnection switching?
            LOGGER.warning("attempt to create UserConnection with a possibly different URL, switching not supported yet! returning old UserConnection");
        }
        return connection;
    }

    /**
     * 

* Perform a task on the UserConnection.

* *

* This method can also be called when authorization process is still * ongoing. The task will be executed as soon as the connection is * validated.

* * @param runnable */ public static void onUserConnection(Runnable runnable) { LOGGER.log(Level.INFO, "adding runnable to USER_CONNECTION_QUEUE"); USER_CONNECTION_QUEUE.add(runnable); LOGGER.log(Level.INFO, "// adding runnable to USER_CONNECTION_QUEUE"); } /** * get a user connection. Will return a default connection when no url is * specified. see * https://bitbucket.org/limetri/agrosense/wiki/DevFaqConfigureServer * * @return */ public static UserConnection get() { if (connection == null) { //FIXME temporary workaround to connect to local server // return create(new URL("http://localhost:8080/web-app/agrosense/")); return create((URL) null); } return connection; } /** * * @param farmURI * @return */ private static FarmConnection create(AgroURI farmURI) { FarmConnectionFactory factory = Lookup.getDefault().lookup(FarmConnectionFactory.class); if (factory == null) { throw new IllegalStateException("No FarmConnectionFactory implementation found!"); } return factory.create(farmURI); } public static FarmConnection forFarm(AgroURI farmURI) { if (!SERVICES.containsKey(farmURI)) { SERVICES.put(farmURI, create(farmURI)); } return SERVICES.get(farmURI); } public static FarmConnection forEntity(AgroURI uri) { AgroURI farmURI = new AgroURIFactory(uri).createURI(ItemIdType.FRM, "1"); return forFarm(farmURI); } public static FarmConnection forModel(PresentationModel model) { FarmConnection farmConnection = null; if (model.getAt(AgroEntity.PROP_FARM_URI) == null) { farmConnection = forEntity(new AgroURI(model.getAt(AgroEntity.PROP_URI).getValue().toString())); } else { String uriVal = (String) model.getAt(AgroEntity.PROP_FARM_URI).getValue(); if (uriVal == null || uriVal.isEmpty()) { LOGGER.log(Level.SEVERE, "presentation model {0} did not contain a value for Entity.PROP_FARM_URI", model); throw new IllegalStateException("Cannot retrieve a FarmDataService for a presentation model without value for Entity.PROP_FARM_URI"); } farmConnection = forFarm(new AgroURI(uriVal)); } return farmConnection; } static class UserConnectionThread extends Thread { private final UserConnection userConnection; public UserConnectionThread(UserConnection userConnection) { this.userConnection = userConnection; } @Override public void run() { LOGGER.info("Starting UserConnectionThread"); if (!userConnection.getUserSession().isValidated()) { userConnection.getUserSession().addValidationListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { synchronized (UserConnectionThread.this) { LOGGER.info("user session validated"); UserConnectionThread.this.notify(); } } }); while (!userConnection.getUserSession().isValidated()) { synchronized (this) { try { LOGGER.info("waiting for user session validation"); wait(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } } } } while (userConnection.getUserSession().isValidated()) { Runnable job = USER_CONNECTION_QUEUE.poll(); if (job != null) { job.run(); }else{ try { sleep(5000); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } } } LOGGER.warning("UserSession invalidated, stopping UserConnectionThread"); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy