Example usage for java.lang Comparable getClass

List of usage examples for java.lang Comparable getClass

Introduction

In this page you can find the example usage for java.lang Comparable getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:jetbrains.exodus.entitystore.PersistentEntityStoreRefactorings.java

void refactorMakePropTablesConsistent() {
    store.executeInReadonlyTransaction(new StoreTransactionalExecutable() {
        @Override/*from w w w.ja v  a 2 s.  c  om*/
        public void execute(@NotNull final StoreTransaction tx) {
            final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx;
            for (final String entityType : store.getEntityTypes(txn)) {
                if (log.isInfoEnabled()) {
                    log.info("Refactoring making props' tables consistent for [" + entityType + ']');
                }
                try {
                    final int entityTypeId = store.getEntityTypeId(txn, entityType, false);
                    final PropertiesTable propTable = store.getPropertiesTable(txn, entityTypeId);
                    final Transaction envTxn = txn.getEnvironmentTransaction();
                    final IntHashMap<LongHashMap<PropertyValue>> props = new IntHashMap<>();
                    final Cursor cursor = store.getPrimaryPropertyIndexCursor(txn, propTable);
                    while (cursor.getNext()) {
                        final PropertyKey propKey = PropertyKey.entryToPropertyKey(cursor.getKey());
                        final PropertyValue propValue = store.getPropertyTypes()
                                .entryToPropertyValue(cursor.getValue());
                        final int propId = propKey.getPropertyId();
                        LongHashMap<PropertyValue> entitiesToValues = props.get(propId);
                        if (entitiesToValues == null) {
                            entitiesToValues = new LongHashMap<>();
                            props.put(propId, entitiesToValues);
                        }
                        entitiesToValues.put(propKey.getEntityLocalId(), propValue);
                    }
                    cursor.close();
                    final List<Pair<Integer, Pair<ByteIterable, ByteIterable>>> missingPairs = new ArrayList<>();
                    final IntHashMap<Set<Long>> allPropsMap = new IntHashMap<>();
                    for (final int propId : props.keySet()) {
                        final Store valueIndex = propTable.getValueIndex(txn, propId, false);
                        final Cursor valueCursor = valueIndex == null ? null : valueIndex.openCursor(envTxn);
                        final LongHashMap<PropertyValue> entitiesToValues = props.get(propId);
                        final Set<Long> localIdSet = entitiesToValues.keySet();
                        final TreeSet<Long> sortedLocalIdSet = new TreeSet<>(localIdSet);
                        allPropsMap.put(propId, sortedLocalIdSet);
                        final Long[] localIds = sortedLocalIdSet.toArray(new Long[entitiesToValues.size()]);
                        for (final long localId : localIds) {
                            final PropertyValue propValue = entitiesToValues.get(localId);
                            final ByteIterable secondaryKey = PropertiesTable.createSecondaryKey(
                                    store.getPropertyTypes(), PropertyTypes.propertyValueToEntry(propValue),
                                    propValue.getType());
                            final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);
                            if (valueCursor == null
                                    || !valueCursor.getSearchBoth(secondaryKey, secondaryValue)) {
                                missingPairs.add(new Pair<>(propId, new Pair<>(secondaryKey, secondaryValue)));
                            }
                        }
                        if (valueCursor != null) {
                            valueCursor.close();
                        }
                    }
                    if (!missingPairs.isEmpty()) {
                        store.executeInTransaction(new StoreTransactionalExecutable() {
                            @Override
                            public void execute(@NotNull final StoreTransaction tx) {
                                final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx;
                                for (final Pair<Integer, Pair<ByteIterable, ByteIterable>> pair : missingPairs) {
                                    final Store valueIndex = propTable.getValueIndex(txn, pair.getFirst(),
                                            true);
                                    final Pair<ByteIterable, ByteIterable> missing = pair.getSecond();
                                    if (valueIndex == null) {
                                        throw new NullPointerException("Can't be");
                                    }
                                    valueIndex.put(txn.getEnvironmentTransaction(), missing.getFirst(),
                                            missing.getSecond());
                                }
                            }
                        });
                        if (log.isInfoEnabled()) {
                            log.info(missingPairs.size() + " missing secondary keys found and fixed for ["
                                    + entityType + ']');
                        }
                    }
                    final List<Pair<Integer, Pair<ByteIterable, ByteIterable>>> phantomPairs = new ArrayList<>();
                    for (final Map.Entry<Integer, Store> entry : propTable.getValueIndices()) {
                        final int propId = entry.getKey();
                        final LongHashMap<PropertyValue> entitiesToValues = props.get(propId);
                        final Cursor c = entry.getValue().openCursor(envTxn);
                        while (c.getNext()) {
                            final ByteIterable keyEntry = c.getKey();
                            final ByteIterable valueEntry = c.getValue();
                            final PropertyValue propValue = entitiesToValues
                                    .get(LongBinding.compressedEntryToLong(valueEntry));
                            if (propValue == null) {
                                phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry)));
                            } else {
                                final ComparableBinding objectBinding = propValue.getBinding();
                                final Comparable value;
                                try {
                                    value = objectBinding.entryToObject(keyEntry);
                                } catch (Throwable t) {
                                    throwJVMError(t);
                                    phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry)));
                                    continue;
                                }
                                final Comparable data = propValue.getData();
                                //noinspection unchecked
                                if (!data.getClass().equals(value.getClass())
                                        || PropertyTypes.toLowerCase(data).compareTo(value) != 0) {
                                    phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry)));
                                }
                            }
                        }
                        c.close();
                    }
                    if (!phantomPairs.isEmpty()) {
                        store.executeInTransaction(new StoreTransactionalExecutable() {
                            @Override
                            public void execute(@NotNull final StoreTransaction tx) {
                                final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx;
                                final Transaction envTxn = txn.getEnvironmentTransaction();
                                for (final Pair<Integer, Pair<ByteIterable, ByteIterable>> pair : phantomPairs) {
                                    final Store valueIndex = propTable.getValueIndex(txn, pair.getFirst(),
                                            true);
                                    final Pair<ByteIterable, ByteIterable> phantom = pair.getSecond();
                                    if (valueIndex == null) {
                                        throw new NullPointerException("Can't be");
                                    }
                                    deletePair(valueIndex.openCursor(envTxn), phantom.getFirst(),
                                            phantom.getSecond());
                                }
                            }
                        });
                        if (log.isInfoEnabled()) {
                            log.info(phantomPairs.size() + " phantom secondary keys found and fixed for ["
                                    + entityType + ']');
                        }
                    }
                    final List<Pair<Integer, Long>> phantomIds = new ArrayList<>();
                    final Cursor c = propTable.getAllPropsIndex().openCursor(envTxn);
                    while (c.getNext()) {
                        final int propId = IntegerBinding.compressedEntryToInt(c.getKey());
                        final long localId = LongBinding.compressedEntryToLong(c.getValue());
                        final Set<Long> localIds = allPropsMap.get(propId);
                        if (localIds == null || !localIds.remove(localId)) {
                            phantomIds.add(new Pair<>(propId, localId));
                        } else {
                            if (localIds.isEmpty()) {
                                allPropsMap.remove(propId);
                            }
                        }
                    }
                    c.close();
                    if (!allPropsMap.isEmpty()) {
                        final int[] added = { 0 };
                        store.executeInTransaction(new StoreTransactionalExecutable() {
                            @Override
                            public void execute(@NotNull final StoreTransaction txn) {
                                int count = 0;
                                final Store allPropsIndex = propTable.getAllPropsIndex();
                                final Transaction envTxn = ((PersistentStoreTransaction) txn)
                                        .getEnvironmentTransaction();
                                for (Map.Entry<Integer, Set<Long>> entry : allPropsMap.entrySet()) {
                                    final ArrayByteIterable keyEntry = IntegerBinding
                                            .intToCompressedEntry(entry.getKey());
                                    for (long localId : entry.getValue()) {
                                        allPropsIndex.put(envTxn, keyEntry,
                                                LongBinding.longToCompressedEntry(localId));
                                        ++count;
                                    }
                                }
                                added[0] = count;
                            }
                        });
                        if (log.isInfoEnabled()) {
                            log.info(added[0] + " missing id pairs found and fixed for [" + entityType + ']');
                        }
                    }
                    if (!phantomIds.isEmpty()) {
                        store.executeInTransaction(new StoreTransactionalExecutable() {
                            @Override
                            public void execute(@NotNull final StoreTransaction txn) {
                                final Store allPropsIndex = propTable.getAllPropsIndex();
                                final Transaction envTxn = ((PersistentStoreTransaction) txn)
                                        .getEnvironmentTransaction();
                                final Cursor c = allPropsIndex.openCursor(envTxn);
                                for (final Pair<Integer, Long> phantom : phantomIds) {
                                    if (!c.getSearchBoth(
                                            IntegerBinding.intToCompressedEntry(phantom.getFirst()),
                                            LongBinding.longToCompressedEntry(phantom.getSecond()))) {
                                        throw new EntityStoreException("Can't be");
                                    }
                                    c.deleteCurrent();
                                }
                                c.close();
                            }
                        });
                        if (log.isInfoEnabled()) {
                            log.info(phantomIds.size() + " phantom id pairs found and fixed for [" + entityType
                                    + ']');
                        }
                    }
                } catch (Throwable t) {
                    log.error("Failed to execute refactoring for entity type: " + entityType, t);
                    throwJVMError(t);
                }
            }
        }
    });
}

