Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

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

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:GestoSAT.GestoSAT.java

public Map recuperarFactura(int idAlbaran) {
    try {/*from  w  w  w .  ja  v  a  2 s .  c om*/
        Map mapFactura = new HashMap();
        // Torna un map de la facuta actual
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery(
                "SELECT f.*, a.id_Cliente id_Cliente,GROUP_CONCAT(concat(IF(e.id_entrada is null,'',e.id_entrada),';',id_Albaran)) EntradaAlbaran"
                        + " FROM (((albaranes a INNER JOIN facturas f ON a.id_factura = f.id_factura) LEFT JOIN presupuestos p ON a.id_Presupuesto=p.id_Presupuesto)"
                        + " LEFT JOIN entradas e ON e.id_entrada=p.id_entrada) WHERE a.id_Factura=(SELECT id_Factura FROM albaranes"
                        + " WHERE id_Albaran=" + idAlbaran
                        + ") AND a.id_Factura IS NOT NULL GROUP BY a.id_Factura");
        Factura factura;
        String[] vecEntradasAlbaranes;
        if (res.next()) {
            vecEntradasAlbaranes = res.getString("EntradaAlbaran").split(",");
            factura = new Factura(res.getString("f.concepto"), res.getString("f.forma_pago"),
                    res.getString("f.observaciones"), res.getTimestamp("f.fch_creacion"),
                    this.getCliente(res.getInt("id_Cliente")), this);
            if (this.documento.putIfAbsent(res.getInt("f.id_Factura") + ";Factura", factura) == null) {
                mapFactura.putIfAbsent(res.getInt("f.id_Factura") + ";Factura", factura);
                ((Cliente) this.cliente.get(res.getInt("id_Cliente"))).setFactura(res.getInt("f.id_Factura"),
                        factura);

                ((Albaran) this.documento.get(idAlbaran + ";Albaran")).setFactura(factura);
                factura.setAlbaran(idAlbaran, (Albaran) this.documento.get(idAlbaran + ";Albaran"));
                Map auxMap;
                for (int i = 0; i < vecEntradasAlbaranes.length; i++) {
                    if (vecEntradasAlbaranes[i].split(";")[0].isEmpty()) {
                        auxMap = this.recuperarVenta(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[1]));
                        ((Albaran) auxMap.get(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[1])))
                                .setFactura(factura);
                        factura.setAlbaran(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[1]),
                                (Albaran) auxMap.get(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[1])));
                    } else {
                        Entrada entrada = this
                                .getEntrada(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[0]));
                        entrada.cargarPresupuesto(Integer.parseInt(vecEntradasAlbaranes[i].split(";")[0]));
                    }
                }
            } else {
                factura = (Factura) this.documento.get(res.getInt("f.id_Factura") + ";Factura");
                factura.actualizar(res.getString("f.concepto"), res.getString("f.forma_pago"),
                        res.getString("f.observaciones"));
                factura.setAlbaran(idAlbaran, (Albaran) this.documento.get(idAlbaran + ";Albaran"));
                mapFactura.putIfAbsent(res.getInt("f.id_Factura") + ";Factura", factura);
            }
            ((Cliente) this.cliente.get(res.getInt("id_Cliente"))).setFactura(res.getInt("f.id_Factura"),
                    factura);
            st.close();
        }
        return mapFactura;
    } catch (SQLException ex) {
        Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex);
        return new HashMap();
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Reader.java

/**
 * Importing span annotations including slot annotations
 * //from w ww.  j  a va  2  s. c  o  m
 * @param aJCas
 * @param aAnnosPerTypePerUnit
 */

