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.jahia.services.usermanager.JahiaUserManagerService.java

public Set<JCRUserNode> searchUsers(final Properties searchCriterias, String siteKey,
        final String[] providerKeys, boolean excludeProtected, JCRSessionWrapper session) {

    try {// w w  w.  j  ava2 s.c o  m

        int limit = 0;
        Set<JCRUserNode> users = new HashSet<JCRUserNode>();

        if (session.getWorkspace().getQueryManager() != null) {

            StringBuilder query = new StringBuilder();

            // Add provider to query
            if (providerKeys != null) {
                List<JCRStoreProvider> providers = getProviders(siteKey, providerKeys, session);
                if (!providers.isEmpty()) {
                    query.append("(");
                    for (JCRStoreProvider provider : providers) {
                        query.append(query.length() > 1 ? " OR " : "");
                        if (provider.isDefault()) {
                            query.append("u.[j:external] = false");
                        } else {
                            query.append("ISDESCENDANTNODE('").append(provider.getMountPoint()).append("')");
                        }
                    }
                    query.append(")");
                } else {
                    return users;
                }
            }

            // Add criteria
            if (searchCriterias != null && !searchCriterias.isEmpty()) {
                Properties filters = (Properties) searchCriterias.clone();
                String operation = " OR ";
                if (filters.containsKey(MULTI_CRITERIA_SEARCH_OPERATION)) {
                    if (((String) filters.get(MULTI_CRITERIA_SEARCH_OPERATION)).trim().toLowerCase()
                            .equals("and")) {
                        operation = " AND ";
                    }
                    filters.remove(MULTI_CRITERIA_SEARCH_OPERATION);
                }
                if (filters.containsKey(COUNT_LIMIT)) {
                    limit = Integer.parseInt((String) filters.get(COUNT_LIMIT));
                    logger.debug("Limit of results has be set to " + limit);
                    filters.remove(COUNT_LIMIT);
                }
                // Avoid wildcard attribute
                if (!(filters.containsKey("*") && filters.size() == 1
                        && filters.getProperty("*").equals("*"))) {
                    Iterator<Map.Entry<Object, Object>> criteriaIterator = filters.entrySet().iterator();
                    if (criteriaIterator.hasNext()) {
                        query.append(query.length() > 0 ? " AND " : "").append(" (");
                        while (criteriaIterator.hasNext()) {
                            Map.Entry<Object, Object> entry = criteriaIterator.next();
                            String propertyKey = (String) entry.getKey();
                            if ("username".equals(propertyKey)) {
                                propertyKey = "j:nodename";
                            }
                            String propertyValue = (String) entry.getValue();
                            if ("*".equals(propertyValue)) {
                                propertyValue = "%";
                            } else {
                                if (propertyValue.indexOf('*') != -1) {
                                    propertyValue = Patterns.STAR.matcher(propertyValue).replaceAll("%");
                                } else {
                                    propertyValue = propertyValue + "%";
                                }
                            }
                            propertyValue = JCRContentUtils.sqlEncode(propertyValue);
                            if ("*".equals(propertyKey)) {
                                query.append("(CONTAINS(u.*,'"
                                        + QueryParser
                                                .escape(Patterns.PERCENT.matcher(propertyValue).replaceAll(""))
                                        + "') OR LOWER(u.[j:nodename]) LIKE '")
                                        .append(propertyValue.toLowerCase()).append("') ");
                            } else {
                                query.append("LOWER(u.[" + Patterns.DOT.matcher(propertyKey).replaceAll("\\\\.")
                                        + "])").append(" LIKE '").append(propertyValue.toLowerCase())
                                        .append("'");
                            }
                            if (criteriaIterator.hasNext()) {
                                query.append(operation);
                            }
                        }
                        query.append(")");
                    }
                }
            }

            if (query.length() > 0) {
                query.insert(0, " and ");
            }
            if (excludeProtected) {
                query.insert(0, " and [j:nodename] <> '" + GUEST_USERNAME + "'");
            }
            String s = (siteKey == null) ? "/users/" : "/sites/" + siteKey + "/users/";
            query.insert(0, "SELECT * FROM [" + Constants.JAHIANT_USER + "] as u where isdescendantnode(u,'"
                    + JCRContentUtils.sqlEncode(s) + "')");
            if (logger.isDebugEnabled()) {
                logger.debug(query.toString());
            }
            Query q = session.getWorkspace().getQueryManager().createQuery(query.toString(), Query.JCR_SQL2);
            if (limit > 0) {
                q.setLimit(limit);
            }
            QueryResult qr = q.execute();
            NodeIterator ni = qr.getNodes();
            while (ni.hasNext()) {
                Node userNode = ni.nextNode();
                users.add((JCRUserNode) userNode);
            }
        }

        return users;
    } catch (RepositoryException e) {
        logger.error("Error while searching for users", e);
        return new HashSet<JCRUserNode>();
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.DhcpConfigWriter.java

private void writeKuraExtendedConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig,
        Properties kuraExtendedProps) throws KuraException {
    boolean enabled = false;
    boolean passDns = false;

    List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = null;
    if (netInterfaceConfig instanceof EthernetInterfaceConfigImpl) {
        netInterfaceAddressConfigs = ((EthernetInterfaceConfigImpl) netInterfaceConfig)
                .getNetInterfaceAddresses();
    } else if (netInterfaceConfig instanceof WifiInterfaceConfigImpl) {
        netInterfaceAddressConfigs = ((WifiInterfaceConfigImpl) netInterfaceConfig).getNetInterfaceAddresses();
    } else {//from   w w  w.j a v a  2s .co m
        s_logger.error("not adding config for " + netInterfaceConfig.getName());
    }

    if (netInterfaceAddressConfigs != null && netInterfaceAddressConfigs.size() > 0) {
        for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
            List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();
            if (netConfigs != null && netConfigs.size() > 0) {
                for (int i = 0; i < netConfigs.size(); i++) {
                    NetConfig netConfig = netConfigs.get(i);
                    if (netConfig instanceof DhcpServerConfig4) {
                        enabled = ((DhcpServerConfig4) netConfig).isEnabled();
                        passDns = ((DhcpServerConfig4) netConfig).isPassDns();
                    }
                }
            }
        }
    }

    // set it all
    if (kuraExtendedProps == null) {
        s_logger.debug("kuraExtendedProps was null");
        kuraExtendedProps = new Properties();
    }
    StringBuilder sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName())
            .append(".config.dhcpServer4.enabled");
    kuraExtendedProps.put(sb.toString(), Boolean.toString(enabled));
    sb = new StringBuilder().append("net.interface.").append(netInterfaceConfig.getName())
            .append(".config.dhcpServer4.passDns");
    kuraExtendedProps.put(sb.toString(), Boolean.toString(passDns));

    // write it
    if (kuraExtendedProps != null && !kuraExtendedProps.isEmpty()) {
        try {
            KuranetConfig.storeProperties(kuraExtendedProps);
        } catch (Exception e) {
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
        }
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.BatchClassManagementServiceImpl.java

/**
 * API to get the sample regular expressions list defined in a properties file.
 * /* www.  j a v a2s .com*/
 * @return List of sample patterns
 * @throws GWTException
 */
@Override
public SamplePatternDTO getSamplePatterns() throws GWTException {
    Properties samplePatternProperties = null;
    try {
        samplePatternProperties = ApplicationConfigProperties.getApplicationConfigProperties()
                .getAllProperties(SAMPLE_PATTERN_PROPERTY_FILE_NAME);
    } catch (IOException ioException) {
        LOGGER.error("Unable to read sample pattern properties file.", ioException);
        throw new GWTException("Unable to read sample pattern properties file.");
    }
    SamplePatternDTO samplePattern = new SamplePatternDTO();
    if (samplePatternProperties != null && (!samplePatternProperties.isEmpty())) {
        BatchClassUtil.createSamplePatternDTO(samplePattern, samplePatternProperties);
    }
    return samplePattern;
}

From source file:org.wso2.carbon.security.config.SecurityConfigAdmin.java

public void populateRampartConfig(RampartConfig rampartConfig, Properties props,
        KerberosConfigData kerberosConfigurations) throws SecurityConfigException {

    if (rampartConfig != null) {
        if (kerberosConfigurations != null) {

            Properties kerberosProperties = new Properties();
            kerberosProperties.setProperty(KerberosConfig.SERVICE_PRINCIPLE_NAME,
                    kerberosConfigurations.getServicePrincipleName());
            KerberosConfig kerberosConfig = new KerberosConfig();
            kerberosConfig.setProp(kerberosProperties);
            String carbonSecurityConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separatorChar
                    + IDENTITY_CONFIG_DIR;

            String krbFile = carbonSecurityConfigurationPath + File.separatorChar
                    + KerberosConfigData.KERBEROS_CONFIG_FILE_NAME;

            File krbFileObject = new File(krbFile);

            if (!krbFileObject.exists()) {
                throw new SecurityConfigException("Kerberos configuration file not found at " + krbFile);
            }//from  w  w  w  .  j  a  v  a  2  s . co  m

            log.info("Setting " + KerberosConfigData.KERBEROS_CONFIG_FILE_SYSTEM_PROPERTY
                    + " to kerberos configuration file " + krbFile);

            System.setProperty(KerberosConfigData.KERBEROS_CONFIG_FILE_SYSTEM_PROPERTY, krbFile);

            rampartConfig.setKerberosConfig(kerberosConfig);

        } else {
            if (!props.isEmpty()) {
                // Encryption crypto config
                {
                    CryptoConfig encrCryptoConfig = new CryptoConfig();
                    encrCryptoConfig.setProvider(ServerCrypto.class.getName());
                    encrCryptoConfig.setProp(props);
                    encrCryptoConfig.setCacheEnabled(true);
                    encrCryptoConfig.setCryptoKey(ServerCrypto.PROP_ID_PRIVATE_STORE);
                    rampartConfig.setEncrCryptoConfig(encrCryptoConfig);
                }
                {
                    CryptoConfig signatureCryptoConfig = new CryptoConfig();
                    signatureCryptoConfig.setProvider(ServerCrypto.class.getName());
                    signatureCryptoConfig.setProp(props);
                    signatureCryptoConfig.setCacheEnabled(true);
                    signatureCryptoConfig.setCryptoKey(ServerCrypto.PROP_ID_PRIVATE_STORE);
                    rampartConfig.setSigCryptoConfig(signatureCryptoConfig);
                }
            }

            rampartConfig.setEncryptionUser(WSHandlerConstants.USE_REQ_SIG_CERT);
            rampartConfig.setUser(props.getProperty(SecurityConstants.USER));

            // Get ttl and timeskew params from axis2 xml
            int ttl = RampartConfig.DEFAULT_TIMESTAMP_TTL;
            int timeSkew = RampartConfig.DEFAULT_TIMESTAMP_MAX_SKEW;

            rampartConfig.setTimestampTTL(Integer.toString(ttl));
            rampartConfig.setTimestampMaxSkew(Integer.toString(timeSkew));

            //this will check for TokenStoreClassName property under Security in carbon.xml
            //if it is not found, default token store class will be set
            String tokenStoreClassName = ServerConfiguration.getInstance()
                    .getFirstProperty("Security.TokenStoreClassName");
            if (tokenStoreClassName == null) {
                rampartConfig.setTokenStoreClass(SecurityTokenStore.class.getName());
            } else {
                rampartConfig.setTokenStoreClass(tokenStoreClassName);
            }
        }
    }
}

From source file:org.apache.geode.distributed.internal.DistributionConfigImpl.java

private Properties loadPropertiesFromURL(URL url, boolean secure) {
    Properties result = new Properties();
    loadPropertiesFromURL(result, url);/*  w w  w. j  av  a 2s  . c om*/
    if (!result.isEmpty()) {
        setSource(result, ConfigSource.file(url.toString(), secure));
    }
    return result;
}

From source file:org.apache.geode.distributed.internal.DistributionConfigImpl.java

/**
 * Creates a new <code>DistributionConfigImpl</code> with the given non-default configuration
 * properties. See {@link org.apache.geode.distributed.DistributedSystem#connect} for a list of
 * exceptions that may be thrown.// ww  w  .j av a  2 s . co  m
 * 
 * @param nonDefault The configuration properties specified by the caller
 * @param ignoreGemFirePropsFile whether to skip loading distributed system properties from
 *        gemfire.properties file
 * @param isConnected whether to skip Validation for SSL properties and copy of ssl properties to
 *        other ssl properties. This parameter will be used till we provide support for ssl-*
 *        properties.
 *
 * @since GemFire 8.0
 */
public DistributionConfigImpl(Properties nonDefault, boolean ignoreGemFirePropsFile, boolean isConnected) {
    HashMap props = new HashMap();
    if (!ignoreGemFirePropsFile) {// For admin bug #40434
        props.putAll(loadPropertiesFromURL(DistributedSystem.getPropertyFileURL(), false));
    }
    props.putAll(loadPropertiesFromURL(DistributedSystem.getSecurityPropertiesFileURL(), true));

    // Now override values picked up from the file with values passed
    // in from the caller's code
    if (nonDefault != null) {
        props.putAll(nonDefault);
        setSource(nonDefault, ConfigSource.api());
    }
    // Now remove all user defined properties from props.
    for (Object entry : props.entrySet()) {
        Map.Entry<String, String> ent = (Map.Entry<String, String>) entry;
        if (((String) ent.getKey()).startsWith(USERDEFINED_PREFIX_NAME)) {
            userDefinedProps.put(ent.getKey(), ent.getValue());
        }
    }
    // Now override values picked up from the file or code with values
    // from the system properties.
    String[] attNames = getAttributeNames();

    // For gemfire.security-* properties, we will need to look at
    // all the system properties instead of looping through attNames
    Set attNameSet = new HashSet();
    for (int index = 0; index < attNames.length; ++index) {
        attNameSet.add(GEMFIRE_PREFIX + attNames[index]);
    }

    /* clone() is a synchronized method for Properties (actually in Hashtable) */
    Properties sysProps = (Properties) System.getProperties().clone();
    Iterator<?> sysPropsIter = sysProps.entrySet().iterator();
    while (sysPropsIter.hasNext()) {
        Map.Entry sysEntry = (Map.Entry) sysPropsIter.next();
        String sysName = (String) sysEntry.getKey();
        if (attNameSet.contains(sysName) || sysName.startsWith(GEMFIRE_PREFIX + SECURITY_PREFIX_NAME)
                || sysName.startsWith(GEMFIRE_PREFIX + SSL_SYSTEM_PROPS_NAME)) {
            String sysValue = (String) sysEntry.getValue();
            if (sysValue != null) {
                String attName = sysName.substring(GEMFIRE_PREFIX.length());
                props.put(attName, sysValue);
                this.sourceMap.put(attName, ConfigSource.sysprop());
            }
        }
    }
    sysProps.clear(); // clearing cloned SysProps

    final Properties overriddenDefaults = ProcessLauncherContext.getOverriddenDefaults();
    if (!overriddenDefaults.isEmpty()) {
        for (String key : overriddenDefaults.stringPropertyNames()) {
            // only apply the overridden default if it's not already specified in props
            final String property = key.substring(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX.length());
            if (!props.containsKey((property))) {
                props.put(property, overriddenDefaults.getProperty(key));
                this.sourceMap.put(property, ConfigSource.launcher());
            }
        }
    }

    initialize(props);

    if (securityPeerAuthInit != null && securityPeerAuthInit.length() > 0) {
        System.setProperty(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTH_INIT, securityPeerAuthInit);
    }
    if (securityPeerAuthenticator != null && securityPeerAuthenticator.length() > 0) {
        System.setProperty(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTHENTICATOR, securityPeerAuthenticator);
    }

    Iterator iter = security.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        System.setProperty(SECURITY_SYSTEM_PREFIX + (String) entry.getKey(), (String) entry.getValue());
    }
    if (!isConnected) {
        copySSLPropsToServerSSLProps();
        copySSLPropsToJMXSSLProps();
        copyClusterSSLPropsToGatewaySSLProps();
        copySSLPropsToHTTPSSLProps();
    }

    // Make attributes writeable only
    this.modifiable = true;
    validateConfigurationProperties(props);
    validateSSLEnabledComponentsConfiguration();
    // Make attributes read only
    this.modifiable = false;

}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveProperties(ExternalData data) throws RepositoryException {
    OutputStream outputStream = null;
    try {//from ww  w.j a v a  2 s  .c o m
        ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance()
                .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES);
        Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType
                .getDeclaredPropertyDefinitionsAsMap();
        Properties properties = new SortedProperties();
        for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) {
            if (propertyDefinitionMap.containsKey(property.getKey())) {
                String[] v = property.getValue();
                if (v != null) {
                    String propertyValue = StringUtils.join(v, ",");
                    if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN
                            || !propertyValue.equals("false")) {
                        properties.put(property.getKey(), propertyValue);
                    }
                }
            }
        }
        FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION);
        Properties original = new Properties();
        if (file.exists()) {
            original.load(file.getContent().getInputStream());
            for (String s : propertyDefinitionMap.keySet()) {
                original.remove(s);
            }
        }
        properties.putAll(original);
        if (!properties.isEmpty()) {
            outputStream = file.getContent().getOutputStream();
            properties.store(outputStream, data.getPath());
        } else {
            if (file.exists()) {
                file.delete();
            }
        }
        ResourceBundle.clearCache();
    } catch (FileSystemException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (NoSuchNodeTypeException e) {
        logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e);
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:io.github.arven.flare.boot.TomcatContainer.java

public void start() throws Exception {
    if (base == null || !base.exists()) {
        setup(configuration);//from  w  w w. java 2 s  .  c  om
    }

    final Properties props = configuration.getProperties();

    if (props != null) {
        StrSubstitutor substitutor = null;
        for (final String s : props.stringPropertyNames()) {
            final String v = props.getProperty(s);
            if (v != null && v.contains("${")) {
                if (substitutor == null) {
                    final Map<String, String> placeHolders = new HashMap<String, String>();
                    placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort()));
                    placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort()));
                    placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort()));
                    substitutor = new StrSubstitutor(placeHolders);
                }
                props.put(s, substitutor.replace(v));
            }
        }

        // inherit from system props
        final Properties properties = new Properties(System.getProperties());
        properties.putAll(configuration.getProperties());
        Logger.configure(properties);
    } else {
        Logger.configure();
    }

    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");

    final String catalinaBase = base.getAbsolutePath();

    // set the env before calling anoything on tomcat or Catalina!!
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.deployments.classpath", "false");
    System.setProperty("catalina.home", catalinaBase);
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.home", catalinaBase);
    System.setProperty("openejb.base", catalinaBase);
    System.setProperty("openejb.servicemanager.enabled", "false");

    copyFileTo(conf, "catalina.policy");
    copyTemplateTo(conf, "catalina.properties");
    copyFileTo(conf, "context.xml");
    copyFileTo(conf, "openejb.xml");
    copyFileTo(conf, "tomcat-users.xml");
    copyFileTo(conf, "web.xml");

    final boolean initialized;
    if (configuration.hasServerXml()) {
        final File file = new File(conf, "server.xml");
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            IO.copy(configuration.getServerXmlFile(), fos);
        } finally {
            IO.close(fos);
        }

        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.isKeepServerXmlAsThis()) {
            // force ports to be able to stop the server and get @ArquillianResource
            configuration.setHttpPort(Integer.parseInt(ports.http()));
            configuration.setStopPort(Integer.parseInt(ports.stop()));
        } else {
            final Map<String, String> replacements = new HashMap<String, String>();
            replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
            replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
            replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
            IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file);
        }

        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        copyFileTo(conf, "server.xml");
        initialized = false;
    }

    if (props != null && !props.isEmpty()) {
        final FileWriter systemProperties = new FileWriter(new File(conf, "system.properties"));
        try {
            props.store(systemProperties, "");
        } finally {
            IO.close(systemProperties);
        }
    }

    // Need to use JULI so log messages from the tests are visible
    // using openejb logging conf in embedded mode
    /* if we use our config (Logger.configure()) don't override it
    copyFileTo(conf, "logging.properties");
    System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager");
    final File logging = new File(conf, "logging.properties");
    if (logging.exists()) {
    System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
    }
    */

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.getHost());
    if (!initialized) {
        tomcat.getHost().setAppBase(webapps.getAbsolutePath());
        tomcat.getEngine().setDefaultHost(configuration.getHost());
        tomcat.setHostname(configuration.getHost());
    }

    if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
        final Connector connector = new Connector(Http11Protocol.class.getName());
        connector.setPort(configuration.getHttpPort());
        connector.setAttribute("connectionTimeout", "3000");
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }

    // create https connector
    if (configuration.isSsl()) {
        final Connector httpsConnector = new Connector(Http11Protocol.class.getName());
        httpsConnector.setPort(configuration.getHttpsPort());
        httpsConnector.setSecure(true);
        httpsConnector.setProperty("SSLEnabled", "true");
        httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol());

        if (configuration.getKeystoreFile() != null) {
            httpsConnector.setAttribute("keystoreFile", configuration.getKeystoreFile());
        }
        if (configuration.getKeystorePass() != null) {
            httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass());
        }
        httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType());
        httpsConnector.setAttribute("clientAuth", configuration.getClientAuth());
        httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias());

        tomcat.getService().addConnector(httpsConnector);

        if (configuration.isSkipHttp()) {
            tomcat.setConnector(httpsConnector);
        }
    }

    // Bootstrap Tomcat
    Logger.getInstance(LogCategory.OPENEJB_STARTUP, TomcatContainer.class)
            .info("Starting TomEE from: " + base.getAbsolutePath()); // create it after Logger is configured

    if (configuration.getUsers() != null) {
        for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.getRoles() != null) {
        for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    if (!initialized) {
        tomcat.init();
    }
    tomcat.start();

    // Bootstrap OpenEJB
    final Properties properties = new Properties();
    properties.setProperty("openejb.deployments.classpath", "false");
    properties.setProperty("openejb.loader", "tomcat-system");
    properties.setProperty("openejb.home", catalinaBase);
    properties.setProperty("openejb.base", catalinaBase);
    properties.setProperty("openejb.servicemanager.enabled", "false");
    if (configuration.getProperties() != null) {
        properties.putAll(configuration.getProperties());
    }
    if (properties.getProperty("openejb.system.apps") == null) { // will make startup faster and it is rarely useful for embedded case
        properties.setProperty("openejb.system.apps", "false");
    }
    if (configuration.isQuickSession()) {
        properties.put("openejb.session.manager", QuickSessionManager.class.getName());
    }

    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final Properties tomcatServerInfo = IO.readProperties(
                classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"),
                new Properties());

        String serverNumber = tomcatServerInfo.getProperty("server.number");
        if (serverNumber == null) {
            // Tomcat5 only has server.info
            final String serverInfo = tomcatServerInfo.getProperty("server.info");
            if (serverInfo != null) {
                final int slash = serverInfo.indexOf('/');
                serverNumber = serverInfo.substring(slash + 1);
            }
        }
        if (serverNumber != null) {
            System.setProperty("tomcat.version", serverNumber);
        }

        final String serverBuilt = tomcatServerInfo.getProperty("server.built");
        if (serverBuilt != null) {
            System.setProperty("tomcat.built", serverBuilt);
        }
    } catch (final Throwable e) {
        // no-op
    }

    final TomcatLoader loader = new TomcatLoader();
    loader.initDefaults(properties);

    // need to add properties after having initialized defaults
    // to properties passed to SystemInstance otherwise we loose some of them
    final Properties initProps = new Properties();
    initProps.putAll(System.getProperties());
    initProps.putAll(properties);
    if (SystemInstance.isInitialized()) {
        SystemInstance.get().getProperties().putAll(initProps);
    } else {
        SystemInstance.init(initProps);
    }
    SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer());
    SystemInstance.get().setComponent(Server.class, tomcat.getServer()); // needed again cause of init()

    loader.initialize(properties);

    assembler = SystemInstance.get().getComponent(Assembler.class);
    configurationFactory = new ConfigurationFactory();
}

