Search in sources :

Example 66 with IdentityHashMap

use of java.util.IdentityHashMap in project vcell by virtualcell.

the class BioCartoonTool method pasteReactionSteps0.

/**
 * pasteReactionSteps0 : does the actual pasting. First called with a cloned model, to track issues. If user still wants to proceed, the paste
 * is performed on the original model.
 *
 * Insert the method's description here.
 * Creation date: (5/10/2003 3:55:25 PM)
 * @param pasteToModel cbit.vcell.model.Model
 * @param pasteToStructure cbit.vcell.model.Structure
 * @param bNew boolean
 */
private static final PasteHelper pasteReactionSteps0(HashMap<String, HashMap<ReactionParticipant, Structure>> rxPartMapStructure, Component parent, IssueContext issueContext, ReactionStep[] copyFromRxSteps, Model pasteToModel, Structure pasteToStructure, boolean bNew, /*boolean bUseDBSpecies,*/
UserResolvedRxElements userResolvedRxElements) throws Exception {
    HashMap<BioModelEntityObject, BioModelEntityObject> reactionsAndSpeciesContexts = new HashMap<>();
    if (copyFromRxSteps == null || copyFromRxSteps.length == 0 || pasteToModel == null || pasteToStructure == null) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps Error " + (copyFromRxSteps == null || copyFromRxSteps.length == 0 ? "reactionStepsArr empty " : "") + (pasteToModel == null ? "model is null " : "") + (pasteToStructure == null ? "struct is null " : ""));
    }
    if (!pasteToModel.contains(pasteToStructure)) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps model " + pasteToModel.getName() + " does not contain structure " + pasteToStructure.getName());
    }
    // Check PasteToModel has preferred targets if set
    if (userResolvedRxElements != null) {
        for (int i = 0; i < userResolvedRxElements.toSpeciesArr.length; i++) {
            if (userResolvedRxElements.toSpeciesArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toSpeciesArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Species " + userResolvedRxElements.toSpeciesArr[i]);
                }
            }
            if (userResolvedRxElements.toStructureArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toStructureArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Structure " + userResolvedRxElements.toStructureArr[i]);
                }
            }
        }
    }
    int counter = 0;
    Structure currentStruct = pasteToStructure;
    String copiedStructName = copyFromRxSteps[counter].getStructure().getName();
    StructureTopology structTopology = (copyFromRxSteps[counter].getModel() == null ? pasteToModel.getStructureTopology() : copyFromRxSteps[counter].getModel().getStructureTopology());
    IdentityHashMap<Species, Species> speciesHash = new IdentityHashMap<Species, Species>();
    IdentityHashMap<SpeciesContext, SpeciesContext> speciesContextHash = new IdentityHashMap<SpeciesContext, SpeciesContext>();
    Vector<Issue> issueVector = new Vector<Issue>();
    do {
        // create a new reaction, instead of cloning the old one; set struc
        ReactionStep copyFromReactionStep = copyFromRxSteps[counter];
        String newName = copyFromReactionStep.getName();
        while (pasteToModel.getReactionStep(newName) != null) {
            newName = org.vcell.util.TokenMangler.getNextEnumeratedToken(newName);
        }
        ReactionStep newReactionStep = null;
        if (copyFromReactionStep instanceof SimpleReaction) {
            newReactionStep = new SimpleReaction(pasteToModel, currentStruct, newName, copyFromReactionStep.isReversible());
        } else if (copyFromReactionStep instanceof FluxReaction && currentStruct instanceof Membrane) {
            newReactionStep = new FluxReaction(pasteToModel, (Membrane) currentStruct, null, newName, copyFromReactionStep.isReversible());
        }
        pasteToModel.addReactionStep(newReactionStep);
        reactionsAndSpeciesContexts.put(newReactionStep, copyFromReactionStep);
        Structure toRxnStruct = newReactionStep.getStructure();
        Structure fromRxnStruct = copyFromReactionStep.getStructure();
        if (!fromRxnStruct.getClass().equals(pasteToStructure.getClass())) {
            throw new Exception("Cannot copy reaction from " + fromRxnStruct.getTypeName() + " to " + pasteToStructure.getTypeName() + ".");
        }
        // add appropriate reactionParticipants to newReactionStep.
        StructureTopology toStructureTopology = pasteToModel.getStructureTopology();
        ReactionParticipant[] copyFromRxParticipantArr = copyFromReactionStep.getReactionParticipants();
        if (rxPartMapStructure == null) {
            // null during 'issues' trial
            rxPartMapStructure = new HashMap<String, HashMap<ReactionParticipant, Structure>>();
        }
        if (rxPartMapStructure.get(copyFromReactionStep.getName()) == null) {
            // Ask user to assign species to compartments for each reaction to be pasted
            rxPartMapStructure.put(copyFromReactionStep.getName(), askUserResolveMembraneConnections(parent, pasteToModel.getStructures(), currentStruct, fromRxnStruct, toRxnStruct, copyFromRxParticipantArr, toStructureTopology, structTopology));
        }
        for (int i = 0; i < copyFromRxParticipantArr.length; i += 1) {
            Structure pasteToStruct = currentStruct;
            // if(toRxnStruct instanceof Membrane){
            pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(copyFromRxParticipantArr[i]);
            // if(pasteToStruct == null){
            // for(ReactionParticipant myRXPart:rxPartMapStructure.get(copyFromReactionStep.getName()).keySet()){
            // if(myRXPart.getSpeciesContext().getName().equals(copyFromRxParticipantArr[i].getSpeciesContext().getName())){
            // pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(myRXPart);
            // break;
            // }
            // }
            // }
            // }
            // this adds the speciesContexts and species (if any) to the model)
            String rootSC = ReactionCartoonTool.speciesContextRootFinder(copyFromRxParticipantArr[i].getSpeciesContext());
            SpeciesContext newSc = null;
            SpeciesContext[] matchSC = pasteToModel.getSpeciesContexts();
            for (int j = 0; matchSC != null && j < matchSC.length; j++) {
                String matchRoot = ReactionCartoonTool.speciesContextRootFinder(matchSC[j]);
                if (matchRoot != null && matchRoot.equals(rootSC) && matchSC[j].getStructure().getName().equals(pasteToStruct.getName())) {
                    newSc = matchSC[j];
                    reactionsAndSpeciesContexts.put(newSc, matchSC[j]);
                    break;
                }
            }
            if (newSc == null) {
                newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(), rootSC, pasteToModel, pasteToStruct, bNew, /*bUseDBSpecies,*/
                speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, copyFromRxParticipantArr[i]));
                reactionsAndSpeciesContexts.put(newSc, copyFromRxParticipantArr[i].getSpeciesContext());
            }
            // record the old-new speciesContexts (reactionparticipants) in the IdHashMap, this is useful, esp for 'Paste new', while replacing proxyparams.
            SpeciesContext oldSc = copyFromRxParticipantArr[i].getSpeciesContext();
            if (speciesContextHash.get(oldSc) == null) {
                speciesContextHash.put(oldSc, newSc);
            }
            if (copyFromRxParticipantArr[i] instanceof Reactant) {
                newReactionStep.addReactionParticipant(new Reactant(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Product) {
                newReactionStep.addReactionParticipant(new Product(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Catalyst) {
                newReactionStep.addCatalyst(newSc);
            }
        }
        // // If 'newReactionStep' is a fluxRxn, set its fluxCarrier
        // if (newReactionStep instanceof FluxReaction) {
        // if (fluxCarrierSp != null) {
        // ((FluxReaction)newReactionStep).setFluxCarrier(fluxCarrierSp, pasteToModel);
        // } else {
        // throw new RuntimeException("Could not set FluxCarrier species for the flux reaction to be pasted");
        // }
        // }
        // For each kinetic parameter expression for new kinetics, replace the proxyParams from old kinetics with proxyParams in new kinetics
        // i.e., if the proxyParams are speciesContexts, replace with corresponding speciesContext in newReactionStep;
        // if the proxyParams are structureSizes or MembraneVoltages, replace with corresponding structure quantity in newReactionStep
        Kinetics oldKinetics = copyFromReactionStep.getKinetics();
        KineticsParameter[] oldKps = oldKinetics.getKineticsParameters();
        KineticsProxyParameter[] oldKprps = oldKinetics.getProxyParameters();
        Hashtable<String, Expression> paramExprHash = new Hashtable<String, Expression>();
        for (int i = 0; oldKps != null && i < oldKps.length; i++) {
            Expression newExpression = new Expression(oldKps[i].getExpression());
            for (int j = 0; oldKprps != null && j < oldKprps.length; j++) {
                // check if kinetic proxy parameter is in kinetic parameter expression
                if (newExpression.hasSymbol(oldKprps[j].getName())) {
                    SymbolTableEntry ste = oldKprps[j].getTarget();
                    Model pasteFromModel = copyFromReactionStep.getModel();
                    if (ste instanceof SpeciesContext) {
                        // if newRxnStruct is a feature/membrane, get matching spContexts from old reaction and replace them in new rate expr.
                        SpeciesContext oldSC = (SpeciesContext) ste;
                        SpeciesContext newSC = speciesContextHash.get(oldSC);
                        if (newSC == null) {
                            // check if oldSc is present in paste-model; if not, add it.
                            if (!pasteToModel.equals(pasteFromModel)) {
                                if (pasteToModel.getSpeciesContext(oldSC.getName()) == null) {
                                    // if paste-model has oldSc struct, paste it there,
                                    Structure newSCStruct = pasteToModel.getStructure(oldSC.getStructure().getName());
                                    if (newSCStruct != null) {
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, newSCStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                    } else {
                                        // oldStruct wasn't found in paste-model, paste it in newRxnStruct and add warning to issues list
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, toRxnStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                        Issue issue = new Issue(oldSC, issueContext, IssueCategory.CopyPaste, "SpeciesContext '" + oldSC.getSpecies().getCommonName() + "' was not found in compartment '" + oldSC.getStructure().getName() + "' in the model; the species was added to the compartment '" + toRxnStruct.getName() + "' where the reaction was pasted.", Issue.SEVERITY_WARNING);
                                        issueVector.add(issue);
                                    }
                                }
                            }
                        // if models are the same and newSc is null, then oldSc is not a rxnParticipant. Leave it as is in the expr.
                        }
                        if (newSC != null) {
                            reactionsAndSpeciesContexts.put(newSC, oldSC);
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(newSC.getName()));
                        }
                    // SpeciesContext sc = null;
                    // Species newSp = model.getSpecies(oldSc.getSpecies().getCommonName());
                    // if  (oldSc.getStructure() == (oldRxnStruct)) {
                    // sc = model.getSpeciesContext(newSp, newRxnStruct);
                    // } else {
                    // if (newRxnStruct instanceof Membrane) {
                    // // for a membrane, we need to make sure that inside-outside spContexts used are appropriately replaced.
                    // if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getOutsideFeature()) {
                    // // old speciesContext is outside (old) membrane, new spContext should be outside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getOutsideFeature());
                    // } else if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getInsideFeature()) {
                    // // old speciesContext is inside (old) membrane, new spContext should be inside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getInsideFeature());
                    // }
                    // }
                    // }
                    // if (sc != null) {
                    // newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(sc.getName()));
                    // }
                    } else if (ste instanceof StructureSize) {
                        Structure str = ((StructureSize) ste).getStructure();
                        // if the structure size used is same as the structure in which the reaction is present, change the structSize to appropriate new struct
                        if (str.compareEqual(fromRxnStruct)) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(toRxnStruct.getStructureSize().getName()));
                        } else {
                            if (fromRxnStruct instanceof Membrane) {
                                if (str.equals(structTopology.getOutsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getOutsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                } else if (str.equals(structTopology.getInsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getInsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                }
                            }
                        }
                    } else if (ste instanceof MembraneVoltage) {
                        Membrane membr = ((MembraneVoltage) ste).getMembrane();
                        // if the MembraneVoltage used is same as that of the membrane in which the reaction is present, change the MemVoltage
                        if ((fromRxnStruct instanceof Membrane) && (membr.compareEqual(fromRxnStruct))) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(((Membrane) toRxnStruct).getMembraneVoltage().getName()));
                        }
                    } else if (ste instanceof ModelParameter) {
                        // see if model has this global parameter (if rxn is being pasted into another model, it won't)
                        if (!pasteToModel.equals(pasteFromModel)) {
                            ModelParameter oldMp = (ModelParameter) ste;
                            ModelParameter mp = pasteToModel.getModelParameter(oldMp.getName());
                            boolean bNonNumeric = false;
                            String newMpName = oldMp.getName();
                            if (mp != null) {
                                // new model has a model parameter with same name - are they the same param?
                                if (!mp.getExpression().equals(oldMp.getExpression())) {
                                    // no, they are not the same param, so mangle the 'ste' name and add as global in the other model
                                    while (pasteToModel.getModelParameter(newMpName) != null) {
                                        newMpName = TokenMangler.getNextEnumeratedToken(newMpName);
                                    }
                                    // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                    Expression exp = oldMp.getExpression();
                                    if (!exp.flatten().isNumeric()) {
                                        exp = new Expression(0.0);
                                        bNonNumeric = true;
                                    }
                                    ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                    String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                    newMp.setModelParameterAnnotation(annotation);
                                    pasteToModel.addModelParameter(newMp);
                                    // if global param name had to be changed, make sure newExpr is updated as well.
                                    if (!newMpName.equals(oldMp.getName())) {
                                        newExpression.substituteInPlace(new Expression(oldMp.getName()), new Expression(newMpName));
                                    }
                                }
                            } else {
                                // no global param with same name was found in other model, so add it to other model.
                                // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                Expression exp = oldMp.getExpression();
                                if (!exp.flatten().isNumeric()) {
                                    exp = new Expression(0.0);
                                    bNonNumeric = true;
                                }
                                ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                newMp.setModelParameterAnnotation(annotation);
                                pasteToModel.addModelParameter(newMp);
                            }
                            // if a non-numeric parameter was encountered in the old model, it was added as a numeric (0.0), warn user of change.
                            if (bNonNumeric) {
                                Issue issue = new Issue(oldMp, issueContext, IssueCategory.CopyPaste, "Global parameter '" + oldMp.getName() + "' was non-numeric; it has been added " + "as global parameter '" + newMpName + "' in the new model with value = 0.0. " + "Please update its value, if required, before using it.", Issue.SEVERITY_WARNING);
                                issueVector.add(issue);
                            }
                        }
                    }
                }
            // end - if newExpr.hasSymbol(ProxyParam)
            }
            // now if store <param names, new expression> in hashTable
            if (paramExprHash.get(oldKps[i].getName()) == null) {
                paramExprHash.put(oldKps[i].getName(), newExpression);
            }
        }
        // end for - oldKps (old kinetic parameters)
        // use this new expression to generate 'vcml' for the (new) kinetics (easier way to transfer all kinetic parameters)
        String newKineticsStr = oldKinetics.writeTokensWithReplacingProxyParams(paramExprHash);
        // convert the kinetics 'vcml' to tokens.
        CommentStringTokenizer kineticsTokens = new CommentStringTokenizer(newKineticsStr);
        // skip the first token;
        kineticsTokens.nextToken();
        // second token is the kinetic type; use this to create a dummy kinetics
        String kineticType = kineticsTokens.nextToken();
        Kinetics newkinetics = KineticsDescription.fromVCMLKineticsName(kineticType).createKinetics(newReactionStep);
        // use the remaining tokens to construct the new kinetics
        newkinetics.fromTokens(newKineticsStr);
        // bind newkinetics to newReactionStep and add it to newReactionStep
        newkinetics.bind(newReactionStep);
        newReactionStep.setKinetics(newkinetics);
        counter += 1;
        if (counter == copyFromRxSteps.length) {
            break;
        }
        if (!copiedStructName.equals(fromRxnStruct.getName())) {
            if (currentStruct instanceof Feature) {
                currentStruct = structTopology.getMembrane((Feature) currentStruct);
            } else if (currentStruct instanceof Membrane) {
                currentStruct = structTopology.getInsideFeature((Membrane) currentStruct);
            }
        }
        copiedStructName = fromRxnStruct.getName();
    } while (true);
    return new PasteHelper(issueVector, rxPartMapStructure, reactionsAndSpeciesContexts);
}
Also used : Issue(org.vcell.util.Issue) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) Feature(cbit.vcell.model.Feature) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species) Vector(java.util.Vector) SimpleReaction(cbit.vcell.model.SimpleReaction) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) StructureTopology(cbit.vcell.model.Model.StructureTopology) Hashtable(java.util.Hashtable) BioModelEntityObject(cbit.vcell.model.BioModelEntityObject) StructureSize(cbit.vcell.model.Structure.StructureSize) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) UserCancelException(org.vcell.util.UserCancelException) ModelParameter(cbit.vcell.model.Model.ModelParameter) Expression(cbit.vcell.parser.Expression) MembraneVoltage(cbit.vcell.model.Membrane.MembraneVoltage) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) Kinetics(cbit.vcell.model.Kinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Example 67 with IdentityHashMap

use of java.util.IdentityHashMap in project dubbo by alibaba.

the class JavaBeanSerializeUtil method serializeInternal.

private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, JavaBeanAccessor accessor, IdentityHashMap<Object, JavaBeanDescriptor> cache) {
    if (obj == null || descriptor == null) {
        return;
    }
    if (obj.getClass().isEnum()) {
        descriptor.setEnumNameProperty(((Enum<?>) obj).name());
    } else if (ReflectUtils.isPrimitive(obj.getClass())) {
        descriptor.setPrimitiveProperty(obj);
    } else if (Class.class.equals(obj.getClass())) {
        descriptor.setClassNameProperty(((Class<?>) obj).getName());
    } else if (obj.getClass().isArray()) {
        int len = Array.getLength(obj);
        for (int i = 0; i < len; i++) {
            Object item = Array.get(obj, i);
            if (item == null) {
                descriptor.setProperty(i, null);
            } else {
                JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache);
                descriptor.setProperty(i, itemDescriptor);
            }
        }
    } else if (obj instanceof Collection) {
        Collection collection = (Collection) obj;
        int index = 0;
        for (Object item : collection) {
            if (item == null) {
                descriptor.setProperty(index++, null);
            } else {
                JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache);
                descriptor.setProperty(index++, itemDescriptor);
            }
        }
    } else if (obj instanceof Map) {
        Map map = (Map) obj;
        for (Object key : map.keySet()) {
            Object value = map.get(key);
            Object keyDescriptor = key == null ? null : createDescriptorIfAbsent(key, accessor, cache);
            Object valueDescriptor = value == null ? null : createDescriptorIfAbsent(value, accessor, cache);
            descriptor.setProperty(keyDescriptor, valueDescriptor);
        }
    // ~ end of loop map
    } else {
        if (JavaBeanAccessor.isAccessByMethod(accessor)) {
            Map<String, Method> methods = ReflectUtils.getBeanPropertyReadMethods(obj.getClass());
            for (Map.Entry<String, Method> entry : methods.entrySet()) {
                try {
                    Object value = entry.getValue().invoke(obj);
                    if (value == null) {
                        continue;
                    }
                    JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache);
                    descriptor.setProperty(entry.getKey(), valueDescriptor);
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        // ~ end of loop method map
        }
        if (JavaBeanAccessor.isAccessByField(accessor)) {
            Map<String, Field> fields = ReflectUtils.getBeanPropertyFields(obj.getClass());
            for (Map.Entry<String, Field> entry : fields.entrySet()) {
                if (!descriptor.containsProperty(entry.getKey())) {
                    try {
                        Object value = entry.getValue().get(obj);
                        if (value == null) {
                            continue;
                        }
                        JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache);
                        descriptor.setProperty(entry.getKey(), valueDescriptor);
                    } catch (Exception e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        // ~ end of loop field map
        }
    // ~ end of if (JavaBeanAccessor.isAccessByField(accessor))
    }
// ~ end of else
}
Also used : Collection(java.util.Collection) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) Map(java.util.Map) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 68 with IdentityHashMap

use of java.util.IdentityHashMap in project elasticsearch by elastic.

the class ClusterService method submitStateUpdateTasks.

/**
     * Submits a batch of cluster state update tasks; submitted updates are guaranteed to be processed together,
     * potentially with more tasks of the same executor.
     *
     * @param source   the source of the cluster state update task
     * @param tasks    a map of update tasks and their corresponding listeners
     * @param config   the cluster state update task configuration
     * @param executor the cluster state update task executor; tasks
     *                 that share the same executor will be executed
     *                 batches on this executor
     * @param <T>      the type of the cluster state update task state
     *
     */
public <T> void submitStateUpdateTasks(final String source, final Map<T, ClusterStateTaskListener> tasks, final ClusterStateTaskConfig config, final ClusterStateTaskExecutor<T> executor) {
    if (!lifecycle.started()) {
        return;
    }
    if (tasks.isEmpty()) {
        return;
    }
    try {
        @SuppressWarnings("unchecked") ClusterStateTaskExecutor<Object> taskExecutor = (ClusterStateTaskExecutor<Object>) executor;
        // convert to an identity map to check for dups based on update tasks semantics of using identity instead of equal
        final IdentityHashMap<Object, ClusterStateTaskListener> tasksIdentity = new IdentityHashMap<>(tasks);
        final List<UpdateTask> updateTasks = tasksIdentity.entrySet().stream().map(entry -> new UpdateTask(source, entry.getKey(), config.priority(), taskExecutor, safe(entry.getValue(), logger))).collect(Collectors.toList());
        synchronized (updateTasksPerExecutor) {
            LinkedHashSet<UpdateTask> existingTasks = updateTasksPerExecutor.computeIfAbsent(executor, k -> new LinkedHashSet<>(updateTasks.size()));
            for (UpdateTask existing : existingTasks) {
                if (tasksIdentity.containsKey(existing.task)) {
                    throw new IllegalStateException("task [" + taskExecutor.describeTasks(Collections.singletonList(existing.task)) + "] with source [" + source + "] is already queued");
                }
            }
            existingTasks.addAll(updateTasks);
        }
        final UpdateTask firstTask = updateTasks.get(0);
        final TimeValue timeout = config.timeout();
        if (timeout != null) {
            threadPoolExecutor.execute(firstTask, threadPool.scheduler(), timeout, () -> onTimeout(updateTasks, source, timeout));
        } else {
            threadPoolExecutor.execute(firstTask);
        }
    } catch (EsRejectedExecutionException e) {
        // to be done here...
        if (!lifecycle.stoppedOrClosed()) {
            throw e;
        }
    }
}
Also used : MetaData(org.elasticsearch.cluster.metadata.MetaData) ScheduledFuture(java.util.concurrent.ScheduledFuture) Nullable(org.elasticsearch.common.Nullable) Property(org.elasticsearch.common.settings.Setting.Property) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) UnaryOperator(java.util.function.UnaryOperator) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ClusterStateListener(org.elasticsearch.cluster.ClusterStateListener) ClusterTasksResult(org.elasticsearch.cluster.ClusterStateTaskExecutor.ClusterTasksResult) ClusterState(org.elasticsearch.cluster.ClusterState) Future(java.util.concurrent.Future) Settings(org.elasticsearch.common.settings.Settings) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) Locale(java.util.Locale) Map(java.util.Map) CountDown(org.elasticsearch.common.util.concurrent.CountDown) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) Priority(org.elasticsearch.common.Priority) IdentityHashMap(java.util.IdentityHashMap) Setting(org.elasticsearch.common.settings.Setting) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) PrioritizedEsThreadPoolExecutor(org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor) Supplier(org.apache.logging.log4j.util.Supplier) Queue(java.util.Queue) EsExecutors.daemonThreadFactory(org.elasticsearch.common.util.concurrent.EsExecutors.daemonThreadFactory) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) PrioritizedRunnable(org.elasticsearch.common.util.concurrent.PrioritizedRunnable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProcessClusterEventTimeoutException(org.elasticsearch.cluster.metadata.ProcessClusterEventTimeoutException) ArrayList(java.util.ArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ClusterStateTaskListener(org.elasticsearch.cluster.ClusterStateTaskListener) Text(org.elasticsearch.common.text.Text) TimeValue(org.elasticsearch.common.unit.TimeValue) Iterables(org.elasticsearch.common.util.iterable.Iterables) BiConsumer(java.util.function.BiConsumer) ClusterStateApplier(org.elasticsearch.cluster.ClusterStateApplier) LinkedHashSet(java.util.LinkedHashSet) TimeoutClusterStateListener(org.elasticsearch.cluster.TimeoutClusterStateListener) Loggers(org.elasticsearch.common.logging.Loggers) Builder(org.elasticsearch.cluster.ClusterState.Builder) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) OperationRouting(org.elasticsearch.cluster.routing.OperationRouting) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) FutureUtils(org.elasticsearch.common.util.concurrent.FutureUtils) Iterator(java.util.Iterator) Executor(java.util.concurrent.Executor) Discovery(org.elasticsearch.discovery.Discovery) DiscoverySettings(org.elasticsearch.discovery.DiscoverySettings) ClusterStateTaskConfig(org.elasticsearch.cluster.ClusterStateTaskConfig) ClusterStateTaskExecutor(org.elasticsearch.cluster.ClusterStateTaskExecutor) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) TimeUnit(java.util.concurrent.TimeUnit) LocalNodeMasterListener(org.elasticsearch.cluster.LocalNodeMasterListener) NodeConnectionsService(org.elasticsearch.cluster.NodeConnectionsService) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) AckedClusterStateTaskListener(org.elasticsearch.cluster.AckedClusterStateTaskListener) Collections(java.util.Collections) IdentityHashMap(java.util.IdentityHashMap) ClusterStateTaskExecutor(org.elasticsearch.cluster.ClusterStateTaskExecutor) TimeValue(org.elasticsearch.common.unit.TimeValue) ClusterStateTaskListener(org.elasticsearch.cluster.ClusterStateTaskListener) AckedClusterStateTaskListener(org.elasticsearch.cluster.AckedClusterStateTaskListener) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException)