private void addAnnotations(JCas aJCas,
        Map<Type, Map<AnnotationUnit, List<AnnotationFS>>> aAnnosPerTypePerUnit) {

    for (Type type : annotationsPerPostion.keySet()) {
        Map<AnnotationUnit, Map<Integer, AnnotationFS>> multiTokUnits = new HashMap<>();
        int ref = 1;
        for (AnnotationUnit unit : annotationsPerPostion.get(type).keySet()) {
            int end = unit.end;
            List<AnnotationFS> annos = aAnnosPerTypePerUnit.get(type).get(unit);
            int j = 0;
            Feature linkeF = null;
            Map<AnnotationFS, List<FeatureStructure>> linkFSesPerSlotAnno = new HashMap<>();

            if (allLayers.get(type).size() == 0) {
                ref = addAnnotationWithNoFeature(aJCas, type, unit, annos, multiTokUnits, end, ref);
                continue;
            }

            for (Feature feat : allLayers.get(type)) {
                String anno = annotationsPerPostion.get(type).get(unit).get(j);
                if (!anno.equals("_")) {
                    int i = 0;
                    // if it is a slot annotation (multiple slots per
                    // single annotation
                    // (Target1<--role1--Base--role2-->Target2)
                    int slot = 0;
                    boolean targetAdd = false;
                    String stackedAnnoRegex = "(?<!\\\\)" + Pattern.quote("|");
                    for (String mAnnos : anno.split(stackedAnnoRegex)) {
                        String multipleSlotAnno = "(?<!\\\\)" + Pattern.quote(";");
                        for (String mAnno : mAnnos.split(multipleSlotAnno)) {
                            String depRef = "";
                            String multSpliter = "(?<!\\\\)" + Pattern.quote("[");
                            // is this slot target ambiguous?
                            boolean ambigTarget = false;
                            if (mAnno.split(multSpliter).length > 1) {
                                ambigTarget = true;
                                depRef = mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1);
                                ref = depRef.contains("_") ? ref
                                        : Integer.valueOf(
                                                mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1));
                                mAnno = mAnno.substring(0, mAnno.indexOf("["));
                            }
                            if (mAnno.equals("*")) {
                                mAnno = null;
                            }
                            boolean isMultitoken = false;
                            AnnotationFS multiAnnoFs = null;

                            if (!multiTokUnits.isEmpty())
                                for (AnnotationUnit u : multiTokUnits.keySet()) {
                                    for (Integer r : multiTokUnits.get(u).keySet()) {
                                        if (ref == r) {
                                            isMultitoken = true;
                                            multiAnnoFs = multiTokUnits.get(u).get(r);
                                            break;
                                        }
                                    }
                                }
                            if (isMultitoken) {
                                Feature endF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                                multiAnnoFs.setIntValue(endF, end);
                                mAnno = getEscapeChars(mAnno);
                                multiAnnoFs.setFeatureValueFromString(feat, mAnno);
                                if (feat.getShortName().equals(REF_LINK)) {
                                    // since REF_REL do not start with BIO,
                                    // update it it...
                                    annos.set(i, multiAnnoFs);
                                }
                                setAnnoRefPerUnit(unit, type, ref, multiAnnoFs);

                            } else {
                                if (roleLinks.containsKey(feat)) {
                                    linkeF = feat;
                                    FeatureStructure link = aJCas.getCas().createFS(slotLinkTypes.get(feat));
                                    Feature roleFeat = link.getType().getFeatureByBaseName("role");

                                    mAnno = getEscapeChars(mAnno);

                                    link.setStringValue(roleFeat, mAnno);
                                    linkFSesPerSlotAnno.putIfAbsent(annos.get(i), new ArrayList<>());
                                    linkFSesPerSlotAnno.get(annos.get(i)).add(link);

                                } else if (roleTargets.containsKey(feat)) {

                                    FeatureStructure link = linkFSesPerSlotAnno.get(annos.get(i)).get(slot);
                                    int customTypeNumber = 0;
                                    if (mAnno.split("-").length > 2) {
                                        customTypeNumber = Integer
                                                .valueOf(mAnno.substring(mAnno.lastIndexOf("-") + 1));
                                        mAnno = mAnno.substring(0, mAnno.lastIndexOf("-"));
                                    }

                                    AnnotationUnit targetUnit = token2Units.get(mAnno);
                                    Type tType = null;
                                    if (customTypeNumber == 0) {
                                        tType = roleTargets.get(feat);
                                    } else {
                                        tType = layerMaps.get(customTypeNumber);
                                    }
                                    AnnotationFS targetFs;

                                    if (ambigTarget) {
                                        targetFs = annosPerRef.get(tType).get(targetUnit).get(ref);
                                    } else {
                                        targetFs = annosPerRef.get(tType).get(targetUnit).entrySet().iterator()
                                                .next().getValue();
                                    }

                                    link.setFeatureValue(feat, targetFs);
                                    addSlotAnnotations(linkFSesPerSlotAnno, linkeF);
                                    targetAdd = true;
                                    slot++;

                                } else if (feat.getShortName().equals(REF_REL)) {

                                    int chainNo = Integer.valueOf(mAnno.split("->")[1].split("-")[0]);
                                    int LinkNo = Integer.valueOf(mAnno.split("->")[1].split("-")[1]);
                                    chainAnnosPerTyep.putIfAbsent(type, new TreeMap<>());
                                    if (chainAnnosPerTyep.get(type).get(chainNo) != null
                                            && chainAnnosPerTyep.get(type).get(chainNo).get(LinkNo) != null) {
                                        continue;
                                    }
                                    String refRel = mAnno.split("->")[0];

                                    refRel = getEscapeChars(refRel);
                                    if (refRel.equals("*")) {
                                        refRel = null;
                                    }

                                    annos.get(i).setFeatureValueFromString(feat, refRel);
                                    chainAnnosPerTyep.putIfAbsent(type, new TreeMap<>());
                                    chainAnnosPerTyep.get(type).putIfAbsent(chainNo, new TreeMap<>());
                                    chainAnnosPerTyep.get(type).get(chainNo).put(LinkNo, annos.get(i));

                                } else if (feat.getShortName().equals(REF_LINK)) {

                                    mAnno = getEscapeChars(mAnno);

                                    annos.get(i).setFeatureValueFromString(feat, mAnno);
                                    aJCas.addFsToIndexes(annos.get(i));

                                }

                                else if (depFeatures.get(type) != null && depFeatures.get(type).equals(feat)) {

                                    int g = depRef.isEmpty() ? 0 : Integer.valueOf(depRef.split("_")[0]);
                                    int d = depRef.isEmpty() ? 0 : Integer.valueOf(depRef.split("_")[1]);
                                    Type depType = depTypess.get(type);
                                    AnnotationUnit govUnit = token2Units.get(mAnno);
                                    int l = annotationsPerPostion.get(type).get(unit).size();
                                    String thisUnit = annotationsPerPostion.get(type).get(unit).get(l - 1);
                                    AnnotationUnit depUnit = token2Units.get(thisUnit);
                                    AnnotationFS govFs;
                                    AnnotationFS depFs;

                                    if (depType.getName().equals(POS.class.getName())) {
                                        depType = aJCas.getCas().getTypeSystem().getType(Token.class.getName());
                                        govFs = units2Tokens.get(govUnit);
                                        depFs = units2Tokens.get(unit);

                                    }
                                    // to pass the test case, which have relation on Token which not the case
                                    // in WebAnno world :)(!
                                    else if (depType.getName().equals(Token.class.getName())) {
                                        govFs = units2Tokens.get(govUnit);
                                        depFs = units2Tokens.get(unit);
                                    } else if (g == 0 && d == 0) {
                                        govFs = annosPerRef.get(depType).get(govUnit).entrySet().iterator()
                                                .next().getValue();
                                        depFs = annosPerRef.get(depType).get(depUnit).entrySet().iterator()
                                                .next().getValue();
                                    } else if (g == 0) {
                                        govFs = annosPerRef.get(depType).get(govUnit).entrySet().iterator()
                                                .next().getValue();
                                        depFs = annosPerRef.get(depType).get(depUnit).get(d);
                                    } else {
                                        govFs = annosPerRef.get(depType).get(govUnit).get(g);
                                        depFs = annosPerRef.get(depType).get(depUnit).entrySet().iterator()
                                                .next().getValue();
                                    }

                                    annos.get(i).setFeatureValue(feat, depFs);
                                    annos.get(i).setFeatureValue(type.getFeatureByBaseName(GOVERNOR), govFs);
                                    if (depFs.getBegin() <= annos.get(i).getBegin()) {
                                        Feature beginF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_BEGIN);
                                        annos.get(i).setIntValue(beginF, depFs.getBegin());
                                    } else {
                                        Feature endF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                                        annos.get(i).setIntValue(endF, depFs.getEnd());
                                    }
                                    aJCas.addFsToIndexes(annos.get(i));

                                } else {
                                    mAnno = getEscapeChars(mAnno);
                                    multiTokUnits.putIfAbsent(unit, new HashMap<>());
                                    multiTokUnits.get(unit).put(ref, annos.get(i));
                                    annos.get(i).setFeatureValueFromString(feat, mAnno);
                                    aJCas.addFsToIndexes(annos.get(i));
                                    setAnnoRefPerUnit(unit, type, ref, annos.get(i));
                                }

                            }
                            ref++;
                        }
                        if (type.getName().equals(POS.class.getName())) {
                            units2Tokens.get(unit).setPos((POS) annos.get(i));
                        }
                        if (type.getName().equals(Lemma.class.getName())) {
                            units2Tokens.get(unit).setLemma((Lemma) annos.get(i));
                        }
                        i++;
                    }

                    if (targetAdd) {
                        linkFSesPerSlotAnno = new HashMap<>();
                    }
                }
                j++;
            }
        }
        annosPerRef.put(type, multiTokUnits);
    }

}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Writer.java