From source file:org.apache.tomee.embedded.Container.java

public void start() throws Exception {
    if (base == null || !base.exists()) {
        setup(configuration);//w  w  w  .j  a  v  a  2s .c  o m
    }

    final Properties props = configuration.getProperties();

    if (props != null) {
        StrSubstitutor substitutor = null;
        for (final String s : props.stringPropertyNames()) {
            final String v = props.getProperty(s);
            if (v != null && v.contains("${")) {
                if (substitutor == null) {
                    final Map<String, String> placeHolders = new HashMap<>();
                    placeHolders.put("tomee.embedded.http", Integer.toString(configuration.getHttpPort()));
                    placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort()));
                    placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort()));
                    substitutor = new StrSubstitutor(placeHolders);
                }
                props.put(s, substitutor.replace(v));
            }
        }

        // inherit from system props
        final Properties properties = new Properties(System.getProperties());
        properties.putAll(configuration.getProperties());
        Logger.configure(properties);
    } else {
        Logger.configure();
    }

    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");

    final String catalinaBase = base.getAbsolutePath();

    // set the env before calling anoything on tomcat or Catalina!!
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.deployments.classpath", "false");
    System.setProperty("catalina.home", catalinaBase);
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.home", catalinaBase);
    System.setProperty("openejb.base", catalinaBase);
    System.setProperty("openejb.servicemanager.enabled", "false");

    copyFileTo(conf, "catalina.policy");
    copyTemplateTo(conf, "catalina.properties");
    copyFileTo(conf, "context.xml");
    copyFileTo(conf, "openejb.xml");
    copyFileTo(conf, "tomcat-users.xml");
    copyFileTo(conf, "web.xml");

    final boolean initialized;
    if (configuration.hasServerXml()) {
        final File file = new File(conf, "server.xml");
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            IO.copy(configuration.getServerXmlFile(), fos);
        } finally {
            IO.close(fos);
        }

        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.isKeepServerXmlAsThis()) {
            // force ports to be able to stop the server and get @ArquillianResource
            configuration.setHttpPort(Integer.parseInt(ports.http()));
            configuration.setStopPort(Integer.parseInt(ports.stop()));
        } else {
            final Map<String, String> replacements = new HashMap<String, String>();
            replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
            replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
            replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
            IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file);
        }

        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        copyFileTo(conf, "server.xml");
        initialized = false;
    }

    if (props != null && !props.isEmpty()) {
        final FileWriter systemProperties = new FileWriter(new File(conf, "system.properties"));
        try {
            props.store(systemProperties, "");
        } finally {
            IO.close(systemProperties);
        }
    }

    // Need to use JULI so log messages from the tests are visible
    // using openejb logging conf in embedded mode
    /* if we use our config (Logger.configure()) don't override it
    copyFileTo(conf, "logging.properties");
    System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager");
    final File logging = new File(conf, "logging.properties");
    if (logging.exists()) {
    System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
    }
    */

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.getHost());
    if (!initialized) {
        tomcat.getHost().setAppBase(webapps.getAbsolutePath());
        tomcat.getEngine().setDefaultHost(configuration.getHost());
        tomcat.setHostname(configuration.getHost());
    }

    if (configuration.getRealm() != null) {
        tomcat.getEngine().setRealm(configuration.getRealm());
    }

    if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
        final Connector connector = new Connector(Http11Protocol.class.getName());
        connector.setPort(configuration.getHttpPort());
        connector.setAttribute("connectionTimeout", "3000");
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }

    // create https connector
    if (configuration.isSsl()) {
        final Connector httpsConnector = new Connector(Http11Protocol.class.getName());
        httpsConnector.setPort(configuration.getHttpsPort());
        httpsConnector.setSecure(true);
        httpsConnector.setProperty("SSLEnabled", "true");
        httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol());

        if (configuration.getKeystoreFile() != null) {
            httpsConnector.setAttribute("keystoreFile", configuration.getKeystoreFile());
        }
        if (configuration.getKeystorePass() != null) {
            httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass());
        }
        httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType());
        httpsConnector.setAttribute("clientAuth", configuration.getClientAuth());
        httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias());

        tomcat.getService().addConnector(httpsConnector);

        if (configuration.isSkipHttp()) {
            tomcat.setConnector(httpsConnector);
        }
    }

    // Bootstrap Tomcat
    Logger.getInstance(LogCategory.OPENEJB_STARTUP, Container.class)
            .info("Starting TomEE from: " + base.getAbsolutePath()); // create it after Logger is configured

    if (configuration.getUsers() != null) {
        for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.getRoles() != null) {
        for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    if (!initialized) {
        tomcat.init();
    }
    tomcat.start();

    // Bootstrap OpenEJB
    final Properties properties = new Properties();
    properties.setProperty("openejb.deployments.classpath", "false");
    properties.setProperty("openejb.loader", "tomcat-system");
    properties.setProperty("openejb.home", catalinaBase);
    properties.setProperty("openejb.base", catalinaBase);
    properties.setProperty("openejb.servicemanager.enabled", "false");
    if (configuration.getProperties() != null) {
        properties.putAll(configuration.getProperties());
    }
    if (properties.getProperty("openejb.system.apps") == null) { // will make startup faster and it is rarely useful for embedded case
        properties.setProperty("openejb.system.apps", "false");
    }
    if (configuration.isQuickSession()) {
        properties.put("openejb.session.manager", QuickSessionManager.class.getName());
    }

    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final Properties tomcatServerInfo = IO.readProperties(
                classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"),
                new Properties());

        String serverNumber = tomcatServerInfo.getProperty("server.number");
        if (serverNumber == null) {
            // Tomcat5 only has server.info
            final String serverInfo = tomcatServerInfo.getProperty("server.info");
            if (serverInfo != null) {
                final int slash = serverInfo.indexOf('/');
                serverNumber = serverInfo.substring(slash + 1);
            }
        }
        if (serverNumber != null) {
            System.setProperty("tomcat.version", serverNumber);
        }

        final String serverBuilt = tomcatServerInfo.getProperty("server.built");
        if (serverBuilt != null) {
            System.setProperty("tomcat.built", serverBuilt);
        }
    } catch (final Throwable e) {
        // no-op
    }

    final TomcatLoader loader = new TomcatLoader();
    loader.initDefaults(properties);

    // need to add properties after having initialized defaults
    // to properties passed to SystemInstance otherwise we loose some of them
    final Properties initProps = new Properties();
    initProps.putAll(System.getProperties());
    initProps.putAll(properties);
    if (SystemInstance.isInitialized()) {
        SystemInstance.get().getProperties().putAll(initProps);
    } else {
        SystemInstance.init(initProps);
    }
    SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer());
    SystemInstance.get().setComponent(Server.class, tomcat.getServer()); // needed again cause of init()

    loader.initialize(properties);

    assembler = SystemInstance.get().getComponent(Assembler.class);
    configurationFactory = new ConfigurationFactory();

    if (configuration.isWithEjbRemote()) {
        tomcat.getHost().addChild(new TomEERemoteWebapp());
    }
}

