Example usage for java.util IdentityHashMap IdentityHashMap

List of usage examples for java.util IdentityHashMap IdentityHashMap

Introduction

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

Prototype

public IdentityHashMap() 

Source Link

Document

Constructs a new, empty identity hash map with a default expected maximum size (21).

Usage

From source file:org.omnaest.utils.proxy.MethodCallCapturer.java

/**
 * Replays the method invocations done to the given stub for the given object like the object would have been invoked in the
 * first place.//from   ww w .  j  ava2  s.  c o  m
 * 
 * @see #replay(Object)
 * @param stub
 * @param object
 * @return {@link ReplayResult}
 */
public <E> ReplayResult replay(E stub, E object) {
    //
    ReplayResult result = new ReplayResult();

    //
    if (stub != null && object != null) {
        //
        Map<Object, Object> stubToObjectMap = new IdentityHashMap<Object, Object>();
        stubToObjectMap.put(stub, object);

        //
        try {
            List<MethodCallCaptureContext> methodCallCaptureContextList = this
                    .getMethodCallCaptureContextList(stub);
            for (MethodCallCaptureContext methodCallCaptureContext : methodCallCaptureContextList) {
                if (methodCallCaptureContext != null) {
                    //
                    MethodCallCapture methodCallCapture = methodCallCaptureContext.getMethodCallCapture();
                    if (methodCallCapture != null) {
                        //
                        Object invocationStub = methodCallCapture.getObject();
                        Object invocationObject = stubToObjectMap.get(invocationStub);

                        //
                        if (invocationObject != null) {
                            Method method = methodCallCapture.getMethod();
                            Object[] args = methodCallCapture.getArguments();
                            if (method != null) {
                                //
                                Object methodInvocationResult = method.invoke(invocationObject, args);

                                //
                                Object returnedStub = methodCallCaptureContext.getReturnedStub();
                                if (returnedStub != null && methodInvocationResult != null) {
                                    stubToObjectMap.put(returnedStub, methodInvocationResult);
                                }
                            }
                        }
                    }
                }
            }

            //
            result.setReplaySuccessful(true);
        } catch (Exception exception) {
            result.setException(exception);
        }
    }

    //
    return result;
}

From source file:org.gluu.site.ldap.persistence.LdapEntryManager.java

private <T> Map<T, List<T>> groupListByPropertiesImpl(Class<T> entryClass, List<T> entries,
        boolean caseSensetive, Getter[] groupPropertyGetters, Setter[] groupPropertySetters,
        Getter[] sumProperyGetters, Setter[] sumPropertySetter) {
    Map<String, T> keys = new HashMap<String, T>();
    Map<T, List<T>> groups = new IdentityHashMap<T, List<T>>();

    for (T entry : entries) {
        String key = getEntryKey(entry, caseSensetive, groupPropertyGetters);

        T entryKey = keys.get(key);//from   w  ww  .  j  a v a 2 s . com
        if (entryKey == null) {
            try {
                entryKey = ReflectHelper.createObjectByDefaultConstructor(entryClass);
            } catch (Exception ex) {
                throw new MappingException(String.format("Entry %s should has default constructor", entryClass),
                        ex);
            }
            try {
                ReflectHelper.copyObjectPropertyValues(entry, entryKey, groupPropertyGetters,
                        groupPropertySetters);
            } catch (Exception ex) {
                throw new MappingException("Failed to set values in group Entry", ex);
            }
            keys.put(key, entryKey);
        }

        List<T> groupValues = groups.get(entryKey);
        if (groupValues == null) {
            groupValues = new ArrayList<T>();
            groups.put(entryKey, groupValues);
        }

        try {
            if (sumProperyGetters != null) {
                ReflectHelper.sumObjectPropertyValues(entryKey, entry, sumProperyGetters, sumPropertySetter);
            }
        } catch (Exception ex) {
            throw new MappingException("Failed to sum values in group Entry", ex);
        }

        groupValues.add(entry);
    }

    return groups;
}

From source file:ca.sqlpower.architect.swingui.SwingUIProjectLoader.java

/**
 * Do just the writing part of save, given a PrintWriter
 * @param out - the file to write to/*from w  w  w  . j a v  a2s  . co m*/
 * @return True iff the save completed OK
 * @throws IOException
 * @throws SQLObjectException
 */
