Example usage for java.util Properties isEmpty

List of usage examples for java.util Properties isEmpty

Introduction

In this page you can find the example usage for java.util Properties isEmpty.

Prototype

@Override
    public boolean isEmpty() 

Source Link

Usage

From source file:org.sakaiproject.announcement.entityprovider.AnnouncementEntityProviderImpl.java

/**
 * Helper to get the channels for a site. 
 * <p>//from ww  w.j a  v  a2s  .c om
 * If user site and not superuser, returns all available channels for this user.<br />
 * If user site and superuser, return all merged channels.<br />
 * If normal site, returns all merged channels.<br />
 * If motd site, returns the motd channel.
 * 
 * @param siteId
 * @return
 */
private List<String> getChannels(String siteId) {

    List<String> channels = new ArrayList<String>();

    //if motd
    if (StringUtils.equals(siteId, MOTD_SITEID)) {
        log.debug("is motd site, returning motd channel");
        channels = Collections.singletonList(announcementService.channelReference(siteId, MOTD_CHANNEL_SUFFIX));
        return channels;
    }

    //if user site
    if (siteService.isUserSite(siteId)) {
        //if not super user, get all channels this user has access to
        if (!securityService.isSuperUser()) {
            log.debug("is user site and not super user, returning all permitted channels");
            channels = Arrays
                    .asList(new MergedList().getAllPermittedChannels(new AnnouncementChannelReferenceMaker()));
            return channels;
        }
    }

    //this is either a normal site, or we are a super user
    //so get the merged announcements for this site
    Site site = null;
    try {
        site = siteService.getSite(siteId);
    } catch (IdUnusedException e) {
        //this should have been caught and dealt with already so just return empty list
        return channels;
    }
    if (site != null) {
        ToolConfiguration toolConfig = site.getToolForCommonId("sakai.announcements");

        if (toolConfig != null) {
            Properties props = toolConfig.getPlacementConfig();
            if (props.isEmpty()) {
                props = toolConfig.getConfig();
            }

            if (props != null) {

                String mergeProp = (String) props.get(PORTLET_CONFIG_PARAM_MERGED_CHANNELS);
                if (StringUtils.isNotBlank(mergeProp)) {
                    log.debug("is normal site or super user, returning all merged channels in this site");
                    log.debug("mergeProp: " + mergeProp);
                    channels = Arrays.asList(new MergedList().getChannelReferenceArrayFromDelimitedString(
                            new AnnouncementChannelReferenceMaker().makeReference(siteId), mergeProp));
                } else {
                    log.debug(
                            "is normal site or super user but no merged channels, using original siteId channel");
                    channels = Collections.singletonList(
                            announcementService.channelReference(siteId, SiteService.MAIN_CONTAINER));
                }
            }
        }
    }

    return channels;
}

From source file:com.opoopress.maven.plugins.plugin.AbstractDeployMojo.java

private Repository createRepository(Map<String, String> repo)
        throws MojoExecutionException, MojoFailureException {
    String id = repo.get("id");
    String url = repo.get("url");

    if (id == null || url == null) {
        throw new MojoFailureException("Deploy configuration must contains 'id' and 'url': " + repo);
    }//from w  w  w.j  a  va 2  s.c  o m

    url = resolveRepositoryURL(id, url);

    Properties props = new Properties();
    for (String key : repo.keySet()) {
        if ("id".equals(key) || "url".equals(key)) {
            continue;
        }
        props.setProperty(key, repo.get(key));
    }

    Repository repository = new Repository(id, appendSlash(url));
    if (!props.isEmpty()) {
        repository.setParameters(props);
    }
    return repository;
}

From source file:com.smartitengineering.loadtest.engine.impl.LoadTestEngineImpl.java

