Example usage for java.util IdentityHashMap get

List of usage examples for java.util IdentityHashMap get

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.apache.pig.pen.LineageTrimmingVisitor.java

private Map<LOLoad, DataBag> PruneBaseDataConstrainedCoverage(Map<LOLoad, DataBag> baseData,
        LineageTracer lineage, Collection<IdentityHashSet<Tuple>> equivalenceClasses) {

    IdentityHashMap<Tuple, Collection<Tuple>> membershipMap = lineage.getMembershipMap();
    IdentityHashMap<Tuple, Double> lineageGroupWeights = lineage.getWeightedCounts(2f, 1);

    // compute a mapping from lineage group to the set of equivalence
    // classes covered by it
    // IdentityHashMap<Tuple, Set<Integer>> lineageGroupToEquivClasses = new
    // IdentityHashMap<Tuple, Set<Integer>>();
    IdentityHashMap<Tuple, Set<IdentityHashSet<Tuple>>> lineageGroupToEquivClasses = new IdentityHashMap<Tuple, Set<IdentityHashSet<Tuple>>>();
    for (IdentityHashSet<Tuple> equivClass : equivalenceClasses) {
        for (Object t : equivClass) {
            Tuple lineageGroup = lineage.getRepresentative((Tuple) t);
            // Set<Integer> entry =
            // lineageGroupToEquivClasses.get(lineageGroup);
            Set<IdentityHashSet<Tuple>> entry = lineageGroupToEquivClasses.get(lineageGroup);
            if (entry == null) {
                // entry = new HashSet<Integer>();
                entry = new HashSet<IdentityHashSet<Tuple>>();
                lineageGroupToEquivClasses.put(lineageGroup, entry);
            }/*from  w  w  w .ja v a 2s. c o  m*/
            // entry.add(equivClassId);
            entry.add(equivClass);
        }
    }

    // select lineage groups such that we cover all equivalence classes
    IdentityHashSet<Tuple> selectedLineageGroups = new IdentityHashSet<Tuple>();
    while (!lineageGroupToEquivClasses.isEmpty()) {
        // greedily find the lineage group with the best "score", where
        // score = # equiv classes covered / group weight
        double bestWeight = -1;
        Tuple bestLineageGroup = null;
        Set<IdentityHashSet<Tuple>> bestEquivClassesCovered = null;
        int bestNumEquivClassesCovered = 0;
        for (Tuple lineageGroup : lineageGroupToEquivClasses.keySet()) {
            double weight = lineageGroupWeights.get(lineageGroup);

            Set<IdentityHashSet<Tuple>> equivClassesCovered = lineageGroupToEquivClasses.get(lineageGroup);
            int numEquivClassesCovered = equivClassesCovered.size();

            if ((numEquivClassesCovered > bestNumEquivClassesCovered)
                    || (numEquivClassesCovered == bestNumEquivClassesCovered && weight < bestWeight)) {

                if (selectedLineageGroups.contains(lineageGroup)) {
                    bestLineageGroup = lineageGroup;
                    bestEquivClassesCovered = equivClassesCovered;
                    continue;
                }

                bestWeight = weight;
                bestLineageGroup = lineageGroup;
                bestNumEquivClassesCovered = numEquivClassesCovered;
                bestEquivClassesCovered = equivClassesCovered;
            }
        }
        // add the best-scoring lineage group to the set of ones we plan to
        // retain
        selectedLineageGroups.add(bestLineageGroup);

        // make copy of bestEquivClassesCovered (or else the code that
        // follows won't work correctly, because removing from the reference
        // set)
        Set<IdentityHashSet<Tuple>> toCopy = bestEquivClassesCovered;
        bestEquivClassesCovered = new HashSet<IdentityHashSet<Tuple>>();
        bestEquivClassesCovered.addAll(toCopy);

        // remove the classes we've now covered
        Collection<Tuple> toRemove = new LinkedList<Tuple>();
        for (Tuple lineageGroup : lineageGroupToEquivClasses.keySet()) {

            Set<IdentityHashSet<Tuple>> equivClasses = lineageGroupToEquivClasses.get(lineageGroup);

            for (Iterator<IdentityHashSet<Tuple>> it = equivClasses.iterator(); it.hasNext();) {
                IdentityHashSet<Tuple> equivClass = it.next();
                if (bestEquivClassesCovered.contains(equivClass)) {
                    it.remove();
                }
            }
            if (equivClasses.size() == 0)
                toRemove.add(lineageGroup);

        }
        for (Tuple removeMe : toRemove)
            lineageGroupToEquivClasses.remove(removeMe);
    }

    // revise baseData to only contain the tuples that are part of
    // selectedLineageGroups
    IdentityHashSet<Tuple> tuplesToRetain = new IdentityHashSet<Tuple>();
    for (Tuple lineageGroup : selectedLineageGroups) {
        Collection<Tuple> members = membershipMap.get(lineageGroup);
        for (Tuple t : members)
            tuplesToRetain.add(t);
    }

    Map<LOLoad, DataBag> newBaseData = new HashMap<LOLoad, DataBag>();
    for (LOLoad loadOp : baseData.keySet()) {
        DataBag data = baseData.get(loadOp);
        // DataBag newData = new DataBag();
        DataBag newData = BagFactory.getInstance().newDefaultBag();
        for (Iterator<Tuple> it = data.iterator(); it.hasNext();) {
            Tuple t = it.next();
            if (tuplesToRetain.contains(t))
                newData.add(t);
        }
        newBaseData.put(loadOp, newData);
    }

    return newBaseData;
}