private void setSpanAnnoPerFeature(Map<AnnotationUnit, List<List<String>>> aAnnotationsPertype, Type aType,
        AnnotationFS aFs, AnnotationUnit aUnit, boolean aIsMultiToken, boolean aIsFirst) {
    List<String> annoPerFeatures = new ArrayList<>();
    featurePerLayer.putIfAbsent(aType.getName(), new LinkedHashSet<>());
    int ref = getRefId(aType, aFs, aUnit);

    if (ambigUnits.get(aType.getName()).get(getFirstUnit(aUnit)).equals(false)) {
        ref = 0;/*from   w w w.jav  a 2s.c om*/
    }
    for (Feature feature : aType.getFeatures()) {
        if (feature.toString().equals("uima.cas.AnnotationBase:sofa")
                || feature.toString().equals("uima.tcas.Annotation:begin")
                || feature.toString().equals("uima.tcas.Annotation:end")
                || feature.getShortName().equals(GOVERNOR) || feature.getShortName().equals(DEPENDENT)
                || feature.getShortName().equals(FIRST) || feature.getShortName().equals(NEXT)) {
            continue;
        }

        // if slot feature
        if (slotFeatures != null && slotFeatures.contains(feature.getName())) {
            if (aFs.getFeatureValue(feature) != null) {
                ArrayFS array = (ArrayFS) aFs.getFeatureValue(feature);
                StringBuffer sbRole = new StringBuffer();
                StringBuffer sbTarget = new StringBuffer();
                for (FeatureStructure linkFS : array.toArray()) {
                    String role = linkFS.getStringValue(linkFS.getType().getFeatureByBaseName("role"));
                    AnnotationFS targetFs = (AnnotationFS) linkFS
                            .getFeatureValue(linkFS.getType().getFeatureByBaseName("target"));
                    Type tType = targetFs.getType();

                    AnnotationUnit firstUnit = getFirstUnit(targetFs);
                    ref = getRefId(tType, targetFs, firstUnit);
                    // Check if the target is ambiguous or not
                    if (ambigUnits.get(tType.getName()).get(firstUnit).equals(false)) {
                        ref = 0;
                    }
                    if (role == null) {
                        role = "*";
                    } else {
                        // Escape special character
                        role = replaceEscapeChars(role);
                    }
                    if (sbRole.length() < 1) {
                        sbRole.append(role);
                        // record the actual target type column number if slot target is
                        // uima.tcas.Annotation
                        int targetTypeNumber = 0;
                        if (slotFeatureTypes.get(feature).getName().equals(CAS.TYPE_NAME_ANNOTATION)) {
                            targetTypeNumber = layerMaps.get(tType);
                        }
                        sbTarget.append(unitsLineNumber.get(firstUnit)
                                + (targetTypeNumber == 0 ? "" : "-" + targetTypeNumber)
                                + (ref > 0 ? "[" + ref + "]" : ""));
                    } else {
                        sbRole.append(";");
                        sbTarget.append(";");
                        sbRole.append(role);
                        int targetTypeNumber = 0;
                        if (slotFeatureTypes.get(feature).getName().equals(CAS.TYPE_NAME_ANNOTATION)) {
                            targetTypeNumber = layerMaps.get(tType);
                        }
                        sbTarget.append(unitsLineNumber.get(firstUnit)
                                + (targetTypeNumber == 0 ? "" : "-" + targetTypeNumber)
                                + (ref > 0 ? "[" + ref + "]" : ""));
                    }
                }
                annoPerFeatures.add(sbRole.toString().isEmpty() ? "_" : sbRole.toString());
                annoPerFeatures.add(sbTarget.toString().isEmpty() ? "_" : sbTarget.toString());
            } else {
                // setting it to null
                annoPerFeatures.add("_");
                annoPerFeatures.add("_");
            }
            featurePerLayer.get(aType.getName())
                    .add(ROLE + feature.getName() + "_" + slotLinkTypes.get(feature.getName()));
            featurePerLayer.get(aType.getName()).add(slotFeatureTypes.get(feature).getName());
        } else {
            String annotation = aFs.getFeatureValueAsString(feature);
            if (annotation == null) {
                annotation = "*";
            } else {
                // Escape special character
                annotation = replaceEscapeChars(annotation);
            }
            annotation = annotation + (ref > 0 ? "[" + ref + "]" : "");
            // only add BIO markers to multiple annotations
            setAnnoFeature(aIsMultiToken, aIsFirst, annoPerFeatures, annotation);

            featurePerLayer.get(aType.getName()).add(feature.getShortName());
        }
    }
    aAnnotationsPertype.putIfAbsent(aUnit, new ArrayList<>());
    // If the layer do not have a feature at all, add dummy * as a place holder
    if (annoPerFeatures.size() == 0) {
        setAnnoFeature(aIsMultiToken, aIsFirst, annoPerFeatures, "*" + (ref > 0 ? "[" + ref + "]" : ""));
    }
    aAnnotationsPertype.get(aUnit).add(annoPerFeatures);
}