From source file:com.github.gerbsen.math.Frequency.java

/**
 * Adds 1 to the frequency count for v./*from  www.  ja v a  2 s.  co  m*/
 * <p>
 * If other objects have already been added to this Frequency, v must
 * be comparable to those that have already been added.
 * </p>
 *
 * @param v the value to add.
 * @throws IllegalArgumentException if <code>v</code> is not comparable with previous entries
 */
public void addValue(Comparable<?> v) {
    Comparable<?> obj = v;
    if (v instanceof Integer) {
        obj = Long.valueOf(((Integer) v).longValue());
    }
    try {
        Long count = freqTable.get(obj);
        if (count == null) {
            freqTable.put(obj, Long.valueOf(1));
        } else {
            freqTable.put(obj, Long.valueOf(count.longValue() + 1));
        }
    } catch (ClassCastException ex) {
        //TreeMap will throw ClassCastException if v is not comparable
        throw new MathIllegalArgumentException(LocalizedFormats.INSTANCES_NOT_COMPARABLE_TO_EXISTING_VALUES,
                v.getClass().getName());
    }
}

From source file:org.codhaus.groovy.grails.validation.ext.ConstrainedPropertyGunn.java

/**
 * @param max The max to set.//from   ww  w .j av  a  2 s  . c o  m
 */