From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java

public void testEntrySetRemove() {
    IdentityHashMap hashMap = new IdentityHashMap();
    hashMap.put("A", "B");
    IdentityHashMap dummy = new IdentityHashMap();
    dummy.put("A", "b");
    Entry bogus = (Entry) dummy.entrySet().iterator().next();
    Set entrySet = hashMap.entrySet();
    boolean removed = entrySet.remove(bogus);
    assertEquals(removed, false);//  www. j  a v  a 2  s.  com
    assertEquals(hashMap.get("A"), "B");
}

From source file:ca.uhn.fhir.rest.method.TransactionMethodBinding.java

@SuppressWarnings("unchecked")
@Override/*from  w ww  .jav  a  2 s  .  com*/
public Object invokeServer(IRestfulServer theServer, RequestDetails theRequest, Object[] theMethodParams)
        throws InvalidRequestException, InternalErrorException {

    /*
     * The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a
     * bunch of resources (because that's what it was), but in DSTU2 transaction has become much more broad, so we
     * no longer hold the user's hand much here.
     */
    if (myTransactionParamStyle == ParamStyle.RESOURCE_BUNDLE) {
        // This is the DSTU2 style
        Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
        return response;
    }

    // Grab the IDs of all of the resources in the transaction
    List<IResource> resources;
    if (theMethodParams[myTransactionParamIndex] instanceof Bundle) {
        resources = ((Bundle) theMethodParams[myTransactionParamIndex]).toListOfResources();
    } else {
        resources = (List<IResource>) theMethodParams[myTransactionParamIndex];
    }

    IdentityHashMap<IResource, IdDt> oldIds = new IdentityHashMap<IResource, IdDt>();
    for (IResource next : resources) {
        oldIds.put(next, next.getId());
    }

    // Call the server implementation method
    Object response = invokeServerMethod(theServer, theRequest, theMethodParams);
    IBundleProvider retVal = toResourceList(response);

    /*
     * int offset = 0; if (retVal.size() != resources.size()) { if (retVal.size() > 0 && retVal.getResources(0,
     * 1).get(0) instanceof OperationOutcome) { offset = 1; } else { throw new
     * InternalErrorException("Transaction bundle contained " + resources.size() +
     * " entries, but server method response contained " + retVal.size() + " entries (must be the same)"); } }
     */

    List<IBaseResource> retResources = retVal.getResources(0, retVal.size());
    for (int i = 0; i < retResources.size(); i++) {
        IdDt oldId = oldIds.get(retResources.get(i));
        IBaseResource newRes = retResources.get(i);
        if (newRes.getIdElement() == null || newRes.getIdElement().isEmpty()) {
            if (!(newRes instanceof BaseOperationOutcome)) {
                throw new InternalErrorException("Transaction method returned resource at index " + i
                        + " with no id specified - IResource#setId(IdDt)");
            }
        }

        if (oldId != null && !oldId.isEmpty()) {
            if (!oldId.equals(newRes.getIdElement()) && newRes instanceof IResource) {
                ((IResource) newRes).getResourceMetadata().put(ResourceMetadataKeyEnum.PREVIOUS_ID, oldId);
            }
        }
    }

    return retVal;
}

From source file:ded.ui.DiagramController.java

/** Make a copy of 'src', taking advantage of the maps to corresponding
  * entities and inheritances already copied. */
private static RelationEndpoint copyRelationEndpoint(RelationEndpoint src,
        IdentityHashMap<Entity, Entity> entityToCopy,
        IdentityHashMap<Inheritance, Inheritance> inheritanceToCopy) {
    RelationEndpoint ret;//from   w  w w  . j a  v  a  2s. c o  m

    if (src.entity != null) {
        Entity eCopy = entityToCopy.get(src.entity);
        if (eCopy == null) {
            // Counterpart is not copied, so we will bail on the
            // endpoint, and hence the relation too.
            return null;
        }
        ret = new RelationEndpoint(eCopy);
    }

    else if (src.inheritance != null) {
        Inheritance iCopy = inheritanceToCopy.get(src.inheritance);
        if (iCopy == null) {
            return null;
        }
        ret = new RelationEndpoint(iCopy);
    }

    else {
        ret = new RelationEndpoint(new Point(src.pt));
    }

    ret.arrowStyle = src.arrowStyle;
    return ret;
}