public void init(String testName, Set<UnitTestInstance> testInstances, Properties initProperties)
        throws IllegalArgumentException, IllegalStateException {
    if (getState().getStateStep() != State.CREATED.getStateStep()) {
        throw new IllegalStateException();
    }/*w w  w  .  j a  v  a 2 s . c  om*/
    if (testName == null || testName.length() <= 0) {
        throw new IllegalArgumentException();
    }
    if (testInstances == null || testInstances.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (initProperties != null && !initProperties.isEmpty()) {
        if (initProperties.containsKey(PROPS_PERMIT_KEY)) {
            try {
                setPermits(Integer.parseInt(initProperties.getProperty(PROPS_PERMIT_KEY)));
            } catch (Exception ex) {
                ex.printStackTrace();
                setPermits(-1);
            }
        }
    }
    initializeInternals(testName);
    initializeFinishDetector();
    initializeResult(testName);
    initializeTestInstances(testInstances);

    setState(State.INITIALIZED);
}

From source file:org.sakaiproject.announcement.entityprovider.AnnouncementEntityProviderImpl.java

/**
 * Get the list of announcements for a site (or user site, or !site for motd).
 * This is aimed to providing a list of announcements similar to those that the synoptic announcement
 * tool shows. It doesn't show announcements that are outside their date range even if you
 * have permission to see them (eg from being a maintainer in the site).
 *
 * @param siteId - siteId requested, or user site, or !site for motd.
 * @param params - the raw URL params that were sent, for processing.
 * @param onlyPublic - only show public announcements
 * @return// w  w w. j a  va  2 s . com
 */
private List<?> getAnnouncements(String siteId, Map<String, Object> params, boolean onlyPublic) {

    //check if we are loading the MOTD
    boolean motdView = false;
    if (StringUtils.equals(siteId, MOTD_SITEID)) {
        motdView = true;
    }

    //get number of announcements and days in the past to show from the URL params, validate and set to 0 if not set or conversion fails.
    //we use this zero value to determine if we need to look up from the tool config, or use the defaults if still not set.
    int numberOfAnnouncements = NumberUtils.toInt((String) params.get("n"), 0);
    int numberOfDaysInThePast = NumberUtils.toInt((String) params.get("d"), 0);

    //get currentUserId for permissions checks, although unused for motdView and onlyPublic
    String currentUserId = sessionManager.getCurrentSessionUserId();

    if (log.isDebugEnabled()) {
        log.debug("motdView: " + motdView);
        log.debug("siteId: " + siteId);
        log.debug("currentUserId: " + currentUserId);
        log.debug("onlyPublic: " + onlyPublic);
    }

    //check current user has annc.read permissions for this site, not for public or motd though
    if (!onlyPublic && !motdView) {
        if (!securityService.unlock(AnnouncementService.SECURE_ANNC_READ, siteService.siteReference(siteId))) {
            throw new SecurityException("You do not have access to site: " + siteId);
        }
    }

    // get the channels
    List<String> channels = getChannels(siteId);
    if (channels.size() == 0) {
        throw new EntityNotFoundException("No announcement channels found for site: " + siteId, siteId);
    }

    if (log.isDebugEnabled()) {
        log.debug("channels: " + channels.toString());
        log.debug("num channels: " + channels.size());
    }

    Site site = null;
    String siteTitle = null;
    ToolConfiguration synopticTc = null;

    if (!motdView) {

        //get site
        try {
            site = siteService.getSite(siteId);
        } catch (IdUnusedException e) {
            throw new IllegalArgumentException(
                    "No site found for the siteid:" + siteId + " : " + e.getMessage());
        }

        //get properties for synoptic tool in this site
        synopticTc = site.getToolForCommonId("sakai.synoptic.announcement");

    }

    if (synopticTc != null) {
        Properties props = synopticTc.getPlacementConfig();
        if (props.isEmpty()) {
            props = synopticTc.getConfig();
        }

        if (props != null) {

            //only get these from the synoptic tool config if not already set in the URL params
            if (numberOfAnnouncements == 0 && props.get("items") != null) {
                numberOfAnnouncements = getIntegerParameter(props, "items", DEFAULT_NUM_ANNOUNCEMENTS);
            }
            if (numberOfDaysInThePast == 0 && props.get("days") != null) {
                numberOfDaysInThePast = getIntegerParameter(props, "days", DEFAULT_DAYS_IN_PAST);
            }
        }
    }

    //get site title
    if (!motdView) {
        siteTitle = site.getTitle();
    } else {
        siteTitle = rb.getString("motd.title");
    }

    //if numbers are still zero, use the defaults
    if (numberOfAnnouncements == 0) {
        numberOfAnnouncements = DEFAULT_NUM_ANNOUNCEMENTS;
    }
    if (numberOfDaysInThePast == 0) {
        numberOfDaysInThePast = DEFAULT_DAYS_IN_PAST;
    }

    if (log.isDebugEnabled()) {
        log.debug("numberOfAnnouncements: " + numberOfAnnouncements);
        log.debug("numberOfDaysInThePast: " + numberOfDaysInThePast);
    }

    //get the Sakai Time for the given java Date
    Time t = timeService.newTime(getTimeForDaysInPast(numberOfDaysInThePast).getTime());

    //get the announcements for each channel
    List<Message> announcements = new ArrayList<Message>();

    //for each channel
    for (String channel : channels) {
        try {
            announcements.addAll(announcementService.getMessages(channel, t, numberOfAnnouncements, true, false,
                    onlyPublic));
        } catch (PermissionException e) {
            log.warn("User: " + currentUserId + " does not have access to view the announcement channel: "
                    + channel + ". Skipping...");
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("announcements.size(): " + announcements.size());
    }

    //convert raw announcements into decorated announcements
    List<DecoratedAnnouncement> decoratedAnnouncements = new ArrayList<DecoratedAnnouncement>();

    for (Message m : announcements) {
        AnnouncementMessage a = (AnnouncementMessage) m;
        if (announcementService.isMessageViewable(a)) {
            try {
                DecoratedAnnouncement da = createDecoratedAnnouncement(a, siteTitle);
                decoratedAnnouncements.add(da);
            } catch (Exception e) {
                //this can throw an exception if we are not logged in, ie public, this is fine so just deal with it and continue
                log.info("Exception caught processing announcement: " + m.getId() + " for user: "
                        + currentUserId + ". Skipping...");
            }
        }
    }

    //sort
    Collections.sort(decoratedAnnouncements);

    //reverse so it is date descending. This could be dependent on a parameter that specifies the sort order
    Collections.reverse(decoratedAnnouncements);

    //trim to final number, within bounds of list size.
    if (numberOfAnnouncements > decoratedAnnouncements.size()) {
        numberOfAnnouncements = decoratedAnnouncements.size();
    }
    decoratedAnnouncements = decoratedAnnouncements.subList(0, numberOfAnnouncements);

    return decoratedAnnouncements;
}

From source file:net.jetrix.config.ServerConfig.java

/**
 * Write the configuration of the specified filter.
 *//*from  w ww  .  jav  a  2  s  .  c  o m*/
private void saveFilter(FilterConfig filter, PrintWriter out, String indent) {
    Properties props = filter.getProperties();
    if (props == null || props.isEmpty()) {
        if (filter.getName() != null) {
            out.println(indent + "<filter name=\"" + filter.getName() + "\"/>");
        } else {
            out.println(indent + "<filter class=\"" + filter.getClassname() + "\"/>");
        }
    } else {
        if (filter.getName() != null) {
            out.println(indent + "<filter name=\"" + filter.getName() + "\">");
        } else {
            out.println(indent + "<filter class=\"" + filter.getClassname() + "\">");
        }

        for (Object name : props.keySet()) {
            out.println(indent + "  <param name=\"" + name + "\" value=\"" + props.get(name) + "\"/>");
        }
        out.println(indent + "</filter>");
    }
}

From source file:org.apache.synapse.commons.datasource.JNDIBasedDataSourceRepository.java

private Properties createJNDIEnvironment(Properties dsProperties, String name) {

    String namingFactory = DataSourceConstants.DEFAULT_IC_FACTORY;
    String providerUrl = null;//from   w ww. ja v a  2  s.  com
    int port = DataSourceConstants.DEFAULT_PROVIDER_PORT;
    String providerPort = null;
    // setting naming provider
    Properties jndiEvn = new Properties(); //This is needed for PerUserPoolDatasource

    if (dsProperties != null && !dsProperties.isEmpty()) {

        if (log.isDebugEnabled()) {
            log.debug("Using properties " + dsProperties + " to create JNDI Environment");
        }

        StringBuffer buffer = new StringBuffer();
        buffer.append(DataSourceConstants.PROP_SYNAPSE_PREFIX_DS);
        buffer.append(DataSourceConstants.DOT_STRING);
        if (name != null && !"".equals(name)) {
            buffer.append(name);
            buffer.append(DataSourceConstants.DOT_STRING);
        }
        // The prefix for root level jndiProperties
        String rootPrefix = buffer.toString();

        namingFactory = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_IC_FACTORY, DataSourceConstants.DEFAULT_IC_FACTORY);

        //Provider URL
        providerUrl = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_PROVIDER_URL, null);
        providerPort = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_PROVIDER_PORT,
                String.valueOf(DataSourceConstants.DEFAULT_PROVIDER_PORT));

    }

    jndiEvn.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);

    if (providerUrl != null && !"".equals(providerUrl)) {
        if (log.isDebugEnabled()) {
            log.debug("Using provided initial context provider url :" + providerUrl);
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("No initial context provider url...creaeting a new one");
        }
        String providerHost = "localhost";
        try {
            InetAddress addr = InetAddress.getLocalHost();
            if (addr != null) {
                String hostname = addr.getHostName();
                if (hostname == null) {
                    String ipAddr = addr.getHostAddress();
                    if (ipAddr != null) {
                        providerHost = ipAddr;
                    }
                } else {
                    providerHost = hostname;
                }
            }
        } catch (UnknownHostException e) {
            log.warn("Unable to determine hostname or IP address.. Using localhost", e);
        }

        // default port for RMI registry

        if (providerPort != null) {
            try {
                port = Integer.parseInt(providerPort);
            } catch (NumberFormatException ignored) {
            }
        }

        // Create a RMI local registry
        RMIRegistryController.getInstance().createLocalRegistry(port);
        cachedPorts.add(port);
        providerUrl = "rmi://" + providerHost + ":" + port;

    }

    jndiEvn.put(Context.PROVIDER_URL, providerUrl);

    log.info("DataSources will be registered in the JNDI context with provider PROP_URL : " + providerUrl);
    return jndiEvn;
}