@SuppressWarnings("rawtypes")
public void setMax(Comparable max) {
    if (max == null) {
        appliedConstraints.remove(MAX_CONSTRAINT);
        return;
    }

    if (!propertyType.equals(max.getClass())) {
        throw new MissingPropertyException(MAX_CONSTRAINT, propertyType);
    }

    Range r = getRange();
    if (r != null) {
        LOG.warn("Range constraint already set ignoring constraint [" + MAX_CONSTRAINT + "] for value [" + max
                + "]");
        return;
    }

    Constraint c = appliedConstraints.get(MAX_CONSTRAINT);
    if (c == null) {
        c = new MaxConstraint();
        c.setOwningClass(owningClass);
        c.setPropertyName(propertyName);
        appliedConstraints.put(MAX_CONSTRAINT, c);
    }
    c.setParameter(max);
}

From source file:org.codhaus.groovy.grails.validation.ext.ConstrainedPropertyGunn.java

/**
 * @param min The min to set.// ww w. ja  v  a 2 s  .  co m
 */
@SuppressWarnings("rawtypes")
public void setMin(Comparable min) {
    if (min == null) {
        appliedConstraints.remove(MIN_CONSTRAINT);
        return;
    }

    if (!propertyType.equals(min.getClass())) {
        throw new MissingPropertyException(MIN_CONSTRAINT, propertyType);
    }

    Range r = getRange();
    if (r != null) {
        LOG.warn("Range constraint already set ignoring constraint [" + MIN_CONSTRAINT + "] for value [" + min
                + "]");
        return;
    }

    Constraint c = appliedConstraints.get(MIN_CONSTRAINT);
    if (c == null) {
        c = new MinConstraint();
        c.setOwningClass(owningClass);
        c.setPropertyName(propertyName);
        appliedConstraints.put(MIN_CONSTRAINT, c);
    }
    c.setParameter(min);
}

From source file:jetbrains.exodus.entitystore.iterate.PropertiesIterableWrapper.java