From source file:cdr.forms.SwordDepositHandler.java

private File makeZipFile(gov.loc.mets.DocumentRoot metsDocumentRoot,
        IdentityHashMap<DepositFile, String> filenames) {

    // Get the METS XML

    String metsXml = serializeMets(metsDocumentRoot);

    // Create the zip file

    File zipFile;/*from   w w  w  .j  av a2 s . c  o  m*/

    try {
        zipFile = File.createTempFile("tmp", ".zip");
    } catch (IOException e) {
        throw new Error(e);
    }

    FileOutputStream fileOutput;

    try {
        fileOutput = new FileOutputStream(zipFile);
    } catch (FileNotFoundException e) {
        throw new Error(e);
    }

    ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

    try {

        ZipEntry entry;

        // Write the METS

        entry = new ZipEntry("mets.xml");
        zipOutput.putNextEntry(entry);

        PrintStream xmlPrintStream = new PrintStream(zipOutput);
        xmlPrintStream.print(metsXml);

        // Write files

        for (DepositFile file : filenames.keySet()) {

            if (!file.isExternal()) {

                entry = new ZipEntry(filenames.get(file));
                zipOutput.putNextEntry(entry);

                FileInputStream fileInput = new FileInputStream(file.getFile());

                byte[] buffer = new byte[1024];
                int length;

                while ((length = fileInput.read(buffer)) != -1)
                    zipOutput.write(buffer, 0, length);

                fileInput.close();

            }

        }

        zipOutput.finish();
        zipOutput.close();

        fileOutput.close();

    } catch (IOException e) {

        throw new Error(e);

    }

    return zipFile;

}

From source file:org.batoo.jpa.core.impl.manager.EntityManagerImpl.java

/**
 * Cascaded implementation of {@link #merge(Object)}.
 * <p>/*from w  w  w  .j a va 2 s  . c om*/
 * Also manages a direct or indirect requirement to an implicit flush.
 * 
 * @param entity
 *            the entity to cascade
 * @param requiresFlush
 *            if an implicit flush is required
 * @param processed
 *            registry of processed entities
 * @param instances
 *            the persisted instances
 * @param cascade
 *            cascades the merge operation
 * @param <T>
 *            the type of the entity
 * @return true if an implicit flush is required, false otherwise
 * 
 * @since 2.0.0
 */
@SuppressWarnings("unchecked")
public <T> T mergeImpl(T entity, MutableBoolean requiresFlush, IdentityHashMap<Object, Object> processed,
        LinkedList<ManagedInstance<?>> instances, boolean cascade) {
    if (entity == null) {
        return null;
    }

    // if already processed just return
    final T processedEntity = (T) processed.get(entity);
    if (processedEntity != null) {
        return processedEntity;
    }

    // try to locate the instance in the session
    ManagedInstance<T> instance = this.session.get(entity);

    Class<?> clazz = entity.getClass();
    if (entity instanceof EnhancedInstance) {
        clazz = clazz.getSuperclass();
    }

    final EntityTypeImpl<T> type = (EntityTypeImpl<T>) this.metamodel.entity(clazz);

    // if it is in the session then test its status
    if (instance != null) {
        // if it is a removed entity then throw
        if (instance.getStatus() == Status.REMOVED) {
            throw new IllegalArgumentException("Entity has been previously removed");
        }

        // if it is an existing instance then merge and return
        if ((instance.getStatus() == Status.MANAGED) || (instance.getStatus() == Status.NEW)) {
            processed.put(entity, instance.getInstance());
            if (instance.getStatus() == Status.NEW) {
                instances.add(instance);
            }

            if (instance.getInstance() != entity) {
                instance.mergeWith(this, entity, requiresFlush, processed, instances);
            } else {
                this.cascadeMerge(type, entity, requiresFlush, processed, instances);
            }

            return instance.getInstance();
        }
    }

    // get the id of the entity
    final Object id = type.getInstanceId(entity);

    // if it has an id try to locate instance in the database
    if (id != null) {
        T existingEntity = null;
        try {
            existingEntity = this.find((Class<T>) clazz, id);
        } catch (final NoResultException e) {
        }

        // if it is found in the database then merge and return
        if (existingEntity != null) {
            instance = (ManagedInstance<T>) ((EnhancedInstance) existingEntity)
                    .__enhanced__$$__getManagedInstance();

            processed.put(entity, instance.getInstance());

            instance.mergeWith(this, entity, requiresFlush, processed, instances);

            return instance.getInstance();
        }
    }

    // it is a new instance, create a new instance and merge with it
    final ManagedId<T> managedId = new ManagedId<T>(id, type);
    instance = type.getManagedInstanceById(this.session, managedId, false);

    instance.setStatus(Status.NEW);

    instance.enhanceCollections();

    this.session.putExternal(instance);
    processed.put(entity, instance.getInstance());
    instances.add(instance);

    instance.mergeWith(this, entity, requiresFlush, processed, instances);

    if (!instance.fillIdValues()) {
        requiresFlush.setValue(true);
    }

    return instance.getInstance();
}