From source file:org.compass.gps.device.jpa.embedded.toplink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded TopLink Essentials support enabled, initializing for session [" + session
                + "]");
    }//from www .j av a  2  s.co  m
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> toplinkProps = new HashMap();
    toplinkProps.putAll(persistenceUnitInfo.getProperties());
    toplinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) toplinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : toplinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean toplinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            toplinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            toplinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with Toplink transaction listeners
        toplinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using Toplink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    TopLinkEssentialsJpaEntityLifecycleInjector lifecycleInjector = new TopLinkEssentialsJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EmbeddedToplinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since Toplink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, toplinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded TopLink Essentials support active");
    }
}

From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java

/**
 * Sets the output properties for the transformation.
 *
 * @param outputProps - the set of output properties that will be used to
 *                      override any of the same properties in affect
 *                      for the transformation.
 *//*from   w  w w . java 2  s.  c  o m*/
public void setOutputProperties(Properties outputProps) {
    if (outputProps == null || outputProps.isEmpty())
        return;
    this.transformer.setOutputProperties(outputProps);
}

From source file:org.compass.gps.device.jpa.embedded.eclipselink.CompassSessionCustomizer.java

public void customize(Session session) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Compass embedded EclipseLink support enabled, initializing for session [" + session + "]");
    }//from  w w w.j a  v  a2 s. co m
    PersistenceUnitInfo persistenceUnitInfo = findPersistenceUnitInfo(session);
    if (persistenceUnitInfo == null) {
        throw new CompassException("Failed to find Persistence Unit Info");
    }

    Map<Object, Object> eclipselinkProps = new HashMap();
    eclipselinkProps.putAll(persistenceUnitInfo.getProperties());
    eclipselinkProps.putAll(session.getProperties());

    String sessionCustomizer = (String) eclipselinkProps.get(COMPASS_SESSION_CUSTOMIZER);
    if (sessionCustomizer != null) {
        ((SessionCustomizer) ClassUtils.forName(sessionCustomizer, persistenceUnitInfo.getClassLoader())
                .newInstance()).customize(session);
    }

    Properties compassProperties = new Properties();
    //noinspection unchecked
    for (Map.Entry entry : eclipselinkProps.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            continue;
        }
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties found in configuraiton, disabling Compass");
        }
        return;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return;
    }

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    // use the same class loader of the persistence info to load Compass classes
    compassConfiguration.setClassLoader(persistenceUnitInfo.getClassLoader());
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

    String configLocation = (String) compassProperties.get(COMPASS_CONFIG_LOCATION);
    if (configLocation != null) {
        compassConfiguration.configure(configLocation);
    }

    Map descriptors = session.getDescriptors();
    for (Object o : descriptors.values()) {
        ClassDescriptor classDescriptor = (ClassDescriptor) o;
        Class mappedClass = classDescriptor.getJavaClass();
        compassConfiguration.tryAddClass(mappedClass);
    }

    // create some default settings

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    boolean eclipselinkControlledTransaction;
    if (transactionFactory == null) {
        if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
            transactionFactory = JTASyncTransactionFactory.class.getName();
            eclipselinkControlledTransaction = false;
        } else {
            transactionFactory = LocalTransactionFactory.class.getName();
            eclipselinkControlledTransaction = true;
        }
        settings.setSetting(CompassEnvironment.Transaction.FACTORY, transactionFactory);
    } else {
        // JPA is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with EclipseLink transaction listeners
        eclipselinkControlledTransaction = false;
    }

    // if the settings is configured to use local transaciton, disable thread bound setting since
    // we are using EclipseLink to managed transaction scope (using user objects on the em) and not thread locals
    // will only be taken into account when using local transactions
    if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
        // if no emf is defined
        settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION, true);
    }

    Compass compass = compassConfiguration.buildCompass();

    boolean commitBeforeCompletion = settings
            .getSettingAsBoolean(CompassEnvironment.Transaction.COMMIT_BEFORE_COMPLETION, false);

    // extract index properties so they will be used
    Properties indexProps = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            indexProps.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    // start an internal JPA device and Gps for mirroring
    EntityManagerFactory emf = new EntityManagerFactoryImpl((ServerSession) session);

    JpaGpsDevice jpaGpsDevice = new JpaGpsDevice(DefaultJpaCompassGps.JPA_DEVICE_NAME, emf);
    jpaGpsDevice.setMirrorDataChanges(true);
    jpaGpsDevice.setInjectEntityLifecycleListener(true);
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(INDEX_QUERY_PREFIX)) {
            String entityName = key.substring(INDEX_QUERY_PREFIX.length());
            String selectQuery = (String) entry.getValue();
            jpaGpsDevice.setIndexSelectQuery(entityName, selectQuery);
        }
    }

    EclipseLinkJpaEntityLifecycleInjector lifecycleInjector = new EclipseLinkJpaEntityLifecycleInjector();
    lifecycleInjector.setEventListener(new EclipseLinkEventListener(jpaGpsDevice));
    jpaGpsDevice.setLifecycleInjector(lifecycleInjector);

    // set explicitly the EntityManagerWrapper since EclipseLink rollback the transaction on EntityManager#getTransaction
    // which makes it useless when using DefaultEntityManagerWrapper
    if (persistenceUnitInfo.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        jpaGpsDevice.setEntityManagerWrapper(new JtaEntityManagerWrapper());
    } else {
        jpaGpsDevice.setEntityManagerWrapper(new ResourceLocalEntityManagerWrapper());
    }

    DefaultJpaCompassGps jpaCompassGps = new DefaultJpaCompassGps();
    jpaCompassGps.setCompass(compass);
    jpaCompassGps.addGpsDevice(jpaGpsDevice);

    // before we start the Gps, open and close a broker
    emf.createEntityManager().close();

    jpaCompassGps.start();

    session.getEventManager().addListener(new CompassSessionEventListener(compass, jpaCompassGps,
            commitBeforeCompletion, eclipselinkControlledTransaction, indexProps));

    if (log.isDebugEnabled()) {
        log.debug("Compass embedded EclipseLink support active");
    }
}

