Example usage for org.hibernate.mapping Map.Entry getKey

List of usage examples for org.hibernate.mapping Map.Entry getKey

Introduction

In this page you can find the example usage for org.hibernate.mapping Map.Entry getKey.

Prototype

public KeyValue getKey() 

Source Link

Usage

From source file:org.compass.gps.device.hibernate.embedded.CompassEventListener.java

License:Apache License

private CompassHolder initCompassHolder(Configuration cfg) {
    Properties compassProperties = new Properties();
    //noinspection unchecked
    Properties props = cfg.getProperties();
    for (Map.Entry entry : props.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }//  www  . ja  v  a 2s  .  c  o m
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassProperties.put(entry.getKey(), entry.getValue());
        }
    }
    if (compassProperties.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass properties defined, disabling Compass");
        }
        return null;
    }
    if (compassProperties.getProperty(CompassEnvironment.CONNECTION) == null) {
        if (log.isDebugEnabled()) {
            log.debug("No Compass [" + CompassEnvironment.CONNECTION + "] property defined, disabling Compass");
        }
        return null;
    }

    processCollections = compassProperties.getProperty(COMPASS_PROCESS_COLLECTIONS, "true")
            .equalsIgnoreCase("true");

    CompassConfiguration compassConfiguration = CompassConfigurationFactory.newConfiguration();
    CompassSettings settings = compassConfiguration.getSettings();
    settings.addSettings(compassProperties);

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

    boolean atleastOneClassAdded = false;
    for (Iterator it = cfg.getClassMappings(); it.hasNext();) {
        PersistentClass clazz = (PersistentClass) it.next();
        Class<?> mappedClass = clazz.getMappedClass();
        for (Iterator propIt = clazz.getPropertyIterator(); propIt.hasNext();) {
            Property prop = (Property) propIt.next();
            Value value = prop.getValue();
            if (value instanceof Component) {
                Component component = (Component) value;
                try {
                    atleastOneClassAdded |= compassConfiguration.tryAddClass(
                            ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader()));
                } catch (ClassNotFoundException e) {
                    log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e);
                }
            }
        }
        Value idValue = clazz.getIdentifierProperty().getValue();
        if (idValue instanceof Component) {
            Component component = (Component) idValue;
            try {
                atleastOneClassAdded |= compassConfiguration.tryAddClass(
                        ClassUtils.forName(component.getComponentClassName(), settings.getClassLoader()));
            } catch (ClassNotFoundException e) {
                log.warn("Failed to load component class [" + component.getComponentClassName() + "]", e);
            }
        }
        atleastOneClassAdded |= compassConfiguration.tryAddClass(mappedClass);
    }
    if (!atleastOneClassAdded) {
        if (log.isDebugEnabled()) {
            log.debug("No searchable class mappings found in Hibernate class mappings, disabling Compass");
        }
        return null;
    }

    CompassHolder compassHolder = new CompassHolder();
    compassHolder.compassProperties = compassProperties;

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

    String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
    if (transactionFactory == null) {
        String hibernateTransactionStrategy = cfg.getProperty(Environment.TRANSACTION_STRATEGY);
        if (CMTTransactionFactory.class.getName().equals(hibernateTransactionStrategy)
                || JTATransactionFactory.class.getName().equals(hibernateTransactionStrategy)) {
            // hibernate is configured with JTA, automatically configure Compass to use its JTASync (by default)
            compassHolder.hibernateControlledTransaction = false;
            compassConfiguration.setSetting(CompassEnvironment.Transaction.FACTORY,
                    JTASyncTransactionFactory.class.getName());
        } else {
            // Hibernate JDBC transaction manager, let Compass use the local transaction manager
            compassHolder.hibernateControlledTransaction = true;
            // if the settings is configured to use local transaciton, disable thread bound setting since
            // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals
            if (settings
                    .getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
                settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION,
                        true);
            }
        }
    } else if (LocalTransactionFactory.class.getName().equals(transactionFactory)) {
        compassHolder.hibernateControlledTransaction = true;
        // if the settings is configured to use local transaciton, disable thread bound setting since
        // we are using Hibernate to managed transaction scope (using the transaction to holder map) and not thread locals
        if (settings.getSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION) == null) {
            settings.setBooleanSetting(CompassEnvironment.Transaction.DISABLE_THREAD_BOUND_LOCAL_TRANSATION,
                    true);
        }
    } else {
        // Hibernate is not controlling the transaction (using JTA Sync or XA), don't commit/rollback
        // with Hibernate transaction listeners
        compassHolder.hibernateControlledTransaction = false;
    }

    compassHolder.indexSettings = new Properties();
    for (Map.Entry entry : compassProperties.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith(COMPASS_GPS_INDEX_PREFIX)) {
            compassHolder.indexSettings.put(key.substring(COMPASS_GPS_INDEX_PREFIX.length()), entry.getValue());
        }
    }

    String mirrorFilterClass = compassHolder.compassProperties.getProperty(COMPASS_MIRROR_FILTER);
    if (mirrorFilterClass != null) {
        try {
            compassHolder.mirrorFilter = (HibernateMirrorFilter) ClassUtils
                    .forName(mirrorFilterClass, compassConfiguration.getSettings().getClassLoader())
                    .newInstance();
        } catch (Exception e) {
            throw new CompassException("Failed to create mirror filter [" + mirrorFilterClass + "]", e);
        }
    }

    compassHolder.compass = compassConfiguration.buildCompass();

    return compassHolder;
}