From source file:com.thesmartweb.swebrank.Moz.java

/**
 * Method that captures the various Moz metrics for the provided urls (with help of the sample here https://github.com/seomoz/SEOmozAPISamples
 * and ranks them accordingly//from w w  w.  j  a  v a  2s. c  o  m
 * @param links the urls to analyze
 * @param top_count the amount of results to keep when we rerank the results according to their value of a specific Moz metric
 * @param moz_threshold the threshold to the Moz value to use
 * @param moz_threshold_option flag if we are going to use threshold in the Moz value or not
 * @param mozMetrics list that contains which metric to use for Moz //1st place is Page Authority,2nd external mozRank, 3rd, mozTrust, 4th DomainAuthority and 5th MozRank (it is the default)
 * @param config_path path that has the config files with the api keys and secret for Moz
 * @return an array with the links sorted according to their moz values
 */
public String[] perform(String[] links, int top_count, Double moz_threshold, Boolean moz_threshold_option,
        List<Boolean> mozMetrics, String config_path) {
    //=====short codes for the metrics 
    long upa = 34359738368L;//page authority
    long pda = 68719476736L;//domain authority
    long uemrp = 1048576;//mozrank external equity
    long utrp = 131072;//moztrust 
    long fmrp = 32768;//mozrank subdomain
    long umrp = 16384;//mozrank
    System.gc();
    System.out.println("into Moz");
    Double[] mozRanks = new Double[links.length];
    DataManipulation textualmanipulation = new DataManipulation();
    for (int i = 0; i < links.length; i++) {
        if (links[i] != null) {
            if (!textualmanipulation.StructuredFileCheck(links[i])) {
                try {
                    Thread.sleep(10000);
                    URLMetricsService urlMetricsservice;
                    urlMetricsservice = authenticate(config_path);
                    String objectURL = links[i].substring(0, links[i].length());
                    Gson gson = new Gson();
                    if (mozMetrics.get(1)) {//Domain Authority
                        String response = urlMetricsservice.getUrlMetrics(objectURL, pda);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getPda();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(2)) {//External MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, uemrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUemrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(3)) {//MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, umrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUmrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(4)) {//MozTrust
                        String response = urlMetricsservice.getUrlMetrics(objectURL, utrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUtrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(5)) {//Page Authority
                        String response = urlMetricsservice.getUrlMetrics(objectURL, upa);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUpa();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(6)) {//subdomain MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, fmrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getFmrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    }
                } catch (InterruptedException | JsonSyntaxException | NumberFormatException ex) {
                    System.out.println("exception moz:" + ex.toString());
                    mozRanks[i] = Double.parseDouble("0");
                    String[] links_out = null;
                    return links_out;
                }
            } else {
                mozRanks[i] = Double.parseDouble("0");
            }
        }
    }
    try {//ranking of the urls according to their moz score
         //get the scores to a list
        System.out.println("I am goint to rank the scores of Moz");
        System.gc();
        List<Double> seomozRanks_scores_list = Arrays.asList(mozRanks);
        //create a hashmap in order to map the scores with the indexes
        System.gc();
        IdentityHashMap<Double, Integer> originalIndices = new IdentityHashMap<Double, Integer>();
        //copy the original scores list
        System.gc();
        for (int i = 0; i < seomozRanks_scores_list.size(); i++) {
            originalIndices.put(seomozRanks_scores_list.get(i), i);
            System.gc();
        }
        //sort the scores
        List<Double> sorted_seomozRanks_scores = new ArrayList<Double>();
        System.gc();
        sorted_seomozRanks_scores.addAll(seomozRanks_scores_list);
        System.gc();
        sorted_seomozRanks_scores.removeAll(Collections.singleton(null));
        System.gc();
        if (!sorted_seomozRanks_scores.isEmpty()) {
            Collections.sort(sorted_seomozRanks_scores, Collections.reverseOrder());
        }
        //get the original indexes
        //the max amount of results
        int[] origIndex = new int[150];
        if (!sorted_seomozRanks_scores.isEmpty()) {
            //if we want to take the top scores(for example top 10)
            if (!moz_threshold_option) {
                origIndex = new int[top_count];
                for (int i = 0; i < top_count; i++) {
                    Double score = sorted_seomozRanks_scores.get(i);
                    System.gc();
                    // Lookup original index efficiently
                    origIndex[i] = originalIndices.get(score);
                }
            }
            //if we have a threshold
            else if (moz_threshold_option) {
                int j = 0;
                int counter = 0;
                while (j < sorted_seomozRanks_scores.size()) {
                    if (sorted_seomozRanks_scores.get(j).compareTo(moz_threshold) >= 0) {
                        counter++;
                    }
                    j++;
                }
                origIndex = new int[counter];
                for (int k = 0; k < origIndex.length - 1; k++) {
                    System.gc();
                    Double score = sorted_seomozRanks_scores.get(k);
                    origIndex[k] = originalIndices.get(score);
                }
            }
        }
        String[] links_out = new String[origIndex.length];
        for (int jj = 0; jj < origIndex.length; jj++) {
            System.gc();
            links_out[jj] = links[origIndex[jj]];
        }
        System.gc();
        System.out.println("I have ranked the scores of moz");
        return links_out;
    } catch (Exception ex) {
        System.out.println("exception moz list" + ex.toString());
        //Logger.getLogger(Moz.class.getName()).log(Level.SEVERE, null, ex);
        String[] links_out = null;
        return links_out;
    }
}

From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java

/**
 * Test method for 'java.util.IdentityHashMap.putAll(Map)'.
 *//*from w w  w.j a  v a  2 s  .  co  m*/
public void testPutAll() {
    IdentityHashMap srcMap = new IdentityHashMap();
    checkEmptyHashMapAssumptions(srcMap);

    srcMap.put(KEY_1, VALUE_1);
    srcMap.put(KEY_2, VALUE_2);
    srcMap.put(KEY_3, VALUE_3);

    // Make sure that the data is copied correctly
    IdentityHashMap dstMap = new IdentityHashMap();
    checkEmptyHashMapAssumptions(dstMap);

    dstMap.putAll(srcMap);
    assertEquals(srcMap.size(), dstMap.size());
    assertTrue(dstMap.containsKey(KEY_1));
    assertTrue(dstMap.containsValue(VALUE_1));
    assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_2));
    assertTrue(dstMap.containsValue(VALUE_2));
    assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_3));
    assertTrue(dstMap.containsValue(VALUE_3));
    assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT)));

    // Check that an empty map does not blow away the contents of the
    // destination map
    IdentityHashMap emptyMap = new IdentityHashMap();
    checkEmptyHashMapAssumptions(emptyMap);
    dstMap.putAll(emptyMap);
    assertTrue(dstMap.size() == srcMap.size());

    // Check that put all overwrite any existing mapping in the destination map
    srcMap.put(KEY_1, VALUE_2);
    srcMap.put(KEY_2, VALUE_3);
    srcMap.put(KEY_3, VALUE_1);

    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);

    // Check that a putAll does adds data but does not remove it

    srcMap.put(KEY_4, VALUE_4);
    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertTrue(dstMap.containsKey(KEY_4));
    assertTrue(dstMap.containsValue(VALUE_4));
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);
    assertEquals(dstMap.get(KEY_4), VALUE_4);

    dstMap.putAll(dstMap);
}

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;/* w w  w. j a v a  2  s. 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:ca.uhn.fhir.jpa.dao.dstu3.FhirSystemDaoDstu3.java

@SuppressWarnings("unchecked")
private Bundle transaction(ServletRequestDetails theRequestDetails, Bundle theRequest, String theActionName) {
    BundleType transactionType = theRequest.getTypeElement().getValue();
    if (transactionType == BundleType.BATCH) {
        return batch(theRequestDetails, theRequest);
    }/*from  w  ww  .j  a v  a2  s . co m*/

    if (transactionType == null) {
        String message = "Transactiion Bundle did not specify valid Bundle.type, assuming "
                + BundleType.TRANSACTION.toCode();
        ourLog.warn(message);
        transactionType = BundleType.TRANSACTION;
    }
    if (transactionType != BundleType.TRANSACTION) {
        throw new InvalidRequestException(
                "Unable to process transaction where incoming Bundle.type = " + transactionType.toCode());
    }

    ourLog.info("Beginning {} with {} resources", theActionName, theRequest.getEntry().size());

    long start = System.currentTimeMillis();
    Date updateTime = new Date();

    Set<IdType> allIds = new LinkedHashSet<IdType>();
    Map<IdType, IdType> idSubstitutions = new HashMap<IdType, IdType>();
    Map<IdType, DaoMethodOutcome> idToPersistedOutcome = new HashMap<IdType, DaoMethodOutcome>();

    // Do all entries have a verb?
    for (int i = 0; i < theRequest.getEntry().size(); i++) {
        BundleEntryComponent nextReqEntry = theRequest.getEntry().get(i);
        HTTPVerb verb = nextReqEntry.getRequest().getMethodElement().getValue();
        if (verb == null) {
            throw new InvalidRequestException(
                    getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class,
                            "transactionEntryHasInvalidVerb", nextReqEntry.getRequest().getMethod(), i));
        }
    }

    /*
     * We want to execute the transaction request bundle elements in the order
     * specified by the FHIR specification (see TransactionSorter) so we save the
     * original order in the request, then sort it.
     * 
     * Entries with a type of GET are removed from the bundle so that they
     * can be processed at the very end. We do this because the incoming resources
     * are saved in a two-phase way in order to deal with interdependencies, and
     * we want the GET processing to use the final indexing state
     */
    Bundle response = new Bundle();
    List<BundleEntryComponent> getEntries = new ArrayList<BundleEntryComponent>();
    IdentityHashMap<BundleEntryComponent, Integer> originalRequestOrder = new IdentityHashMap<Bundle.BundleEntryComponent, Integer>();
    for (int i = 0; i < theRequest.getEntry().size(); i++) {
        originalRequestOrder.put(theRequest.getEntry().get(i), i);
        response.addEntry();
        if (theRequest.getEntry().get(i).getRequest().getMethodElement().getValue() == HTTPVerb.GET) {
            getEntries.add(theRequest.getEntry().get(i));
        }
    }
    Collections.sort(theRequest.getEntry(), new TransactionSorter());

    Set<String> deletedResources = new HashSet<String>();
    List<DeleteConflict> deleteConflicts = new ArrayList<DeleteConflict>();
    Map<BundleEntryComponent, ResourceTable> entriesToProcess = new IdentityHashMap<BundleEntryComponent, ResourceTable>();
    Set<ResourceTable> nonUpdatedEntities = new HashSet<ResourceTable>();

    /*
     * Loop through the request and process any entries of type
     * PUT, POST or DELETE
     */
    for (int i = 0; i < theRequest.getEntry().size(); i++) {

        if (i % 100 == 0) {
            ourLog.info("Processed {} non-GET entries out of {}", i, theRequest.getEntry().size());
        }

        BundleEntryComponent nextReqEntry = theRequest.getEntry().get(i);
        Resource res = nextReqEntry.getResource();
        IdType nextResourceId = null;
        if (res != null) {

            nextResourceId = res.getIdElement();

            if (nextResourceId.hasIdPart() == false) {
                if (isNotBlank(nextReqEntry.getFullUrl())) {
                    nextResourceId = new IdType(nextReqEntry.getFullUrl());
                }
            }

            if (nextResourceId.hasIdPart() && nextResourceId.getIdPart().matches("[a-zA-Z]+\\:.*")
                    && !isPlaceholder(nextResourceId)) {
                throw new InvalidRequestException("Invalid placeholder ID found: " + nextResourceId.getIdPart()
                        + " - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'");
            }

            if (nextResourceId.hasIdPart() && !nextResourceId.hasResourceType()
                    && !isPlaceholder(nextResourceId)) {
                nextResourceId = new IdType(toResourceName(res.getClass()), nextResourceId.getIdPart());
                res.setId(nextResourceId);
            }

            /*
             * Ensure that the bundle doesn't have any duplicates, since this causes all kinds of weirdness
             */
            if (isPlaceholder(nextResourceId)) {
                if (!allIds.add(nextResourceId)) {
                    throw new InvalidRequestException(
                            getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class,
                                    "transactionContainsMultipleWithDuplicateId", nextResourceId));
                }
            } else if (nextResourceId.hasResourceType() && nextResourceId.hasIdPart()) {
                IdType nextId = nextResourceId.toUnqualifiedVersionless();
                if (!allIds.add(nextId)) {
                    throw new InvalidRequestException(getContext().getLocalizer().getMessage(
                            BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextId));
                }
            }

        }

        HTTPVerb verb = nextReqEntry.getRequest().getMethodElement().getValue();

        String resourceType = res != null ? getContext().getResourceDefinition(res).getName() : null;
        BundleEntryComponent nextRespEntry = response.getEntry().get(originalRequestOrder.get(nextReqEntry));

        switch (verb) {
        case POST: {
            // CREATE
            @SuppressWarnings("rawtypes")
            IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass());
            res.setId((String) null);
            DaoMethodOutcome outcome;
            outcome = resourceDao.create(res, nextReqEntry.getRequest().getIfNoneExist(), false,
                    theRequestDetails);
            handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId,
                    outcome, nextRespEntry, resourceType, res);
            entriesToProcess.put(nextRespEntry, outcome.getEntity());
            if (outcome.getCreated() == false) {
                nonUpdatedEntities.add(outcome.getEntity());
            }

            break;
        }
        case DELETE: {
            // DELETE
            String url = extractTransactionUrlOrThrowException(nextReqEntry, verb);
            UrlParts parts = UrlUtil.parseUrl(url);
            ca.uhn.fhir.jpa.dao.IFhirResourceDao<? extends IBaseResource> dao = toDao(parts, verb.toCode(),
                    url);
            int status = Constants.STATUS_HTTP_204_NO_CONTENT;
            if (parts.getResourceId() != null) {
                IdType deleteId = new IdType(parts.getResourceType(), parts.getResourceId());
                if (!deletedResources.contains(deleteId.getValueAsString())) {
                    ResourceTable deleted = dao.delete(deleteId, deleteConflicts, theRequestDetails);
                    if (deleted != null) {
                        deletedResources.add(deleteId.getValueAsString());
                    }
                }
            } else {
                List<ResourceTable> allDeleted = dao.deleteByUrl(
                        parts.getResourceType() + '?' + parts.getParams(), deleteConflicts, theRequestDetails);
                for (ResourceTable deleted : allDeleted) {
                    deletedResources.add(deleted.getIdDt().toUnqualifiedVersionless().getValueAsString());
                }
                if (allDeleted.isEmpty()) {
                    status = Constants.STATUS_HTTP_204_NO_CONTENT;
                }
            }

            nextRespEntry.getResponse().setStatus(toStatusString(status));
            break;
        }
        case PUT: {
            // UPDATE
            @SuppressWarnings("rawtypes")
            IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass());

            String url = extractTransactionUrlOrThrowException(nextReqEntry, verb);

            DaoMethodOutcome outcome;
            UrlParts parts = UrlUtil.parseUrl(url);
            if (isNotBlank(parts.getResourceId())) {
                res.setId(new IdType(parts.getResourceType(), parts.getResourceId()));
                outcome = resourceDao.update(res, null, false, theRequestDetails);
            } else {
                res.setId((String) null);
                outcome = resourceDao.update(res, parts.getResourceType() + '?' + parts.getParams(), false,
                        theRequestDetails);
            }

            handleTransactionCreateOrUpdateOutcome(idSubstitutions, idToPersistedOutcome, nextResourceId,
                    outcome, nextRespEntry, resourceType, res);
            entriesToProcess.put(nextRespEntry, outcome.getEntity());
            break;
        }
        }
    }

    /*
     * Make sure that there are no conflicts from deletions. E.g. we can't delete something
     * if something else has a reference to it.. Unless the thing that has a reference to it
     * was also deleted as a part of this transaction, which is why we check this now at the
     * end.
     */

    for (Iterator<DeleteConflict> iter = deleteConflicts.iterator(); iter.hasNext();) {
        DeleteConflict next = iter.next();
        if (deletedResources.contains(next.getTargetId().toUnqualifiedVersionless().getValue())) {
            iter.remove();
        }
    }
    validateDeleteConflictsEmptyOrThrowException(deleteConflicts);

    /*
     * Perform ID substitutions and then index each resource we have saved
     */

    FhirTerser terser = getContext().newTerser();
    for (DaoMethodOutcome nextOutcome : idToPersistedOutcome.values()) {
        IBaseResource nextResource = nextOutcome.getResource();
        if (nextResource == null) {
            continue;
        }

        List<IBaseReference> allRefs = terser.getAllPopulatedChildElementsOfType(nextResource,
                IBaseReference.class);
        for (IBaseReference nextRef : allRefs) {
            IIdType nextId = nextRef.getReferenceElement();
            if (!nextId.hasIdPart()) {
                continue;
            }
            if (idSubstitutions.containsKey(nextId)) {
                IdType newId = idSubstitutions.get(nextId);
                ourLog.info(" * Replacing resource ref {} with {}", nextId, newId);
                nextRef.setReference(newId.getValue());
            } else if (nextId.getValue().startsWith("urn:")) {
                throw new InvalidRequestException("Unable to satisfy placeholder ID: " + nextId.getValue());
            } else {
                ourLog.debug(" * Reference [{}] does not exist in bundle", nextId);
            }
        }

        IPrimitiveType<Date> deletedInstantOrNull = ResourceMetadataKeyEnum.DELETED_AT
                .get((IAnyResource) nextResource);
        Date deletedTimestampOrNull = deletedInstantOrNull != null ? deletedInstantOrNull.getValue() : null;
        boolean shouldUpdate = !nonUpdatedEntities.contains(nextOutcome.getEntity());
        updateEntity(nextResource, nextOutcome.getEntity(), deletedTimestampOrNull, shouldUpdate, shouldUpdate,
                updateTime);
    }

    myEntityManager.flush();

    /*
     * Double check we didn't allow any duplicates we shouldn't have
     */
    for (BundleEntryComponent nextEntry : theRequest.getEntry()) {
        if (nextEntry.getRequest().getMethodElement().getValue() == HTTPVerb.POST) {
            String matchUrl = nextEntry.getRequest().getIfNoneExist();
            if (isNotBlank(matchUrl)) {
                IFhirResourceDao<?> resourceDao = getDao(nextEntry.getResource().getClass());
                Set<Long> val = resourceDao.processMatchUrl(matchUrl);
                if (val.size() > 1) {
                    throw new InvalidRequestException("Unable to process " + theActionName
                            + " - Request would cause multiple resources to match URL: \"" + matchUrl
                            + "\". Does transaction request contain duplicates?");
                }
            }
        }
    }

    for (IdType next : allIds) {
        IdType replacement = idSubstitutions.get(next);
        if (replacement == null) {
            continue;
        }
        if (replacement.equals(next)) {
            continue;
        }
        ourLog.info("Placeholder resource ID \"{}\" was replaced with permanent ID \"{}\"", next, replacement);
    }

    /*
     * Loop through the request and process any entries of type GET
     */
    for (int i = 0; i < getEntries.size(); i++) {
        BundleEntryComponent nextReqEntry = getEntries.get(i);
        Integer originalOrder = originalRequestOrder.get(nextReqEntry);
        BundleEntryComponent nextRespEntry = response.getEntry().get(originalOrder);

        ServletSubRequestDetails requestDetails = new ServletSubRequestDetails();
        requestDetails.setServletRequest(theRequestDetails.getServletRequest());
        requestDetails.setRequestType(RequestTypeEnum.GET);
        requestDetails.setServer(theRequestDetails.getServer());

        String url = extractTransactionUrlOrThrowException(nextReqEntry, HTTPVerb.GET);

        int qIndex = url.indexOf('?');
        ArrayListMultimap<String, String> paramValues = ArrayListMultimap.create();
        requestDetails.setParameters(new HashMap<String, String[]>());
        if (qIndex != -1) {
            String params = url.substring(qIndex);
            List<NameValuePair> parameters = translateMatchUrl(params);
            for (NameValuePair next : parameters) {
                paramValues.put(next.getName(), next.getValue());
            }
            for (java.util.Map.Entry<String, Collection<String>> nextParamEntry : paramValues.asMap()
                    .entrySet()) {
                String[] nextValue = nextParamEntry.getValue()
                        .toArray(new String[nextParamEntry.getValue().size()]);
                requestDetails.getParameters().put(nextParamEntry.getKey(), nextValue);
            }
            url = url.substring(0, qIndex);
        }

        requestDetails.setRequestPath(url);
        requestDetails.setFhirServerBase(theRequestDetails.getFhirServerBase());

        theRequestDetails.getServer().populateRequestDetailsFromRequestPath(requestDetails, url);
        BaseMethodBinding<?> method = theRequestDetails.getServer().determineResourceMethod(requestDetails,
                url);
        if (method == null) {
            throw new IllegalArgumentException("Unable to handle GET " + url);
        }

        if (isNotBlank(nextReqEntry.getRequest().getIfMatch())) {
            requestDetails.addHeader(Constants.HEADER_IF_MATCH, nextReqEntry.getRequest().getIfMatch());
        }
        if (isNotBlank(nextReqEntry.getRequest().getIfNoneExist())) {
            requestDetails.addHeader(Constants.HEADER_IF_NONE_EXIST,
                    nextReqEntry.getRequest().getIfNoneExist());
        }
        if (isNotBlank(nextReqEntry.getRequest().getIfNoneMatch())) {
            requestDetails.addHeader(Constants.HEADER_IF_NONE_MATCH,
                    nextReqEntry.getRequest().getIfNoneMatch());
        }

        if (method instanceof BaseResourceReturningMethodBinding) {
            try {
                ResourceOrDstu1Bundle responseData = ((BaseResourceReturningMethodBinding) method)
                        .doInvokeServer(theRequestDetails.getServer(), requestDetails);
                IBaseResource resource = responseData.getResource();
                if (paramValues.containsKey(Constants.PARAM_SUMMARY)
                        || paramValues.containsKey(Constants.PARAM_CONTENT)) {
                    resource = filterNestedBundle(requestDetails, resource);
                }
                nextRespEntry.setResource((Resource) resource);
                nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_200_OK));
            } catch (NotModifiedException e) {
                nextRespEntry.getResponse().setStatus(toStatusString(Constants.STATUS_HTTP_304_NOT_MODIFIED));
            }
        } else {
            throw new IllegalArgumentException("Unable to handle GET " + url);
        }

    }

    for (Entry<BundleEntryComponent, ResourceTable> nextEntry : entriesToProcess.entrySet()) {
        nextEntry.getKey().getResponse().setLocation(nextEntry.getValue().getIdDt().toUnqualified().getValue());
        nextEntry.getKey().getResponse().setEtag(nextEntry.getValue().getIdDt().getVersionIdPart());
    }

    long delay = System.currentTimeMillis() - start;
    ourLog.info(theActionName + " completed in {}ms", new Object[] { delay });

    response.setType(BundleType.TRANSACTIONRESPONSE);
    return response;
}