From source file:org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation.java

private boolean addInputValue(String compInstUniqueId, ComponentInstanceInput instanceProperty,
        Map<String, Map<String, ComponentInstanceInput>> propertyToInstanceValue) {

    String propertyUid = instanceProperty.getUniqueId();

    Map<String, ComponentInstanceInput> map = propertyToInstanceValue.get(propertyUid);
    if (map == null) {
        map = new HashMap<>();
        propertyToInstanceValue.put(propertyUid, map);
    }/*ww w. j a v a2 s  .  c o m*/

    ComponentInstanceInput putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
    if (putIfAbsent != null) {
        BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value",
                "Found 2 values on the same instance", ErrorSeverity.ERROR);
        return false;
    }

    return true;

}

From source file:org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation.java

private boolean addPropertyValue(String compInstUniqueId, ComponentInstanceProperty instanceProperty,
        Map<String, Map<String, ComponentInstanceProperty>> propertyToInstanceValue) {

    String propertyUid = instanceProperty.getUniqueId();

    Map<String, ComponentInstanceProperty> map = propertyToInstanceValue.get(propertyUid);
    if (map == null) {
        map = new HashMap<>();
        propertyToInstanceValue.put(propertyUid, map);
    }//w  ww .ja v  a  2  s.c o  m

    ComponentInstanceProperty putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
    if (putIfAbsent != null) {
        BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value",
                "Found 2 values on the same instance", ErrorSeverity.ERROR);
        return false;
    }

    return true;

}