public void update(final int typeId, final long localId, @Nullable final Comparable oldValue,
        @Nullable final Comparable newValue) {
    if (entityTypeId == -1) {
        entityTypeId = typeId;//from   w  w w  . j a v  a2 s  .  c  o  m
    }
    final IndexEntry oldEntry = oldValue == null ? null
            : new IndexEntry(PropertyTypes.toLowerCase(oldValue), localId);
    final IndexEntry newEntry = newValue == null ? null
            : new IndexEntry(PropertyTypes.toLowerCase(newValue), localId);
    if (oldEntry == null && newEntry == null) {
        throw new IllegalStateException("Can't update in-memory index: both oldValue and newValue are null");
    }
    final Persistent23Tree.MutableTree<IndexEntry> index = mutableIndex;
    if (index == null) {
        throw new IllegalStateException("Mutate index before updating it");
    }
    if (oldEntry != null) {
        if (index.contains(oldEntry)) {
            index.exclude(oldEntry);
        } else if (newEntry != null && !index.contains(newEntry)) {
            log.warn("In-memory index doesn't contain the value [" + oldValue + "]. New value [" + newValue
                    + "]. Handle [" + getHandle() + ']');
        }
    }
    if (newEntry != null) {
        index.add(newEntry);
        if (valueClass == null) {
            valueClass = newValue.getClass();
        }
    }
}

From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIDataGrid.java

public Map<String, ? super Object> addDataEntry() {

    final String BEAN_ENTRY_CLASS_NAME = getBindingBeanList().size() > 0
            ? getBindingBeanList().get(0).getClass().getName()
            : getBindingBeanClassName();

    Map<String, ? super Object> addDataResult = new HashMap<String, Object>();
    boolean success = true;

    FacesContext context = FacesContext.getCurrentInstance();
    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();

    String addEntryStartIndex = requestMap.get(ADD_ENTRY_START_INDEX_KEY);
    String addEntryEndIndex = requestMap.get(ADD_ENTRY_END_INDEX_KEY);

    int parsedAddEntryStartIndex = -1;
    int parsedAddEntryEndIndex = -1;

    try {//  ww w. j  a v a 2 s . c  o m
        parsedAddEntryStartIndex = Integer.parseInt(addEntryStartIndex);
        parsedAddEntryEndIndex = Integer.parseInt(addEntryEndIndex);
    } catch (NumberFormatException parsingException) {
        _log.error("Error parsing of following values [" + addEntryStartIndex + ", " + addEntryEndIndex
                + "] to an int", parsingException);
        success = false;
        addDataResult.put(AbstractEvent.ASYNCHRONOUS_VARIABLES.RESULT_CODE.toString(),
                Boolean.valueOf(success));
        return addDataResult;
    }

    _log.info("Parsed add entry start + end index are [ " + parsedAddEntryStartIndex + ", "
            + parsedAddEntryEndIndex + " ] for component : " + getId());
    int loopLength = parsedAddEntryEndIndex - parsedAddEntryStartIndex;
    try {
        Class<?> beanEntryClass = Class.forName(BEAN_ENTRY_CLASS_NAME);
        Comparable<? super Object> beanEntryInstance;

        for (int i = 0; i < loopLength; i++) {

            beanEntryInstance = (Comparable<? super Object>) beanEntryClass.newInstance();

            for (String currDataGridColumnDataField : _dataGridColumnComponentMapping.keySet()) {
                String currDataFieldKey = currDataGridColumnDataField + ADD_DATA_ENTRY_DELIM + i;
                String currDataFieldValue = requestMap.get(currDataFieldKey);

                _log.debug("Setting dataField : " + currDataGridColumnDataField + " with value : "
                        + currDataFieldValue + " for class : " + beanEntryInstance.getClass().getName()
                        + " for component : " + getId());
                AbstractFlexUIDataGridColumn currDataGridColumnComponent = _dataGridColumnComponentMapping
                        .get(currDataGridColumnDataField);
                currDataGridColumnComponent.setDataField(context, beanEntryInstance, currDataFieldValue);
            }

            WrappedBeanEntry currEntry = new WrappedBeanEntry(beanEntryInstance);
            if (isFiltered()) {

                AbstractFlexUIDataGridColumn filterColumnComponent = _dataGridColumnComponentMapping
                        .get(_filterColumn);
                String filterCheckValue = filterColumnComponent.getFormatedColumnData(beanEntryInstance);

                Boolean filterCurrentRow = false;
                if (getFilterComponentId() != null) {
                    filterCurrentRow = invokeFilterMethod(filterCheckValue, getFilterValue());

                    if (filterCurrentRow) {
                        _log.debug("Row containing value of " + filterCheckValue + " was filtered");
                    } else {
                        _filteredList.add(currEntry);

                    }
                }

            }

            synchronized (_wrappedList) {
                _wrappedList.add(_wrappedList.size(), currEntry);
            }

            synchronized (getBindingBeanList()) {
                getBindingBeanList().add(getBindingBeanList().size(), beanEntryInstance);
            }
        }

    } catch (ClassNotFoundException classNotFoundException) {
        _log.error("Failure in finding className " + BEAN_ENTRY_CLASS_NAME, classNotFoundException);
        success = false;
    } catch (IllegalAccessException illegalAccessException) {
        _log.error("Failure in instantiating " + BEAN_ENTRY_CLASS_NAME, illegalAccessException);
        success = false;
    } catch (InstantiationException instantiationException) {
        _log.error("Failure in instantiating " + BEAN_ENTRY_CLASS_NAME, instantiationException);
        success = false;
    }

    _log.info("Success result code after adding the entries to bindingBeanList is : " + success
            + " for component : " + getId() + "new size of bindingBeanList is : "
            + getBindingBeanList().size());

    Integer batchColumnDataRetrievalSize = computeBatchColumnDataRetrievalSize();
    Integer maxDataPartitionIndex = computeMaxDataPartitionIndex();

    deselectAll();
    selectRows(parsedAddEntryEndIndex, parsedAddEntryEndIndex + loopLength);

    addDataResult.put(BATCH_COLUMN_DATA_RETRIEVAL_SIZE_KEY, batchColumnDataRetrievalSize);
    addDataResult.put(MAX_DATA_PARTITION_INDEX_KEY, maxDataPartitionIndex);
    addDataResult.put(AbstractEvent.ASYNCHRONOUS_VARIABLES.RESULT_CODE.toString(), Boolean.valueOf(success));
    return addDataResult;
}

