Example usage for java.util Properties putAll

List of usage examples for java.util Properties putAll

Introduction

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

Prototype

@Override
    public synchronized void putAll(Map<?, ?> t) 

Source Link

Usage

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 va  2 s.co 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:org.apache.pig.test.TestBuiltin.java

@Test
public void testUniqueID() throws Exception {
    Util.resetStateForExecModeSwitch();
    Properties copyproperties = new Properties();
    copyproperties.putAll(cluster.getProperties());
    PigServer pigServer = new PigServer(cluster.getExecType(), copyproperties);

    // running with 2 mappers each taking 5 records
    String TMP_DIR = FileLocalizer.getTemporaryPath(pigServer.getPigContext()).toUri().getPath();
    Util.createInputFile(cluster, TMP_DIR + "/input1.txt", new String[] { "1\n2\n3\n4\n5" });
    Util.createInputFile(cluster, TMP_DIR + "/input2.txt", new String[] { "1\n2\n3\n4\n5" });
    pigServer.getPigContext().getProperties().setProperty("pig.noSplitCombination", "true");

    pigServer.registerQuery("A = load '" + TMP_DIR + "' as (name);");
    pigServer.registerQuery("B = foreach A generate name, UniqueID();");
    Iterator<Tuple> iter = pigServer.openIterator("B");
    assertEquals("0-0", iter.next().get(1));
    assertEquals("0-1", iter.next().get(1));
    assertEquals("0-2", iter.next().get(1));
    assertEquals("0-3", iter.next().get(1));
    assertEquals("0-4", iter.next().get(1));
    assertEquals("1-0", iter.next().get(1));
    assertEquals("1-1", iter.next().get(1));
    assertEquals("1-2", iter.next().get(1));
    assertEquals("1-3", iter.next().get(1));
    assertEquals("1-4", iter.next().get(1));
    Util.deleteFile(cluster, TMP_DIR + "/input1.txt");
    Util.deleteFile(cluster, TMP_DIR + "/input2.txt");
}

From source file:org.apache.pig.test.TestBuiltin.java