Example 69 with IdentityHashMap

use of java.util.IdentityHashMap in project jersey by jersey.

the class ApplicationHandler method bindProvidersAndResources.

private void bindProvidersAndResources(final Iterable<ComponentProvider> componentProviders, final ComponentBag componentBag, final Collection<Class<?>> resourceClasses, final Collection<Object> resourceInstances) {
    JerseyResourceContext resourceContext = injectionManager.getInstance(JerseyResourceContext.class);
    Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();
    /*
         * Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    java.util.function.Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), RuntimeType.SERVER, !registeredClasses.contains(componentClass), resourceClasses.contains(componentClass));
    /*
         * Check the {@code resource class} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    BiPredicate<Class<?>, ContractProvider> correctlyConfiguredResource = (resourceClass, model) -> Providers.checkProviderRuntime(resourceClass, model, RuntimeType.SERVER, !registeredClasses.contains(resourceClass), true);
    Set<Class<?>> componentClassses = componentBag.getClasses(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(correctlyConfigured).collect(Collectors.toSet());
    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Collections.newSetFromMap(new IdentityHashMap<>());
    classes.addAll(componentClassses);
    classes.addAll(resourceClasses);
    // Bind classes.
    for (final Class<?> componentClass : classes) {
        ContractProvider model = componentBag.getModel(componentClass);
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
            continue;
        }
        if (resourceClasses.contains(componentClass)) {
            if (!Resource.isAcceptable(componentClass)) {
                LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
                continue;
            }
            if (model != null && !correctlyConfiguredResource.test(componentClass, model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(componentClass, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(componentClass, model, injectionManager);
        }
    }
    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(instance -> correctlyConfigured.test(instance.getClass())).collect(Collectors.toSet());
    instances.addAll(resourceInstances);
    // Bind instances.
    for (Object component : instances) {
        ContractProvider model = componentBag.getModel(component.getClass());
        if (resourceInstances.contains(component)) {
            if (model != null && !correctlyConfiguredResource.test(component.getClass(), model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(component, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(component, model, injectionManager);
        }
    }
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) RankedComparator(org.glassfish.jersey.model.internal.RankedComparator) SecurityContext(javax.ws.rs.core.SecurityContext) Errors(org.glassfish.jersey.internal.Errors) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ModelProcessor(org.glassfish.jersey.server.model.ModelProcessor) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) Application(javax.ws.rs.core.Application) JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ContainerLifecycleListener(org.glassfish.jersey.server.spi.ContainerLifecycleListener) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) RankedProvider(org.glassfish.jersey.model.internal.RankedProvider) JerseyRequestTimeoutHandler(org.glassfish.jersey.server.internal.JerseyRequestTimeoutHandler) ExecutorProviders(org.glassfish.jersey.process.internal.ExecutorProviders) Stages(org.glassfish.jersey.process.internal.Stages) Future(java.util.concurrent.Future) Ref(org.glassfish.jersey.internal.util.collection.Ref) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Map(java.util.Map) ProviderBinder(org.glassfish.jersey.internal.inject.ProviderBinder) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ModelErrors(org.glassfish.jersey.server.model.internal.ModelErrors) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Values(org.glassfish.jersey.internal.util.collection.Values) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) LocalizationMessages(org.glassfish.jersey.server.internal.LocalizationMessages) IdentityHashMap(java.util.IdentityHashMap) RuntimeType(javax.ws.rs.RuntimeType) Collection(java.util.Collection) Version(org.glassfish.jersey.internal.Version) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) Container(org.glassfish.jersey.server.spi.Container) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) Providers(org.glassfish.jersey.internal.inject.Providers) Logger(java.util.logging.Logger) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) Collectors(java.util.stream.Collectors) ChainableStage(org.glassfish.jersey.process.internal.ChainableStage) PreMatching(javax.ws.rs.container.PreMatching) GenericType(javax.ws.rs.core.GenericType) DynamicFeature(javax.ws.rs.container.DynamicFeature) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Spliterator(java.util.Spliterator) Resource(org.glassfish.jersey.server.model.Resource) CommonProperties(org.glassfish.jersey.CommonProperties) Configuration(javax.ws.rs.core.Configuration) Order(org.glassfish.jersey.model.internal.RankedComparator.Order) CompletableFuture(java.util.concurrent.CompletableFuture) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Singleton(javax.inject.Singleton) Binder(org.glassfish.jersey.internal.inject.Binder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) BiPredicate(java.util.function.BiPredicate) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) Value(org.glassfish.jersey.internal.util.collection.Value) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) Routing(org.glassfish.jersey.server.internal.routing.Routing) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LazyValue(org.glassfish.jersey.internal.util.collection.LazyValue) StreamSupport(java.util.stream.StreamSupport) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Injections(org.glassfish.jersey.internal.inject.Injections) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) Iterator(java.util.Iterator) ServiceConfigurationError(org.glassfish.jersey.internal.ServiceConfigurationError) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ReflectionHelper(org.glassfish.jersey.internal.util.ReflectionHelper) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) NameBinding(javax.ws.rs.NameBinding) CompositeBinder(org.glassfish.jersey.internal.inject.CompositeBinder) Stage(org.glassfish.jersey.process.internal.Stage) ServiceFinder(org.glassfish.jersey.internal.ServiceFinder) NullOutputStream(org.glassfish.jersey.message.internal.NullOutputStream) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) ContractProvider(org.glassfish.jersey.model.ContractProvider)

Example 70 with IdentityHashMap

use of java.util.IdentityHashMap in project jersey by jersey.

the class CommonConfigTest method testProviderOrderDifForContracts.

@Test
@SuppressWarnings("unchecked")
public void testProviderOrderDifForContracts() throws Exception {
    final Map<Class<?>, Integer> contracts = new IdentityHashMap<Class<?>, Integer>();
    contracts.put(WriterInterceptor.class, ContractProvider.NO_PRIORITY);
    contracts.put(ReaderInterceptor.class, 2000);
    config.register(MidPriorityProvider.class, contracts);
    contracts.clear();
    contracts.put(WriterInterceptor.class, ContractProvider.NO_PRIORITY);
    contracts.put(ReaderInterceptor.class, 1000);
    config.register(LowPriorityProvider.class, contracts);
    contracts.clear();
    contracts.put(WriterInterceptor.class, ContractProvider.NO_PRIORITY);
    contracts.put(ReaderInterceptor.class, 3000);
    config.register(HighPriorityProvider.class, contracts);
    contracts.clear();
    final InjectionManager injectionManager = Injections.createInjectionManager();
    ProviderBinder.bindProviders(config.getComponentBag(), injectionManager);
    final Iterable<WriterInterceptor> writerInterceptors = Providers.getAllProviders(injectionManager, WriterInterceptor.class, new RankedComparator<WriterInterceptor>());
    final Iterator<WriterInterceptor> writerIterator = writerInterceptors.iterator();
    assertEquals(HighPriorityProvider.class, writerIterator.next().getClass());
    assertEquals(MidPriorityProvider.class, writerIterator.next().getClass());
    assertEquals(LowPriorityProvider.class, writerIterator.next().getClass());
    assertFalse(writerIterator.hasNext());
    final Iterable<ReaderInterceptor> readerInterceptors = Providers.getAllProviders(injectionManager, ReaderInterceptor.class, new RankedComparator<ReaderInterceptor>());
    final Iterator<ReaderInterceptor> readerIterator = readerInterceptors.iterator();
    assertEquals(LowPriorityProvider.class, readerIterator.next().getClass());
    assertEquals(MidPriorityProvider.class, readerIterator.next().getClass());
    assertEquals(HighPriorityProvider.class, readerIterator.next().getClass());
    assertFalse(readerIterator.hasNext());
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) IdentityHashMap(java.util.IdentityHashMap) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) Test(org.junit.Test)

Aggregations

IdentityHashMap (java.util.IdentityHashMap)142 Map (java.util.Map)44 HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)31 HashSet (java.util.HashSet)20 LinkedHashMap (java.util.LinkedHashMap)18 Collection (java.util.Collection)16 Set (java.util.Set)16 TreeMap (java.util.TreeMap)16 Iterator (java.util.Iterator)14 AbstractMap (java.util.AbstractMap)13 List (java.util.List)11 Test (org.junit.Test)11 DependencyNode (org.sonatype.aether.graph.DependencyNode)10 WeakHashMap (java.util.WeakHashMap)8 LinkedList (java.util.LinkedList)7 TreeSet (java.util.TreeSet)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)7 Tree (edu.stanford.nlp.trees.Tree)6 IOException (java.io.IOException)6