From source file:org.sakaiproject.chat2.model.impl.ChatEntityProducer.java

/**
 * Import the synoptic tool options from another site
 * /*from   w w  w.java 2s.c  o m*/
 * @param fromContext
 * @param toContext
 */
protected void transferSynopticOptions(String fromContext, String toContext) {
    try {
        // transfer the synoptic tool options
        Site fromSite = SiteService.getSite(fromContext);
        ToolConfiguration fromSynTool = fromSite.getToolForCommonId("sakai.synoptic." + getLabel());
        Properties fromSynProp = fromSynTool.getPlacementConfig();

        Site toSite = SiteService.getSite(toContext);
        ToolConfiguration toSynTool = toSite.getToolForCommonId("sakai.synoptic." + getLabel());
        Properties toSynProp = toSynTool.getPlacementConfig();

        if (fromSynProp != null && !fromSynProp.isEmpty()) {
            Set synPropSet = fromSynProp.keySet();
            Iterator propIter = synPropSet.iterator();
            while (propIter.hasNext()) {
                String propName = ((String) propIter.next());
                String propValue = fromSynProp.getProperty(propName);
                if (propValue != null && propValue.length() > 0) {
                    toSynProp.setProperty(propName, propValue);
                }
            }

            SiteService.save(toSite);
        }
    } catch (PermissionException pe) {
        logger.warn("PermissionException transferring synoptic options for " + serviceName() + ':', pe);
    } catch (IdUnusedException e) {
        logger.warn("Channel " + fromContext + " cannot be found. ");
    } catch (Exception e) {
        logger.warn("transferSynopticOptions(): exception in handling " + serviceName() + " : ", e);
    }
}