@Test
public void testRANDOMWithJob() throws Exception {
    Util.resetStateForExecModeSwitch();
    Properties copyproperties = new Properties();
    copyproperties.putAll(cluster.getProperties());
    PigServer pigServer = new PigServer(cluster.getExecType(), copyproperties);

    // running with 2 mappers each taking 5 records
    String TMP_DIR = FileLocalizer.getTemporaryPath(pigServer.getPigContext()).toUri().getPath();
    Util.createInputFile(cluster, TMP_DIR + "/input1.txt", new String[] { "1\n2\n3\n4\n5" });
    Util.createInputFile(cluster, TMP_DIR + "/input2.txt", new String[] { "1\n2\n3\n4\n5" });
    pigServer.getPigContext().getProperties().setProperty("pig.noSplitCombination", "true");

    pigServer.registerQuery("A = load '" + TMP_DIR + "' as (name);");
    pigServer.registerQuery("B = foreach A generate name, RANDOM();");
    Iterator<Tuple> iter = pigServer.openIterator("B");
    double[] mapper1 = new double[5];
    double[] mapper2 = new double[5];
    for (int i = 0; i < 5; i++) {
        mapper1[i] = (Double) iter.next().get(1);
        if (i != 0) {
            // making sure it's not creating same value
            assertNotEquals(mapper1[i - 1], mapper1[i], 0.0001);
        }//w  w w  . j  av  a2 s  .c om
    }
    for (int i = 0; i < 5; i++) {
        mapper2[i] = (Double) iter.next().get(1);
        if (i != 0) {
            // making sure it's not creating same value
            assertNotEquals(mapper2[i - 1], mapper2[i], 0.0001);
        }
    }
    // making sure different mappers are creating different random values
    for (int i = 0; i < 5; i++) {
        assertNotEquals(mapper1[i], mapper2[i], 0.0001);
    }
    Util.deleteFile(cluster, TMP_DIR + "/input1.txt");
    Util.deleteFile(cluster, TMP_DIR + "/input2.txt");
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java

@SuppressWarnings("unchecked")
protected void bindSimpleId(GrailsDomainClassProperty identifier, RootClass entity, Mappings mappings,
        Identity mappedId, String sessionFactoryBeanName) {

    Mapping mapping = getMapping(identifier.getDomainClass());
    boolean useSequence = mapping != null && mapping.isTablePerConcreteClass();

    // create the id value
    SimpleValue id = new SimpleValue(mappings, entity.getTable());
    // set identifier on entity

    Properties params = new Properties();
    entity.setIdentifier(id);//w w w  . j a  v a2s .com

    if (mappedId == null) {
        // configure generator strategy
        id.setIdentifierGeneratorStrategy(useSequence ? "sequence-identity" : "native");
    } else {
        String generator = mappedId.getGenerator();
        if ("native".equals(generator) && useSequence) {
            generator = "sequence-identity";
        }
        id.setIdentifierGeneratorStrategy(generator);
        params.putAll(mappedId.getParams());
        if ("assigned".equals(generator)) {
            id.setNullValue("undefined");
        }
    }

    params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, mappings.getObjectNameNormalizer());

    if (mappings.getSchemaName() != null) {
        params.setProperty(PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName());
    }
    if (mappings.getCatalogName() != null) {
        params.setProperty(PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName());
    }
    id.setIdentifierGeneratorProperties(params);

    // bind value
    bindSimpleValue(identifier, null, id, EMPTY_PATH, mappings, sessionFactoryBeanName);

    // create property
    Property prop = new Property();
    prop.setValue(id);

    // bind property
    bindProperty(identifier, prop, mappings);
    // set identifier property
    entity.setIdentifierProperty(prop);

    id.getTable().setIdentifierValue(id);
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

private void buildSessionFactory(WGDatabase db, String path, String user, String pwd, CSVersion version,
        ConnectionProvider connProvider) throws WGInvalidDatabaseException {

    // Move old Hibernate2 packages to Hibernate3 packages 
    Iterator dbOptionsIt = db.getCreationOptions().keySet().iterator();
    while (dbOptionsIt.hasNext()) {
        Object key = dbOptionsIt.next();
        String value = (String) db.getCreationOptions().get(key);
        if (value != null && value.startsWith("net.sf.hibernate.")) {
            value = "org.hibernate." + value.substring(17);
            db.getCreationOptions().put(key, value);
        }//from ww  w . ja va 2s .co m
    }

    // Determine mapping file
    _conf = new Configuration();
    try {
        if (db.getCreationOptions().containsKey(DBOPTION_MAPPINGFILE)) {
            File mappingFile = new File((String) db.getCreationOptions().get(DBOPTION_MAPPINGFILE));
            if (!mappingFile.exists() || !mappingFile.isFile()) {
                throw new WGInvalidDatabaseException(
                        "Configured mapping file '" + db.getCreationOptions().get(DBOPTION_MAPPINGFILE)
                                + "' does not exist or is no valid file.");
            }
            _conf.addFile(mappingFile);
        } else if (db.getCreationOptions().containsKey(DBOPTION_MAPPINGRESOURCE)) {
            _conf.addResource((String) db.getCreationOptions().get(DBOPTION_MAPPINGRESOURCE),
                    this.getClass().getClassLoader());
        } else if (_ddlVersion == WGDatabase.CSVERSION_WGA5) {
            int patchLevel = version.getPatchLevel();
            String mappingFile = getCS5PatchLevelMappingFile(patchLevel);
            _conf.addResource(mappingFile, this.getClass().getClassLoader());
        } else if (_ddlVersion == WGDatabase.CSVERSION_WGA4_1) {
            _conf.addResource(HIBERNATE_V41_MAPPING_FILE, this.getClass().getClassLoader());
        } else {
            _conf.addResource(HIBERNATE_V3_MAPPING_FILE, this.getClass().getClassLoader());
        }
    } catch (MappingException e) {
        throw new WGInvalidDatabaseException("Exception parsing hibernate mapping", e);
    }

    // Some options
    _conf.buildMappings();
    if (db.getCreationOptions().containsKey(DBOPTION_HISTORYLOG_IDRANGE)) {
        Integer idRange = Integer.parseInt((String) db.getCreationOptions().get(DBOPTION_HISTORYLOG_IDRANGE));
        Properties generatorProps = ((SimpleValue) _conf.getClassMapping(LogEntry.class.getName())
                .getIdentifier()).getIdentifierGeneratorProperties();
        generatorProps.setProperty("optimizer", "pooled-lo");
        generatorProps.setProperty("increment_size", String.valueOf(idRange));
    }

    Properties props = new Properties();
    props.putAll(db.getCreationOptions());
    _conf.addProperties(props);

    ServiceRegistryBuilder registryBuilder = new ServiceRegistryBuilder();
    registryBuilder.applySettings(_conf.getProperties());
    registryBuilder.addService(ConnectionProvider.class, connProvider);
    ServiceRegistryImplementor serviceRegistry = (ServiceRegistryImplementor) registryBuilder
            .buildServiceRegistry();

    _conf.buildMappings();

    // Some options
    if ("true".equals(db.getCreationOptions().get(DBOPTION_USE_GALERA_OPTIMIZATIONS))) {
        ((SimpleValue) _conf.getClassMapping(LogEntry.class.getName()).getIdentifier())
                .setIdentifierGeneratorStrategy(GaleraClusterTableGenerator.class.getName());
    }

    // Create session factory
    try {
        _sessionFactory = _conf.buildSessionFactory(serviceRegistry);

    } catch (HibernateException e) {
        throw new WGInvalidDatabaseException("Error creating session factory: " + e.getMessage(), e);
    }
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

/**
 * @see de.innovationgate.webgate.api.WGDatabaseCore#open(WGDatabase,
 *      String, String, String, boolean)
 *///from   ww w.  j av a 2 s.c om
public WGUserAccess open(WGDatabase db, String path, String user, String pwd, boolean prepareOnly)
        throws WGAPIException {

    try {

        this._db = db;
        this._path = path;
        this._aclImpl = new ACLImpl(this);

        String jdbcDriver = (String) db.getCreationOptions().get("Driver");
        if (jdbcDriver == null) {
            jdbcDriver = (String) db.getCreationOptions().get("hibernate.connection.driver_class");
        }

        // Determine dll version
        _csVersion = determineCSVersion(db, jdbcDriver, path, user, pwd);
        _ddlVersion = _csVersion.getVersion();
        _fileHandling = createFileHandling();

        boolean useSharedPool = WGUtils.getBooleanMapValue(db.getCreationOptions(),
                WGDatabase.COPTION_SHAREDPOOL, true);
        if (useSharedPool && db.getCreationOptions().containsKey(Database.OPTION_PATH)
                && db.getServer() instanceof SharedPoolJDBCDatabaseServer) {
            SharedPoolJDBCDatabaseServer poolServer = (SharedPoolJDBCDatabaseServer) db.getServer();
            if (poolServer.isPoolAvailable(_csVersion)) {
                try {
                    _connProvider = poolServer.createPoolConnectionProvider(
                            (String) db.getCreationOptions().get(Database.OPTION_PATH));
                    WGFactory.getLogger()
                            .info("Database '" + db.getDbReference()
                                    + "' uses the shared connection pool of database server '"
                                    + db.getServer().getTitle(Locale.getDefault()) + "'");
                } catch (WGInvalidDatabaseException e) {
                    throw e;
                } catch (Exception e) {
                    throw new WGInvalidDatabaseException("Exception connecting to shared database server pool",
                            e);
                }
            }
        }

        // Create regular connection provider if no shared one available/allowed
        if (_connProvider == null) {
            Properties props = new Properties();
            if (path.startsWith("jdbc:")) {
                putDefaultConPoolProps(db, props);
            }
            if (user != null || pwd != null) {
                props.put("hibernate.connection.username", WGUtils.getValueOrDefault(user, ""));
                props.put("hibernate.connection.password", WGUtils.getValueOrDefault(pwd, ""));
            }
            String driverClass = (String) db.getCreationOptions().get("Driver");

            props.put(Environment.ISOLATION, String.valueOf(Connection.TRANSACTION_READ_COMMITTED));

            props.putAll(db.getCreationOptions());
            try {
                _connProvider = new JDBCConnectionProvider(path, driverClass, props, true);
            } catch (JDBCConnectionException e) {
                throw new WGInvalidDatabaseException("Exception creating connection pool", e);
            }
        }

        // Build Session factory and builder
        buildSessionFactory(db, path, user, pwd, _csVersion, _connProvider);
        if ("true".equals(System.getProperty("de.innovationgate.wga.hibernate.enable_jmx"))) {
            _sessionFactory.getStatistics().setStatisticsEnabled(true);
            try {
                Object statisticsMBean = Proxy.newProxyInstance(getClass().getClassLoader(),
                        new Class<?>[] { StatisticsMXBean.class }, new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                return method.invoke(_sessionFactory.getStatistics(), args);
                            }
                        });
                _jmxManager = new JmxManager(statisticsMBean,
                        new ObjectName("de.innovationgate.WGAMonitor:name=Hibernate-Statistics,db="
                                + JmxManager.normalizeJmxKey(db.getDbReference())));
            } catch (Exception e2) {
                WGFactory.getLogger().error("Exception enabling JMX for Hibernate statistics", e2);
            }
        }

        _sessionBuilder = _sessionFactory.withOptions();

        // Determine save isolation
        _saveIsolationActive = _ddlVersion >= WGDatabase.CSVERSION_WGA5;
        if (db.getCreationOptions().containsKey("SaveIsolation")) {
            _saveIsolationActive = Boolean.parseBoolean((String) db.getCreationOptions().get("SaveIsolation"));
        }

        // parse masterPersistenceTimeout
        if (db.getCreationOptions().containsKey(COPTION_MASTERPERSISTENCE_TIMEOUT)) {
            _masterPersistenceTimeout = Long
                    .parseLong((String) db.getCreationOptions().get(COPTION_MASTERPERSISTENCE_TIMEOUT));
        }

        // parse HQL query default type
        String hqlType = (String) db.getCreationOptions().get(COPTION_HQL_FETCH_TYPE);
        if (hqlType != null) {
            _hqlLazyByDefault = hqlType.equals(HQL_FETCHTYPE_LAZY);
        }

        String hqlLazyParentCheck = (String) db.getCreationOptions().get(COPTION_HQL_LAZY_PARENTCHECK);
        if (hqlLazyParentCheck != null) {
            _hqlLazyParentCheck = Boolean.parseBoolean(hqlLazyParentCheck);
        }

        // open session
        WGUserAccess accessLevel;
        try {
            accessLevel = openSession(MasterLoginAuthSession.getInstance(), pwd, true);
        } catch (WGUnavailableException e) {
            throw new WGInvalidDatabaseException("Error opening initial session", e);
        } catch (WGBackendException e) {
            throw new WGInvalidDatabaseException("Error opening initial session", e);
        }
        if (accessLevel.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) {
            try {
                close();
            } catch (WGBackendException e1) {
                WGFactory.getLogger().error(e1);
            }
        }
        return accessLevel;

    } catch (WGInvalidDatabaseException e) {
        if (_connProvider != null) {
            if (_connProvider instanceof Stoppable) {
                ((Stoppable) _connProvider).stop();
            }
            _connProvider = null;
        }
        throw e;
    }

}