public void save(PrintWriter out, String encoding) throws IOException {
    sqlObjectSaveIdMap = new IdentityHashMap<SQLObject, String>();
    olapObjectSaveIdMap = new IdentityHashMap<OLAPObject, String>();
    dbcsSaveIdMap = new HashMap<SPDataSource, String>();
    olapPaneSaveIdMap = new HashMap<OLAPPane<?, ?>, String>();

    ioo.indent = 0;

    try {
        ioo.println(out, "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>"); //$NON-NLS-1$ //$NON-NLS-2$
        ioo.println(out,
                "<architect-project version=\"1.0\" appversion=\"" + ArchitectVersion.APP_FULL_VERSION + "\">"); //$NON-NLS-1$ //$NON-NLS-2$
        ioo.indent++;
        ioo.println(out,
                "<project-name>" + SQLPowerUtils.escapeXML(getSession().getName()) + "</project-name>"); //$NON-NLS-1$ //$NON-NLS-2$
        savePrintSettings(out, getSession().getPrintSettings());
        saveDataSources(out);
        saveSourceDatabases(out);
        saveTargetDatabase(out);
        saveDDLGenerator(out);
        saveCompareDMSettings(out);
        saveCreateKettleJobSettings(out);
        savePlayPen(out, getSession().getPlayPen(), true);
        saveCriticSettings(out);
        saveProfiles(out);

        saveOLAP(out);
        saveOLAPGUI(out);

        ioo.indent--;
        ioo.println(out, "</architect-project>"); //$NON-NLS-1$

        setModified(false);
        for (OLAPEditSession oSession : getSession().getOLAPEditSessions()) {
            oSession.saveNotify();
        }
    } catch (IOException e) {
        ioo.println(out,
                new ExceptionReport(e, "", ArchitectVersion.APP_FULL_VERSION.toString(), "Architect").toXML());
        throw e;
    } catch (RuntimeException e) {
        ioo.println(out,
                new ExceptionReport(e, "", ArchitectVersion.APP_FULL_VERSION.toString(), "Architect").toXML());
        throw e;
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:com.amazon.janusgraph.diskstorage.dynamodb.DynamoDBDelegate.java

/**
 * Helper method that clones an item/*w  w  w . jav a2 s  . c o  m*/
 *
 * @param item the item to clone
 * @return a clone of item.
 */
public static Map<String, AttributeValue> cloneItem(Map<String, AttributeValue> item) {
    if (item == null) {
        return null;
    }
    Map<String, AttributeValue> clonedItem = Maps.newHashMap();
    IdentityHashMap<AttributeValue, AttributeValue> sourceDestinationMap = new IdentityHashMap<>();

    for (Entry<String, AttributeValue> entry : item.entrySet()) {
        if (!sourceDestinationMap.containsKey(entry.getValue())) {
            sourceDestinationMap.put(entry.getValue(), clone(entry.getValue(), sourceDestinationMap));
        }
        clonedItem.put(entry.getKey(), sourceDestinationMap.get(entry.getValue()));
    }
    return clonedItem;
}

From source file:org.hawk.service.emf.impl.HawkResourceImpl.java

@Override
public Map<EClass, List<EStructuralFeature>> fetchTypesWithEClassifier(final EClassifier dataType)
        throws HawkInstanceNotFound, HawkInstanceNotRunning, UnknownQueryLanguage, InvalidQuery, FailedQuery,
        TException {//from w  w w. j  a  v a2 s  .  co  m
    // TODO: add "getExistingTypes" to Hawk API instead of this EOL query?
    final HawkQueryOptions opts = new HawkQueryOptions();
    opts.setRepositoryPattern(descriptor.getHawkRepository());
    opts.setFilePatterns(Arrays.asList(descriptor.getHawkFilePatterns()));
    setEffectiveMetamodelOptions(opts, descriptor.getEffectiveMetamodel());
    final QueryResult typesWithInstances = client.query(descriptor.getHawkInstance(),
            "return Model.types.select(t|not t.all.isEmpty);", EOL_QUERY_LANG, opts);

    final Map<EClass, List<EStructuralFeature>> candidateTypes = new IdentityHashMap<EClass, List<EStructuralFeature>>();
    for (final QueryResult qr : typesWithInstances.getVList()) {
        final ModelElementType type = qr.getVModelElementType();
        final EClass eClass = getEClass(type.metamodelUri, type.typeName,
                getResourceSet().getPackageRegistry());

        final List<EStructuralFeature> attrsWithType = new ArrayList<>();
        for (final EStructuralFeature attr : eClass.getEAllAttributes()) {
            if (attr.getEType() == dataType) {
                attrsWithType.add(attr);
            }
        }
        if (attrsWithType.isEmpty()) {
            candidateTypes.put(eClass, attrsWithType);
        }
    }
    return candidateTypes;
}

From source file:uk.ac.york.mondo.integration.hawk.emf.impl.HawkResourceImpl.java

@Override
public Map<EClass, List<EStructuralFeature>> fetchTypesWithEClassifier(final EClassifier dataType)
        throws HawkInstanceNotFound, HawkInstanceNotRunning, UnknownQueryLanguage, InvalidQuery, FailedQuery,
        TException {//from   w ww .ja  v a 2s  .c  om
    // TODO: add "getExistingTypes" to Hawk API instead of this EOL query?
    final HawkQueryOptions opts = new HawkQueryOptions();
    opts.setRepositoryPattern(descriptor.getHawkRepository());
    opts.setFilePatterns(Arrays.asList(descriptor.getHawkFilePatterns()));
    setEffectiveMetamodelOptions(opts, descriptor.getEffectiveMetamodel());
    final List<QueryResult> typesWithInstances = client.query(descriptor.getHawkInstance(),
            "return Model.types.select(t|not t.all.isEmpty);", EOL_QUERY_LANG, opts);

    final Map<EClass, List<EStructuralFeature>> candidateTypes = new IdentityHashMap<EClass, List<EStructuralFeature>>();
    for (final QueryResult qr : typesWithInstances) {
        final ModelElementType type = qr.getVModelElementType();
        final EClass eClass = getEClass(type.metamodelUri, type.typeName,
                getResourceSet().getPackageRegistry());

        final List<EStructuralFeature> attrsWithType = new ArrayList<>();
        for (final EStructuralFeature attr : eClass.getEAllAttributes()) {
            if (attr.getEType() == dataType) {
                attrsWithType.add(attr);
            }
        }
        if (attrsWithType.isEmpty()) {
            candidateTypes.put(eClass, attrsWithType);
        }
    }
    return candidateTypes;
}

From source file:org.hawk.service.emf.impl.HawkResourceImpl.java

@Override
public Map<EObject, Object> fetchValuesByEStructuralFeature(final EStructuralFeature feature)
        throws HawkInstanceNotFound, HawkInstanceNotRunning, TException, IOException {
    final EClass featureEClass = feature.getEContainingClass();
    final EList<EObject> eobs = fetchNodes(featureEClass, feature instanceof EAttribute);
    LOGGER.debug("Fetched {} nodes of class {}", eobs.size(), featureEClass.getName());

    if (lazyResolver != null && feature instanceof EReference) {
        // If the feature is a reference, collect all its pending nodes in advance
        final EReference ref = (EReference) feature;

        final List<String> allPending = new ArrayList<String>();
        for (final EObject eob : eobs) {
            EList<Object> pending = lazyResolver.getPending(eob, ref);
            if (pending == null)
                continue;
            for (Object p : pending) {
                if (p instanceof String) {
                    allPending.add((String) p);
                }/*from   w ww.java 2s  .  c  o m*/
            }
        }
        fetchNodes(allPending, false);
    }

    final Map<EObject, Object> values = new IdentityHashMap<>();
    for (final EObject eob : eobs) {
        final Object value = eob.eGet(feature);
        if (value != null) {
            values.put(eob, value);
        } else {
            LOGGER.debug("Value is null for feature {} of object {}", feature.getName(), eob);
        }
    }
    return values;
}

From source file:tools.xor.service.AggregateManager.java

@Override
public void importDenormalized(InputStream is, Settings settings) throws IOException {

    try {//from   w ww .  ja  v  a  2  s . c  om
        Workbook wb = WorkbookFactory.create(is);

        // First create the object based on the denormalized values
        // The callInfo should have root BusinessObject
        // clone the task object using a DataObject

        // Create an object creator for the target root
        ObjectCreator oc = new ObjectCreator(getDAS(), getPersistenceOrchestrator(),
                MapperDirection.EXTERNALTODOMAIN);

        // The Excel should have a single sheet containing the denormalized data
        // Create a JSONObject for each row
        Sheet entitySheet = wb.getSheetAt(0);
        Map<String, Integer> colMap = getHeaderMap(wb.getSheetAt(0));

        Map<BusinessObject, Object> roots = new IdentityHashMap<BusinessObject, Object>();
        for (int i = 1; i <= entitySheet.getLastRowNum(); i++) {
            Row row = entitySheet.getRow(i);

            Property idProperty = ((EntityType) settings.getEntityType()).getIdentifierProperty();
            String idName = idProperty.getName();
            if (!colMap.containsKey(idName)) {
                throw new RuntimeException("The Excel sheet needs to have the entity identifier column");
            }

            // TODO: Create a JSON object and then extract the value with the correct type
            Object idValue = getCellValue(row.getCell(colMap.get(idName)));
            if (idProperty.getType() instanceof SimpleType) {
                idValue = ((SimpleType) idProperty.getType()).unmarshall(idValue.toString());
            }

            // Get a child business object of the same type
            // TODO: Get by user key
            EntityKey ek = oc.getTypeMapper().getEntityKey(idValue, settings.getEntityType());
            BusinessObject bo = oc.getByEntityKey(ek);
            if (bo == null) {

                bo = oc.createDataObject(AbstractBO.createInstance(oc, idValue, settings.getEntityType()),
                        settings.getEntityType(), null, null);
                BusinessObject potentialRoot = (BusinessObject) bo.getRootObject();
                if (!roots.containsKey(potentialRoot)) {
                    roots.put(potentialRoot, null);
                }
            }

            for (Map.Entry<String, Integer> entry : colMap.entrySet()) {
                Cell cell = row.getCell(entry.getValue());
                Object cellValue = getCellValue(cell);
                Property property = ((EntityType) settings.getEntityType()).getProperty(entry.getKey());
                cellValue = ((SimpleType) property.getType()).unmarshall(cellValue.toString());
                bo.set(entry.getKey(), cellValue);
            }
        }
        for (BusinessObject root : roots.keySet()) {
            this.update(root.getInstance(), settings);
        }

    } catch (EncryptedDocumentException e) {
        throw new RuntimeException("Document is encrypted, provide a decrypted inputstream", e);
    } catch (InvalidFormatException e) {
        throw new RuntimeException("The provided inputstream is not valid. ", e);
    } catch (Exception e) {
        throw new RuntimeException("An error occurred during update.", e);
    }
}

From source file:ded.ui.DiagramController.java

/** Copy the selected entities to the (application) clipboard. */
public void copySelected() {
    IdentityHashSet<Controller> selControllers = this.getAllSelected();
    if (selControllers.isEmpty()) {
        this.errorMessageBox("Nothing is selected to copy.");
        return;/*ww  w .  j  av a2s. c  o m*/
    }

    // Collect all the selected elements.
    IdentityHashSet<Entity> selEntities = new IdentityHashSet<Entity>();
    IdentityHashSet<Inheritance> selInheritances = new IdentityHashSet<Inheritance>();
    IdentityHashSet<Relation> selRelations = new IdentityHashSet<Relation>();
    for (Controller c : selControllers) {
        if (c instanceof EntityController) {
            selEntities.add(((EntityController) c).entity);
        }
        if (c instanceof InheritanceController) {
            selInheritances.add(((InheritanceController) c).inheritance);
        }
        if (c instanceof RelationController) {
            selRelations.add(((RelationController) c).relation);
        }
    }

    // Map from elements in the original to their counterpart in the copy.
    IdentityHashMap<Entity, Entity> entityToCopy = new IdentityHashMap<Entity, Entity>();
    IdentityHashMap<Inheritance, Inheritance> inheritanceToCopy = new IdentityHashMap<Inheritance, Inheritance>();

    // Construct a new Diagram with just the selected elements.
    Diagram copy = new Diagram();
    for (Entity e : selEntities) {
        Entity eCopy = new Entity(e);
        entityToCopy.put(e, eCopy);
        copy.entities.add(eCopy);
    }
    for (Inheritance i : selInheritances) {
        // See if the parent entity is among those we are copying.
        Entity parentCopy = entityToCopy.get(i.parent);
        if (parentCopy == null) {
            // No, so we'll skip the inheritance too.
        } else {
            Inheritance iCopy = new Inheritance(i, parentCopy);
            inheritanceToCopy.put(i, iCopy);
            copy.inheritances.add(iCopy);
        }
    }
    for (Relation r : selRelations) {
        RelationEndpoint startCopy = copyRelationEndpoint(r.start, entityToCopy, inheritanceToCopy);
        RelationEndpoint endCopy = copyRelationEndpoint(r.end, entityToCopy, inheritanceToCopy);
        if (startCopy == null || endCopy == null) {
            // Skip the relation.
        } else {
            copy.relations.add(new Relation(r, startCopy, endCopy));
        }
    }

    // Make sure the Diagram is well-formed.
    try {
        // This is quadratic...
        copy.selfCheck();
    } catch (Throwable t) {
        this.errorMessageBox("Internal error: failed to create a well-formed copy: " + t);
        return;
    }

    // Copy it as a string to the system clipboard.
    StringSelection data = new StringSelection(copy.toJSONString());
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(data, data);
    clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
    if (clipboard != null) {
        clipboard.setContents(data, data);
    }
}

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * handling readObject method is necessary in order to have the library
 * reconstructed after a serialization/*from ww  w. ja va  2  s .com*/
 */
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    currentObjects = new HashMap<>();
    currentObjects_inverse = new IdentityHashMap<>();
    preregisterObjects();
}