From source file:org.eclipse.emf.teneo.hibernate.HbEntityManagerWrapper.java

License:Open Source License

/** Query with named parameters */
public List<?> executeQuery(String qry, Map<String, Object> namedParameters) {
    final Query query = getEntityManager().createQuery(qry);
    for (Map.Entry<String, Object> entry : namedParameters.entrySet()) {
        query.setParameter(entry.getKey(), entry.getValue());
    }/*from   ww  w .  j  a  v a  2 s.  com*/
    return query.getResultList();
}

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

License:Apache License

public static void clearMappingCache(Class<?> theClass) {
    String className = theClass.getName();
    for (Iterator<Map.Entry<Class<?>, Mapping>> it = MAPPING_CACHE.entrySet().iterator(); it.hasNext();) {
        Map.Entry<Class<?>, Mapping> entry = it.next();
        if (className.equals(entry.getKey().getName())) {
            it.remove();//from   w  w w.ja  v a 2s  .c  o m
        }
    }
}

From source file:org.hyperic.hq.common.server.session.ServerConfigManagerImpl.java

License:Open Source License

private void createChangeAudits(AuthzSubject subject, Collection<ConfigProperty> allProps,
        Properties newProps) {//from www. j a v  a2 s .  c o  m
    Properties oldProps = new Properties();

    for (ConfigProperty prop : allProps) {

        String val = prop.getValue();

        if (val == null) {
            val = prop.getDefaultValue();
        }

        if (val == null) {
            val = "";
        }

        oldProps.put(prop.getKey(), val);
    }

    for (Map.Entry<Object, Object> newEnt : newProps.entrySet()) {
        String newKey = (String) newEnt.getKey();
        String newVal = (String) newEnt.getValue();
        String oldVal = (String) oldProps.get(newKey);

        if (oldVal == null || !oldVal.equals(newVal)) {
            if (oldVal == null) {
                oldVal = "";
            }
            createChangeAudit(subject, newKey, oldVal, newVal);
        }
    }
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.CorrectnessTestCase.java

License:LGPL

@Test
public void test() throws Exception {
    ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);

    Map<Integer, List<Log<String>>> allFamilyNames = new HashMap<>();
    Map<Integer, List<Log<Set<String>>>> allFamilyMembers = new HashMap<>();

    running = true;/*from ww  w  . j a  va2  s  . c  o  m*/
    List<Future<Void>> futures = new ArrayList<>();
    for (int node = 0; node < NUM_NODES; ++node) {
        final int NODE = node;
        for (int i = 0; i < NUM_THREADS_PER_NODE; ++i) {
            final int I = i;
            futures.add(exec.submit(() -> {
                Thread.currentThread().setName("Node" + (char) ('A' + NODE) + "-thread-" + I);
                threadNode.set(NODE);
                while (running) {
                    Operation operation;
                    if (familyIds.size() < NUM_FAMILIES) {
                        operation = new InsertFamily(ThreadLocalRandom.current().nextInt(5) == 0);
                    } else {
                        operation = getOperation();
                    }
                    try {
                        operation.run();
                    } catch (Exception e) {
                        // ignore exceptions from optimistic failures and induced exceptions
                        if (hasCause(e, InducedException.class)) {
                            continue;
                        } else if (Stream.of(EXPECTED).anyMatch(exceptions -> matches(e, exceptions))) {
                            continue;
                        }
                        exceptions.add(e);
                        log.error("Failed " + operation.getClass().getName(), e);
                    }
                }
                synchronized (allFamilyNames) {
                    for (Map.Entry<Integer, List<Log<String>>> entry : familyNames.get().entrySet()) {
                        List<Log<String>> list = allFamilyNames.get(entry.getKey());
                        if (list == null)
                            allFamilyNames.put(entry.getKey(), list = new ArrayList<>());
                        list.addAll(entry.getValue());
                    }
                    for (Map.Entry<Integer, List<Log<Set<String>>>> entry : familyMembers.get().entrySet()) {
                        List<Log<Set<String>>> list = allFamilyMembers.get(entry.getKey());
                        if (list == null)
                            allFamilyMembers.put(entry.getKey(), list = new ArrayList<>());
                        list.addAll(entry.getValue());
                    }
                }
                return null;
            }));
        }
    }
    Exception failure = exceptions.poll(EXECUTION_TIME, TimeUnit.MILLISECONDS);
    if (failure != null)
        exceptions.addFirst(failure);
    running = false;
    exec.shutdown();
    if (!exec.awaitTermination(1000, TimeUnit.SECONDS))
        throw new IllegalStateException();
    for (Future<Void> f : futures) {
        f.get(); // check for exceptions
    }
    checkForEmptyPendingPuts();
    log.infof("Generated %d timestamps%n", timestampGenerator.get());
    AtomicInteger created = new AtomicInteger();
    AtomicInteger removed = new AtomicInteger();
    ForkJoinPool threadPool = ForkJoinPool.commonPool();
    ArrayList<ForkJoinTask<?>> tasks = new ArrayList<>();
    for (Map.Entry<Integer, List<Log<String>>> entry : allFamilyNames.entrySet()) {
        tasks.add(threadPool.submit(() -> {
            int familyId = entry.getKey();
            List<Log<String>> list = entry.getValue();
            created.incrementAndGet();
            NavigableMap<Integer, List<Log<String>>> logByTime = getWritesAtTime(list);
            checkCorrectness("family_name-" + familyId + "-", list, logByTime);
            if (list.stream().anyMatch(l -> l.type == LogType.WRITE && l.getValue() == null)) {
                removed.incrementAndGet();
            }
        }));
    }
    for (Map.Entry<Integer, List<Log<Set<String>>>> entry : allFamilyMembers.entrySet()) {
        tasks.add(threadPool.submit(() -> {
            int familyId = entry.getKey();
            List<Log<Set<String>>> list = entry.getValue();
            NavigableMap<Integer, List<Log<Set<String>>>> logByTime = getWritesAtTime(list);
            checkCorrectness("family_members-" + familyId + "-", list, logByTime);
        }));
    }
    for (ForkJoinTask<?> task : tasks) {
        // with heavy logging this may have trouble to complete
        task.get(30, TimeUnit.SECONDS);
    }
    if (!exceptions.isEmpty()) {
        for (Exception e : exceptions) {
            log.error("Test failure", e);
        }
        throw new IllegalStateException("There were " + exceptions.size() + " exceptions");
    }
    log.infof("Created %d families, removed %d%n", created.get(), removed.get());
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.CorrectnessTestCase.java

License:LGPL

protected void checkForEmptyPendingPuts() throws Exception {
    Field pp = PutFromLoadValidator.class.getDeclaredField("pendingPuts");
    pp.setAccessible(true);/*  w  w  w  .ja  va  2s . co  m*/
    Method getInvalidators = null;
    List<DelayedInvalidators> delayed = new LinkedList<>();
    for (int i = 0; i < sessionFactories.length; i++) {
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactories[i];
        for (Object regionName : sfi.getAllSecondLevelCacheRegions().keySet()) {
            PutFromLoadValidator validator = getPutFromLoadValidator(sfi, (String) regionName);
            if (validator == null) {
                log.warn("No validator for " + regionName);
                continue;
            }
            ConcurrentMap<Object, Object> map = (ConcurrentMap) pp.get(validator);
            for (Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator(); iterator
                    .hasNext();) {
                Map.Entry entry = iterator.next();
                if (getInvalidators == null) {
                    getInvalidators = entry.getValue().getClass().getMethod("getInvalidators");
                    getInvalidators.setAccessible(true);
                }
                java.util.Collection invalidators = (java.util.Collection) getInvalidators
                        .invoke(entry.getValue());
                if (invalidators != null && !invalidators.isEmpty()) {
                    delayed.add(new DelayedInvalidators(map, entry.getKey()));
                }
            }
        }
    }
    // poll until all invalidations come
    long deadline = System.currentTimeMillis() + 30000;
    while (System.currentTimeMillis() < deadline) {
        iterateInvalidators(delayed, getInvalidators, (k, i) -> {
        });
        if (delayed.isEmpty()) {
            break;
        }
        Thread.sleep(1000);
    }
    if (!delayed.isEmpty()) {
        iterateInvalidators(delayed, getInvalidators,
                (k, i) -> log.warnf("Left invalidators on key %s: %s", k, i));
        throw new IllegalStateException("Invalidators were not cleared: " + delayed.size());
    }
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.CorrectnessTestCase.java

License:LGPL

private <T> void checkCorrectness(String dumpPrefix, List<Log<T>> logs,
        NavigableMap<Integer, List<Log<T>>> writesByTime) {
    Collections.sort(logs, WALL_CLOCK_TIME_COMPARATOR);
    int nullReads = 0, reads = 0, writes = 0;
    for (Log read : logs) {
        if (read.type != LogType.READ) {
            writes++;/*from w w  w . jav  a2  s .  c o  m*/
            continue;
        }
        if (read.getValue() == null || isEmptyCollection(read))
            nullReads++;
        else
            reads++;

        Map<T, Log<T>> possibleValues = new HashMap<>();
        for (List<Log<T>> list : writesByTime.subMap(read.before, true, read.after, true).values()) {
            for (Log<T> write : list) {
                if (read.precedes(write))
                    continue;
                possibleValues.put(write.getValue(), write);
            }
        }
        int startOfLastWriteBeforeRead = 0;
        for (Map.Entry<Integer, List<Log<T>>> entry : writesByTime.headMap(read.before, false).descendingMap()
                .entrySet()) {
            int time = entry.getKey();
            if (time < startOfLastWriteBeforeRead)
                break;
            for (Log<T> write : entry.getValue()) {
                if (write.after < read.before && write.before > startOfLastWriteBeforeRead) {
                    startOfLastWriteBeforeRead = write.before;
                }
                possibleValues.put(write.getValue(), write);
            }
        }

        if (possibleValues.isEmpty()) {
            // the entry was not created at all (first write failed)
            break;
        }
        if (!possibleValues.containsKey(read.getValue())) {
            dumpLogs(dumpPrefix, logs);
            exceptions.add(new IllegalStateException(String.format(
                    "R %s: %d .. %d (%s, %s) -> %s not in %s (%d+)", dumpPrefix, read.before, read.after,
                    read.threadName, new SimpleDateFormat("HH:mm:ss,SSS").format(new Date(read.wallClockTime)),
                    read.getValue(), possibleValues.values(), startOfLastWriteBeforeRead)));
            break;
        }
    }
    log.infof("Checked %d null reads, %d reads and %d writes%n", nullReads, reads, writes);
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.CorrectnessTestCase.java

License:LGPL

private int randomFamilyId(ThreadLocalRandom random) {
    Map.Entry<Integer, AtomicInteger> first = familyIds.firstEntry();
    Map.Entry<Integer, AtomicInteger> last = familyIds.lastEntry();
    if (first == null || last == null)
        return 0;
    Map.Entry<Integer, AtomicInteger> ceiling = familyIds
            .ceilingEntry(random.nextInt(first.getKey(), last.getKey() + 1));
    return ceiling == null ? 0 : ceiling.getKey();
}

From source file:org.jasig.portal.tools.dbloader.HibernateDbLoader.java

License:Apache License

@Override
public void process(DbLoaderConfig configuration)
        throws ParserConfigurationException, SAXException, IOException {
    final String scriptFile = configuration.getScriptFile();
    final List<String> script;
    if (scriptFile == null) {
        script = null;//from w ww  .  ja v a2 s .co m
    } else {
        script = new LinkedList<String>();
    }

    final ITableDataProvider tableData = this.loadTables(configuration, dialect);

    //Handle table drop/create
    if (configuration.isDropTables() || configuration.isCreateTables()) {
        //Load Table object model
        final Map<String, Table> tables = tableData.getTables();

        final Mapping mapping = this.configuration.buildMapping();
        final String defaultCatalog = this.configuration.getProperty(Environment.DEFAULT_CATALOG);
        final String defaultSchema = this.configuration.getProperty(Environment.DEFAULT_SCHEMA);

        final Map<String, DataAccessException> failedSql = new LinkedHashMap<String, DataAccessException>();

        //Generate and execute drop table scripts
        if (configuration.isDropTables()) {
            final List<String> dropScript = this.dropScript(tables.values(), dialect, defaultCatalog,
                    defaultSchema);

            if (script == null) {
                this.logger.info("Dropping existing tables");
                for (final String sql : dropScript) {
                    this.logger.info(sql);
                    try {
                        jdbcOperations.update(sql);
                    } catch (NonTransientDataAccessResourceException dae) {
                        throw dae;
                    } catch (DataAccessException dae) {
                        failedSql.put(sql, dae);
                    }
                }
            } else {
                script.addAll(dropScript);
            }
        }

        //Log any drop/create statements that failed 
        for (final Map.Entry<String, DataAccessException> failedSqlEntry : failedSql.entrySet()) {
            this.logger.warn(
                    "'" + failedSqlEntry.getKey() + "' failed to execute due to " + failedSqlEntry.getValue());
        }

        //Generate and execute create table scripts
        if (configuration.isCreateTables()) {
            final List<String> createScript = this.createScript(tables.values(), dialect, mapping,
                    defaultCatalog, defaultSchema);

            if (script == null) {
                this.logger.info("Creating tables");
                for (final String sql : createScript) {
                    this.logger.info(sql);
                    jdbcOperations.update(sql);
                }
            } else {
                script.addAll(createScript);
            }
        }
    }

    //Perform database population
    if (script == null && configuration.isPopulateTables()) {
        this.logger.info("Populating database");
        final Map<String, Map<String, Integer>> tableColumnTypes = tableData.getTableColumnTypes();
        this.populateTables(configuration, tableColumnTypes);
    }

    //Write out the script file
    if (script != null) {
        for (final ListIterator<String> iterator = script.listIterator(); iterator.hasNext();) {
            final String sql = iterator.next();
            iterator.set(sql + ";");
        }

        final File outputFile = new File(scriptFile);
        FileUtils.writeLines(outputFile, script);
        this.logger.info("Saved DDL to: " + outputFile.getAbsolutePath());
    }
}

From source file:org.sns.tool.hibernate.struct.impl.DefaultTableStructureNode.java

License:Open Source License

protected void createColumnDetail() {
    final TableStructureRules rules = owner.getRules();
    final List allColumns = new ArrayList();
    final Map columnDetailsByCategory = new HashMap();
    final Table table = getTable();
    final PrimaryKey primaryKeyColumns = table.getPrimaryKey();

    for (final Iterator columns = table.getColumnIterator(); columns.hasNext();) {
        final Column column = (Column) columns.next();

        ForeignKey partOfForeignKey = null;
        for (Iterator fkIterator = table.getForeignKeyIterator(); fkIterator.hasNext();) {
            final ForeignKey fKey = (ForeignKey) fkIterator.next();
            if (fKey.containsColumn(column)) {
                partOfForeignKey = fKey;
                break;
            }//from  w w w. j a  v a 2 s. c  o m
        }

        final ColumnDetail detail;
        if (primaryKeyColumns.containsColumn(column))
            detail = new DefaultColumnDetail(this, column, primaryKeyColumns, partOfForeignKey);
        else
            detail = new DefaultColumnDetail(this, column, null, partOfForeignKey);

        allColumns.add(detail);

        final ColumnCategory category = detail.getColumnCategory();
        if (category != null) {
            List list = (List) columnDetailsByCategory.get(category);
            if (list == null) {
                list = new ArrayList();
                columnDetailsByCategory.put(category, list);
            }
            list.add(detail);
        }
    }

    this.allColumns = (ColumnDetail[]) allColumns.toArray(new ColumnDetail[allColumns.size()]);

    this.columnDetailsByCategory = new HashMap();
    for (final Iterator i = columnDetailsByCategory.entrySet().iterator(); i.hasNext();) {
        final Map.Entry entry = (Map.Entry) i.next();
        final List list = (List) entry.getValue();
        final ColumnDetail[] categoryColumns = (ColumnDetail[]) list.toArray(new ColumnDetail[list.size()]);
        this.columnDetailsByCategory.put(entry.getKey(), categoryColumns);
    }
}