From source file:be.ibridge.kettle.spoon.Spoon.java

public void getVariables() {
    TransMeta[] transMetas = getLoadedTransformations();
    JobMeta[] jobMetas = getLoadedJobs();
    if ((transMetas == null || transMetas.length == 0) && (jobMetas == null || jobMetas.length == 0))
        return;/*from w  w  w  . j  a  v  a  2s  .c  o m*/

    KettleVariables kettleVariables = KettleVariables.getInstance();
    Properties sp = new Properties();
    sp.putAll(kettleVariables.getProperties());
    sp.putAll(System.getProperties());

    for (int t = 0; t < transMetas.length; t++) {
        TransMeta transMeta = transMetas[t];

        List list = transMeta.getUsedVariables();
        for (int i = 0; i < list.size(); i++) {
            String varName = (String) list.get(i);
            String varValue = sp.getProperty(varName, "");
            if (variables.searchValueIndex(varName) < 0
                    && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX)) {
                variables.addValue(new Value(varName, varValue));
            }
        }
    }

    for (int t = 0; t < jobMetas.length; t++) {
        JobMeta jobMeta = jobMetas[t];

        List list = jobMeta.getUsedVariables();
        for (int i = 0; i < list.size(); i++) {
            String varName = (String) list.get(i);
            String varValue = sp.getProperty(varName, "");
            if (variables.searchValueIndex(varName) < 0
                    && !varName.startsWith(Const.INTERNAL_VARIABLE_PREFIX)) {
                variables.addValue(new Value(varName, varValue));
            }
        }
    }

    // Now ask the use for more info on these!
    EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, variables);
    esd.setTitle(Messages.getString("Spoon.Dialog.SetVariables.Title"));
    esd.setMessage(Messages.getString("Spoon.Dialog.SetVariables.Message"));
    esd.setReadOnly(false);
    if (esd.open() != null) {
        for (int i = 0; i < variables.size(); i++) {
            Value varval = variables.getValue(i);
            if (!Const.isEmpty(varval.getString())) {
                kettleVariables.setVariable(varval.getName(), varval.getString());
            }
        }
    }
}

From source file:be.ibridge.kettle.spoon.Spoon.java

public void showVariables() {
    Properties sp = new Properties();
    KettleVariables kettleVariables = KettleVariables.getInstance();
    sp.putAll(kettleVariables.getProperties());
    sp.putAll(System.getProperties());

    Row allVars = new Row();

    Enumeration keys = kettleVariables.getProperties().keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        String value = kettleVariables.getVariable(key);

        allVars.addValue(new Value(key, value));
    }//from   w  w w.ja  va  2  s  .  c o  m

    // Now ask the use for more info on these!
    EnterStringsDialog esd = new EnterStringsDialog(shell, SWT.NONE, allVars);
    esd.setTitle(Messages.getString("Spoon.Dialog.ShowVariables.Title"));
    esd.setMessage(Messages.getString("Spoon.Dialog.ShowVariables.Message"));
    esd.setReadOnly(true);
    esd.open();
}