From source file:org.ala.dao.CassandraPelopsHelper.java

/**
 * @see org.ala.dao.StoreHelper#put(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Comparable)
 *//*from  w  ww  .  j a v  a 2s .  co m*/
@Override
public boolean put(String table, String columnFamily, String columnName, String guid, Comparable object)
        throws Exception {
    logger.debug("Pelops put table: " + table + " colFamily: " + columnFamily + " guid: " + guid);
    Mutator mutator = Pelops.createMutator(pool);
    Selector selector = Pelops.createSelector(pool);

    guid = StringUtils.trimToNull(guid);
    if (guid == null || object == null) {
        logger.warn("Null or empty guid supplied. Unable to add to row [" + guid + "] column [" + columnName
                + "] object: " + object);
        return false;
    }

    Column col = null;
    try {
        col = selector.getColumnFromRow(columnFamily, guid, columnName, ConsistencyLevel.ONE);
    } catch (Exception e) {
        //expected behaviour. current thrift API doesnt seem
        //to support a retrieve null getter
        if (logger.isTraceEnabled()) {
            logger.trace(e.getMessage(), e);
        }
    }

    //initialise the object mapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

    //read the existing value
    List<Comparable> objectList = null;
    if (col != null) {
        String value = new String(col.getValue(), charsetEncoding);
        objectList = mapper.readValue(value, TypeFactory.collectionType(ArrayList.class, object.getClass()));
    } else {
        objectList = new ArrayList<Comparable>();
    }

    //add to the collection and sort the objects
    if (objectList.contains(object)) {

        int idx = objectList.indexOf(object);
        //replace with this version
        Comparable objectToReplace = objectList.remove(idx);
        //dont lose rankings!!!!!!!!!!!!!!!!!!!!!!!
        if (object instanceof Rankable) {
            //retrieve those rankings
            RankUtils.copyAcrossRankings((Rankable) objectToReplace, (Rankable) object);
        }
        objectList.add(object);
    } else {
        objectList.add(object);
    }
    Collections.sort(objectList);

    //convert to JSON
    String json = mapper.writeValueAsString(objectList);

    //insert into table
    try {
        mutator.writeColumn(columnFamily, guid, mutator.newColumn(columnName, json));
        mutator.execute(ConsistencyLevel.ONE);
        logger.debug("Pelops put returning");
        return true;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}