From source file:org.sakaiproject.message.impl.BaseMessageService.java

/**
 * Import the synoptic tool options from another site
 * //from   w  ww .j av  a  2s  .com
 * @param fromContext
 * @param toContext
 */
public void transferSynopticOptions(String fromContext, String toContext) {
    try {
        // transfer the synoptic tool options
        Site fromSite = m_siteService.getSite(fromContext);
        ToolConfiguration fromSynTool = fromSite.getToolForCommonId("sakai.synoptic." + getLabel());
        Properties fromSynProp = null;
        if (fromSynTool != null)
            fromSynProp = fromSynTool.getPlacementConfig();

        Site toSite = m_siteService.getSite(toContext);
        ToolConfiguration toSynTool = toSite.getToolForCommonId("sakai.synoptic." + getLabel());
        Properties toSynProp = null;
        if (toSynTool != null)
            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) {
                    if (propName.equals(CHANNEL_PROP)) {
                        int index = propValue.lastIndexOf("/");
                        propValue = propValue.substring(index + 1);
                        if (propValue != null && propValue.length() > 0) {
                            String channelRef = channelReference(toContext, propValue);
                            toSynProp.setProperty(propName, channelRef.toString());
                        }
                    } else {
                        toSynProp.setProperty(propName, propValue);
                    }
                }
            }

            Session session = m_sessionManager.getCurrentSession();
            ToolSession toolSession = session.getToolSession(toSynTool.getId());
            if (toolSession.getAttribute(STATE_UPDATE) == null) {
                toolSession.setAttribute(STATE_UPDATE, STATE_UPDATE);
            }

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