Example usage for java.util HashSet iterator

List of usage examples for java.util HashSet iterator

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:com.ichi2.anki.SyncClient.java

/**
 * Anki Desktop -> libanki/anki/sync.py, SyncTools - diffSummary
 *///from   w w w. j av  a2 s. c  o m
private JSONArray diffSummary(JSONObject summaryLocal, JSONObject summaryServer, String key) {
    JSONArray locallyEdited = new JSONArray();
    JSONArray locallyDeleted = new JSONArray();
    JSONArray remotelyEdited = new JSONArray();
    JSONArray remotelyDeleted = new JSONArray();

    Log.i(AnkiDroidApp.TAG, "\ndiffSummary - Key = " + key);
    Log.i(AnkiDroidApp.TAG, "\nSummary local = ");
    Utils.printJSONObject(summaryLocal, false);
    Log.i(AnkiDroidApp.TAG, "\nSummary server = ");
    Utils.printJSONObject(summaryServer, false);

    // Hash of all modified ids
    HashSet<Long> ids = new HashSet<Long>();

    try {
        // Build a hash (id item key, modification time) of the modifications on server (null -> deleted)
        HashMap<Long, Double> remoteMod = new HashMap<Long, Double>();
        putExistingItems(ids, remoteMod, summaryServer.getJSONArray(key));
        HashMap<Long, Double> rdeletedIds = putDeletedItems(ids, remoteMod,
                summaryServer.getJSONArray("del" + key));

        // Build a hash (id item, modification time) of the modifications on client (null -> deleted)
        HashMap<Long, Double> localMod = new HashMap<Long, Double>();
        putExistingItems(ids, localMod, summaryLocal.getJSONArray(key));
        HashMap<Long, Double> ldeletedIds = putDeletedItems(ids, localMod,
                summaryLocal.getJSONArray("del" + key));

        Iterator<Long> idsIterator = ids.iterator();
        while (idsIterator.hasNext()) {
            Long id = idsIterator.next();
            Double localModTime = localMod.get(id);
            Double remoteModTime = remoteMod.get(id);

            Log.i(AnkiDroidApp.TAG,
                    "\nid = " + id + ", localModTime = " + localModTime + ", remoteModTime = " + remoteModTime);
            // Changed/Existing on both sides
            if (localModTime != null && remoteModTime != null) {
                Log.i(AnkiDroidApp.TAG, "localModTime not null AND remoteModTime not null");
                if (localModTime < remoteModTime) {
                    Log.i(AnkiDroidApp.TAG, "Remotely edited");
                    remotelyEdited.put(id);
                } else if (localModTime > remoteModTime) {
                    Log.i(AnkiDroidApp.TAG, "Locally edited");
                    locallyEdited.put(id);
                }
            }
            // If it's missing on server or newer here, sync
            else if (localModTime != null && remoteModTime == null) {
                Log.i(AnkiDroidApp.TAG, "localModTime not null AND remoteModTime null");
                if (!rdeletedIds.containsKey(id) || rdeletedIds.get(id) < localModTime) {
                    Log.i(AnkiDroidApp.TAG, "Locally edited");
                    locallyEdited.put(id);
                } else {
                    Log.i(AnkiDroidApp.TAG, "Remotely deleted");
                    remotelyDeleted.put(id);
                }
            }
            // If it's missing locally or newer there, sync
            else if (remoteModTime != null && localModTime == null) {
                Log.i(AnkiDroidApp.TAG, "remoteModTime not null AND localModTime null");
                if (!ldeletedIds.containsKey(id) || ldeletedIds.get(id) < remoteModTime) {
                    Log.i(AnkiDroidApp.TAG, "Remotely edited");
                    remotelyEdited.put(id);
                } else {
                    Log.i(AnkiDroidApp.TAG, "Locally deleted");
                    locallyDeleted.put(id);
                }
            }
            // Deleted or not modified in both sides
            else {
                Log.i(AnkiDroidApp.TAG, "localModTime null AND remoteModTime null");
                if (ldeletedIds.containsKey(id) && !rdeletedIds.containsKey(id)) {
                    Log.i(AnkiDroidApp.TAG, "Locally deleted");
                    locallyDeleted.put(id);
                } else if (rdeletedIds.containsKey(id) && !ldeletedIds.containsKey(id)) {
                    Log.i(AnkiDroidApp.TAG, "Remotely deleted");
                    remotelyDeleted.put(id);
                }
            }
        }
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

    JSONArray diff = new JSONArray();
    diff.put(locallyEdited);
    diff.put(locallyDeleted);
    diff.put(remotelyEdited);
    diff.put(remotelyDeleted);

    return diff;
}

From source file:edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner.java

protected void setMostSpecificTypes(Resource individual, HashSet<String> typeURIs, Model inferenceModel) {

    Model retractions = ModelFactory.createDefaultModel();

    inferenceModel.enterCriticalSection(Lock.READ);
    try {/*www .  j  av a2 s .  c  o m*/
        // remove obsolete mostSpecificType assertions
        StmtIterator iter = inferenceModel.listStatements(individual, mostSpecificType, (RDFNode) null);

        while (iter.hasNext()) {
            Statement stmt = iter.next();

            if (!stmt.getObject().isResource()) {
                log.warn("The object of this assertion is expected to be a resource: " + stmtString(stmt));
                continue;
            }

            if (!typeURIs.contains(stmt.getObject().asResource().getURI())) {
                retractions.add(stmt);
            }
        }
    } finally {
        inferenceModel.leaveCriticalSection();
    }

    Iterator<Statement> rIter = retractions.listStatements();
    while (rIter.hasNext()) {
        removeInference(rIter.next(), inferenceModel, true, false);
    }

    Iterator<String> typeIter = typeURIs.iterator();
    while (typeIter.hasNext()) {
        String typeURI = typeIter.next();
        Statement mstStmt = ResourceFactory.createStatement(individual, mostSpecificType,
                ResourceFactory.createResource(typeURI));
        addInference(mstStmt, inferenceModel, true);
    }

    return;
}

From source file:org.unitime.timetable.test.ImportPreferences.java

public void importInstructionalOffering(Element element) {
    InstructionalOffering io = (InstructionalOffering) iAllInstructionalOfferings.get(new ClassHash(element));
    sLog.info("Processing instructional offering " + element.attributeValue("subjectArea") + " "
            + element.attributeValue("courseNbr"));
    if (io == null) {
        sLog.info("  -- creating new offering");
        HashSet courseOfferings = new HashSet();
        for (Iterator i = element.elementIterator("courseOffering"); i.hasNext();) {
            Element x = (Element) i.next();
            SubjectArea sa = (SubjectArea) hibSession.createQuery(
                    "select sa from SubjectArea sa where sa.subjectAreaAbbreviation=:subjectAreaAbbreviation and sa.sessionId=:sessionId")
                    .setLong("sessionId", iSession.getUniqueId().longValue())
                    .setString("subjectAreaAbbreviation", x.attributeValue("subjectArea")).uniqueResult();
            CourseOffering co = (CourseOffering) hibSession.createQuery(
                    "select co from CourseOffering co where co.subjectArea.uniqueId=:subjectAreaId and co.courseNbr=:courseNbr")
                    .setInteger("subjectAreaId", sa.getUniqueId().intValue())
                    .setString("courseNbr", x.attributeValue("courseNbr")).uniqueResult();
            if (co == null) {
                co = new CourseOffering();
                co.setSubjectArea(sa);//from w w  w .  j  a va  2 s .c  o  m
                co.setCourseNbr(x.attributeValue("courseNbr"));
            }
            co.setProjectedDemand(Integer.valueOf(x.attributeValue("projectedDemand")));
            co.setDemand(Integer.valueOf(x.attributeValue("demand", "0")));
            co.setIsControl(new Boolean(x.attributeValue("isControl")));
            co.setPermId(x.attributeValue("permId"));
            courseOfferings.add(co);
        }
        io = new InstructionalOffering();
        io.setNotOffered(new Boolean(false));
        io.setSession(iSession);
        io.setInstrOfferingPermId(Integer.valueOf(element.attributeValue("instrOfferingPermId")));
        io.setCourseOfferings(courseOfferings);
        io.setByReservationOnly(false);
        for (Iterator i = courseOfferings.iterator(); i.hasNext();) {
            ((CourseOffering) i.next()).setInstructionalOffering(io);
        }
        hibSession.save(io);
        hibSession.flush();
        hibSession.refresh(io);
    } else if (io.isNotOffered().booleanValue()) {
        sLog.info("  -- changing not offered offering");
        io.setNotOffered(new Boolean(false));
        hibSession.update(io);
    }
    Hashtable classTable = new Hashtable();
    Iterator i = element.elementIterator("instrOfferingConfig");
    if (io.getInstrOfferingConfigs() != null && !io.getInstrOfferingConfigs().isEmpty()) {
        for (Iterator j = io.getInstrOfferingConfigs().iterator(); i.hasNext() && j.hasNext();) {
            InstrOfferingConfig c = (InstrOfferingConfig) j.next();
            Element x = (Element) i.next();
            int limit = Integer.parseInt(x.attributeValue("limit"));
            if (limit != c.getLimit().intValue()) {
                sLog.info("  -- changing limit to " + limit + " (was " + c.getLimit() + ")");
                c.setLimit(new Integer(limit));
            }
            hibSession.update(c);
            for (Iterator k = x.elementIterator("schedulingSubpart"); k.hasNext();) {
                importSchedulingSubpartStructure((Element) k.next(), null, c, classTable);
            }
        }
    }
    while (i.hasNext()) {
        Element x = (Element) i.next();
        InstrOfferingConfig c = new InstrOfferingConfig();
        c.setInstructionalOffering(io);
        c.setLimit(Integer.valueOf(x.attributeValue("limit")));
        c.setUnlimitedEnrollment(Boolean.FALSE);
        if (x.attributeValue("unlimitedEnrollment") != null)
            c.setUnlimitedEnrollment(new Boolean(x.attributeValue("unlimitedEnrollment")));
        hibSession.save(c);
        hibSession.flush();
        hibSession.refresh(c);
        for (Iterator j = x.elementIterator("schedulingSubpart"); j.hasNext();) {
            importSchedulingSubpartStructure((Element) j.next(), null, c, classTable);
        }
    }
}

From source file:es.caib.seycon.ng.servei.XarxaServiceImpl.java

private boolean sonAliasIguales(String alias1, String alias2) {
    if ((alias1 == null && alias2 != null) || (alias1 != null && alias2 == null))
        return false; // solo 1 nulo
    if (alias1 == null && alias2 == null)
        return true; // ambos nulos
    HashSet h_alias1 = new HashSet();
    HashSet h_alias2 = new HashSet();
    // alias1 y alias2 NO son nulos
    String[] v_alias1 = alias1.split(" "); //$NON-NLS-1$
    String[] v_alias2 = alias2.split(" "); //$NON-NLS-1$
    // Los guardamos en los sets
    if (v_alias1 != null)
        for (int i = 0; i < v_alias1.length; i++) {
            String act = v_alias1[i];
            if (act != null && !"".equals(act.trim())) //$NON-NLS-1$
                h_alias1.add(act);/*www .  j  ava  2s  .  com*/
        }
    if (v_alias2 != null)
        for (int i = 0; i < v_alias2.length; i++) {
            String act = v_alias2[i];
            if (act != null && !"".equals(act.trim())) //$NON-NLS-1$
                h_alias2.add(act);
        }
    if (h_alias1.size() != h_alias2.size())
        return false; // No tienen el mismo tamao
    // Los comparamos buscando todos los del primero en el segundo:
    for (Iterator it = h_alias1.iterator(); it.hasNext();) {
        String elem = (String) it.next();
        if (!h_alias2.contains(elem))
            return false;
    }
    return true;
}

From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java

/**
 * Process CUI rows./*from ww  w.  j  a v  a  2 s. co m*/
 *
 * @param conceptData the concept data
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws SQLException the SQL exception
 * @throws PropertyVetoException the property veto exception
 */
private void processCUIRows(ArrayList<RXNCONSO> conceptData)
        throws IOException, SQLException, PropertyVetoException {
    final String rxCui = conceptData.get(0).rxcui;
    final HashSet<String> uniqueTTYs = new HashSet<>();
    final HashSet<String> uniqueSABs = new HashSet<>();

    // ensure all the same CUI, gather the TTYs involved
    conceptData.stream().map((row) -> {
        uniqueTTYs.add(row.tty);
        return row;
    }).map((row) -> {
        uniqueSABs.add(row.sab);
        return row;
    }).filter((row) -> (!row.rxcui.equals(rxCui))).forEachOrdered((_item) -> {
        throw new RuntimeException("Oops");
    });

    ComponentReference cuiConcept;

    if ((uniqueSABs.size() == 1) && uniqueSABs.iterator().next().equals(this.sctSab)) {
        // This is a SCT only concept - we don't want to create it.  But we might need to put some relationships or associations here.
        final String sctId = conceptData.get(0).code;

        if (sctId == null) {
            throw new RuntimeException("Unexpected");
        }

        cuiConcept = ComponentReference.fromConcept(this.sctIdToUUID.get(sctId));

        // Add the RxCUI UUID
        this.importUtil.addUUID(cuiConcept.getPrimordialUuid(), createCUIConceptUUID(rxCui));

        // TODO need to look at what else I should be grabbing - the RXCUI for example should be attached.  What else?
    } else {
        // just creating the reference here, with the UUID - because we don't know if it should be active or inactive yet.
        // create the real concept later.
        cuiConcept = ComponentReference.fromConcept(createCUIConceptUUID(rxCui));

        long conceptTime = Integer.MAX_VALUE;

        // Activate the concept if any description is active
        Status conceptState = Status.INACTIVE;

        this.importUtil.addStringAnnotation(cuiConcept, rxCui,
                this.ptUMLSAttributes.getProperty("RXCUI").getUUID(), Status.ACTIVE);

        final ArrayList<ValuePropertyPairWithSAB> cuiDescriptions = new ArrayList<>();
        final HashSet<String> sabs = new HashSet<>();

        for (final RXNCONSO atom : conceptData) {
            if (atom.sab.equals(this.sctSab)) {
                continue;
            }

            // Add attributes from SAT table
            this.descSat.clearParameters();
            this.descSat.setString(1, rxCui);
            this.descSat.setString(2, atom.rxaui);

            final ArrayList<RXNSAT> satData;
            boolean disableDescription;
            Long descriptionTime;

            try (ResultSet rs = this.descSat.executeQuery()) {
                satData = new ArrayList<>();
                disableDescription = false;
                descriptionTime = null;

                while (rs.next()) {
                    final RXNSAT current = new RXNSAT(rs);

                    satData.add(current);

                    if ("RXN_OBSOLETED".equals(current.atn)) {
                        disableDescription = true;
                    }

                    if ("RXN_ACTIVATED".equals(current.atn)) {
                        try {
                            final long time = this.dateParse.parse(current.atv).getTime();

                            descriptionTime = time;

                            if (time < conceptTime) {
                                conceptTime = time;
                            }
                        } catch (final ParseException e) {
                            throw new RuntimeException("Can't parse date?");
                        }
                    }
                }
            }

            final ValuePropertyPairWithSAB desc = new ValuePropertyPairWithSAB(atom.str,
                    this.ptDescriptions.getProperty(atom.tty), atom.sab, satData);

            if (disableDescription) {
                desc.setDisabled(true);
            } else {
                // if any description is active, concept is still active
                conceptState = Status.ACTIVE;
            }

            if (descriptionTime != null) {
                desc.setTime(descriptionTime);
            }

            desc.setUUID(ConverterUUID.createNamespaceUUIDFromStrings(cuiConcept.getPrimordialUuid().toString(),
                    atom.rxaui));

            // used for sorting description to figure out what to use for FULLY_QUALIFIED_NAME
            cuiDescriptions.add(desc);
            desc.addStringAttribute(this.ptUMLSAttributes.getProperty("RXAUI").getUUID(), atom.rxaui);
            desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SAB").getUUID(),
                    this.ptSABs.getProperty(atom.sab).getUUID());

            if (StringUtils.isNotBlank(atom.code) && !atom.code.equals("NOCODE")) {
                desc.addStringAttribute(this.ptUMLSAttributes.getProperty("CODE").getUUID(), atom.code);
            }

            if (StringUtils.isNotBlank(atom.saui)) {
                desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SAUI").getUUID(), atom.saui);
            }

            if (StringUtils.isNotBlank(atom.scui)) {
                desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SCUI").getUUID(), atom.scui);
            }

            if (StringUtils.isNotBlank(atom.suppress)) {
                desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SUPPRESS").getUUID(),
                        this.suppress.get(atom.suppress));
            }

            if (StringUtils.isNotBlank(atom.cvf)) {
                if (atom.cvf.equals("4096")) {
                    desc.addRefsetMembership(this.cpcRefsetConcept.getPrimordialUuid());
                } else {
                    throw new RuntimeException("Unexpected value in RXNCONSO cvf column '" + atom.cvf + "'");
                }
            }

            if (!atom.lat.equals("ENG")) {
                ConsoleUtil.printErrorln("Non-english lang settings not handled yet!");
            }

            // TODO - at this point, sometime in the future, we make make attributes out of the relationships that occur between the AUIs
            // and store them on the descriptions, since OTF doesn't allow relationships between descriptions
            // TODO am I supposed to be using sabs?
            sabs.add(atom.sab);
        }

        // sanity check on descriptions - make sure we only have one that is of type synonym with the preferred flag
        final ArrayList<String> items = new ArrayList<>();

        cuiDescriptions.stream()
                .filter((vpp) -> ((vpp.getProperty().getPropertySubType() >= BPT_Descriptions.SYNONYM)
                        && (vpp.getProperty().getPropertySubType() <= (BPT_Descriptions.SYNONYM + 20))))
                .forEachOrdered((vpp) -> {
                    items.add(vpp.getProperty().getSourcePropertyNameFQN() + " "
                            + vpp.getProperty().getPropertySubType());
                }); // Numbers come from the rankings down below in makeDescriptionType(...)

        final HashSet<String> ranksLookedAt = new HashSet<>();

        ranksLookedAt.add("204");
        ranksLookedAt.add("206");
        ranksLookedAt.add("210");
        ranksLookedAt.add("208");
        ranksLookedAt.add("212");

        boolean oneNotInList = false;

        if (items.size() > 1) {
            for (final String s : items) {
                if (!ranksLookedAt.contains(s.substring(s.length() - 3, s.length()))) {
                    oneNotInList = true;
                    break;
                }
            }
        }

        if (oneNotInList) {
            ConsoleUtil.printErrorln(
                    "Need to rank multiple synonym types that are each marked preferred, determine if ranking is appropriate!");
            items.forEach((s) -> {
                ConsoleUtil.printErrorln(s);
            });
        }

        final List<SemanticChronology> addedDescriptions = this.importUtil.addDescriptions(cuiConcept,
                cuiDescriptions);

        if (addedDescriptions.size() != cuiDescriptions.size()) {
            throw new RuntimeException("oops");
        }

        final HashSet<String> uniqueUMLSCUI = new HashSet<>();

        for (int i = 0; i < cuiDescriptions.size(); i++) {
            final SemanticChronology desc = addedDescriptions.get(i);
            final ValuePropertyPairWithSAB descPP = cuiDescriptions.get(i);
            final BiFunction<String, String, Boolean> functions = (atn, atv) -> {
                // Pull these up to the concept.
                if ("UMLSCUI".equals(atn)) {
                    uniqueUMLSCUI.add(atv);
                    return true;
                }

                return false;
            };

            // TODO should I be passing in item code here?
            processSAT(ComponentReference.fromChronology(desc), descPP.getSatData(), null, descPP.getSab(),
                    functions);
        }

        // pulling up the UMLS CUIs.
        // uniqueUMLSCUI is populated during processSAT
        uniqueUMLSCUI.forEach((umlsCui) -> {
            final UUID itemUUID = ConverterUUID.createNamespaceUUIDFromString("UMLSCUI" + umlsCui);

            this.importUtil.addStringAnnotation(cuiConcept, itemUUID, umlsCui,
                    this.ptTermAttributes.getProperty("UMLSCUI").getUUID(), Status.ACTIVE);
        });
        ValuePropertyPairWithAttributes.processAttributes(this.importUtil, cuiDescriptions, addedDescriptions);

        // there are no attributes in rxnorm without an AUI.
        //       try
        //       {
        this.importUtil.addRefsetMembership(cuiConcept, this.allCUIRefsetConcept.getPrimordialUuid(),
                Status.ACTIVE, null);

        //       }
        //       catch (RuntimeException e)
        //       {
        //               if (e.toString().contains("duplicate UUID"))
        //               {
        //                       //ok - this can happen due to multiple merges onto an existing SCT concept
        //               }
        //               else
        //               {
        //                       throw e;
        //               }
        //       }
        // add semantic types
        this.semanticTypeStatement.clearParameters();
        this.semanticTypeStatement.setString(1, rxCui);

        final ResultSet rs = this.semanticTypeStatement.executeQuery();

        processSemanticTypes(cuiConcept, rs);

        if (conceptTime < 0) {
            throw new RuntimeException("oops");
        }

        this.importUtil.createConcept(cuiConcept.getPrimordialUuid(), conceptTime, conceptState, null);
    }

    final HashSet<UUID> parents = new HashSet<>();

    this.cuiRelStatementForward.clearParameters();
    this.cuiRelStatementForward.setString(1, rxCui);
    parents.addAll(addRelationships(cuiConcept,
            REL.read(null, this.cuiRelStatementForward.executeQuery(), true, this.allowedCUIsForSABs,
                    this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string)))));
    this.cuiRelStatementBackward.clearParameters();
    this.cuiRelStatementBackward.setString(1, rxCui);
    parents.addAll(addRelationships(cuiConcept,
            REL.read(null, this.cuiRelStatementBackward.executeQuery(), false, this.allowedCUIsForSABs,
                    this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string)))));

    // Have to add multiple parents at once, no place to keep all the other details.  Load those as associations for now.
    if (parents.size() > 0) {
        ComponentReference.fromChronology(this.importUtil.addParent(cuiConcept, null,
                parents.toArray(new UUID[parents.size()]), null, null));
    }
}

From source file:org.kuali.kfs.vnd.document.validation.impl.VendorRule.java

/**
 * Validates vendor address fields./*from  w  w w .  j a  v  a  2  s. c  om*/
 *
 * @param document MaintenanceDocument
 * @return boolean false or true
 */
boolean processAddressValidation(MaintenanceDocument document) {
    boolean valid = true;
    boolean validAddressType = false;

    List<VendorAddress> addresses = newVendor.getVendorAddresses();
    String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode();
    String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType()
            .getVendorAddressTypeRequiredCode();

    for (int i = 0; i < addresses.size(); i++) {
        VendorAddress address = addresses.get(i);
        String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]";
        GlobalVariables.getMessageMap().clearErrorPath();
        GlobalVariables.getMessageMap().addToErrorPath(errorPath);

        this.getDictionaryValidationService().validateBusinessObject(address);
        if (GlobalVariables.getMessageMap().hasErrors()) {
            valid = false;
        }

        if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) {
            validAddressType = true;
        }

        valid &= checkAddressCountryEmptyStateZip(address);

        GlobalVariables.getMessageMap().clearErrorPath();
    }

    // validate Address Type
    String vendorAddressTabPrefix = KFSConstants.ADD_PREFIX + "." + VendorPropertyConstants.VENDOR_ADDRESS
            + ".";
    if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode)
            && !validAddressType) {
        String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode };
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters);
        String addressLine1Label = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_LINE_1);
        String addressCityLabel = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_CITY);
        String addressCountryLabel = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_LINE_1,
                KFSKeyConstants.ERROR_REQUIRED, addressLine1Label);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_CITY,
                KFSKeyConstants.ERROR_REQUIRED, addressCityLabel);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY,
                KFSKeyConstants.ERROR_REQUIRED, addressCountryLabel);
        valid = false;
    }

    valid &= validateDefaultAddressCampus(newVendor);

    // Check to see if all divisions have one desired address for this vendor type
    Map fieldValues = new HashMap();
    fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID,
            newVendor.getVendorHeaderGeneratedIdentifier());
    // Find all the addresses for this vendor and its divisions:
    List<VendorAddress> vendorDivisionAddresses = new ArrayList(
            SpringContext.getBean(BusinessObjectService.class).findMatchingOrderBy(VendorAddress.class,
                    fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true));

    // This set stores the vendorDetailedAssignedIds for the vendor divisions which is
    // bascically the division numbers 0, 1, 2, ...
    HashSet<Integer> vendorDetailedIds = new HashSet();
    // This set stores the vendor division numbers of the ones which have one address of the desired type
    HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet();

    for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) {
        // We need to exclude the first one Since we already checked for this in valid AddressType above.
        if (vendorDivisionAddress.getVendorDetailAssignedIdentifier() != 0) {
            vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
            if (vendorDivisionAddress.getVendorAddressTypeCode()
                    .equalsIgnoreCase(vendorAddressTypeRequiredCode)) {
                vendorDivisionsIdsWithDesiredAddressType
                        .add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
            }
        }
    }

    // If the number of divisions with the desired address type is less than the number of divisions for his vendor
    if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) {
        Iterator itr = vendorDetailedIds.iterator();
        Integer value;
        String vendorId;

        while (itr.hasNext()) {
            value = (Integer) itr.next();
            if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) {
                vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-' + value.toString();
                String[] parameters = new String[] { vendorId, vendorTypeCode, vendorAddressTypeRequiredCode };

                //divisions without the desired address type should only be an warning
                GlobalVariables.getMessageMap().putWarningWithoutFullErrorPath(
                        MAINTAINABLE_ERROR_PREFIX + vendorAddressTabPrefix
                                + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                        VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters);
            }
        }
    }

    return valid;
}

From source file:org.kuali.ole.vnd.document.validation.impl.VendorRule.java

/**
 * Validates vendor address fields.//from  ww  w  .  j a  va 2 s  .  c o  m
 *
 * @param document MaintenanceDocument
 * @return boolean false or true
 */
boolean processAddressValidation(MaintenanceDocument document) {
    boolean valid = true;
    boolean validAddressType = false;

    List<VendorAddress> addresses = newVendor.getVendorAddresses();
    String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode();
    String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType()
            .getVendorAddressTypeRequiredCode();
    if (addresses.size() == 0) {
        putFieldError(VendorPropertyConstants.VENDOR_ADDRESS, VendorKeyConstants.OLE_VENDOR_ADDRESS);
        //GlobalVariables.getMessageMap().putError(VendorPropertyConstants.VENDOR_ADDRESS, VendorKeyConstants.OLE_VENDOR_ADDRESS, "");
        valid = false;
        validAddressType = false;
    }
    if (valid) {

        for (int i = 0; i < addresses.size(); i++) {
            VendorAddress address = addresses.get(i);
            String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i
                    + "]";
            GlobalVariables.getMessageMap().clearErrorPath();
            GlobalVariables.getMessageMap().addToErrorPath(errorPath);

            this.getDictionaryValidationService().validateBusinessObject(address);
            if (GlobalVariables.getMessageMap().hasErrors()) {
                valid = false;
            }

            if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) {
                validAddressType = true;
            }

            valid &= checkFaxNumber(address);

            valid &= checkAddressCountryEmptyStateZip(address);

            GlobalVariables.getMessageMap().clearErrorPath();
        }

        List<VendorPhoneNumber> phoneNumbers = newVendor.getVendorPhoneNumbers();
        for (int j = 0; j < phoneNumbers.size(); j++) {
            VendorPhoneNumber phoneNumber = phoneNumbers.get(j);
            String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_PHONE_NUMBERS + "["
                    + j + "]";
            GlobalVariables.getMessageMap().clearErrorPath();
            GlobalVariables.getMessageMap().addToErrorPath(errorPath);
            this.getDictionaryValidationService().validateBusinessObject(phoneNumber);
            valid &= checkPhoneNumber(phoneNumber);
        }

        // validate Address Type
        String vendorAddressTabPrefix = OLEConstants.ADD_PREFIX + "." + VendorPropertyConstants.VENDOR_ADDRESS
                + ".";
        if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode)
                && !validAddressType) {
            String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode };
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                    VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters);
            String addressLine1Label = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_LINE_1);
            String addressCityLabel = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_CITY);
            String addressCountryLabel = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_LINE_1,
                    OLEKeyConstants.ERROR_REQUIRED, addressLine1Label);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_CITY,
                    OLEKeyConstants.ERROR_REQUIRED, addressCityLabel);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY,
                    OLEKeyConstants.ERROR_REQUIRED, addressCountryLabel);
            valid = false;
        }

        valid &= validateDefaultAddressCampus(newVendor);

        // Check to see if all divisions have one desired address for this vendor type
        Map fieldValues = new HashMap();
        fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID,
                newVendor.getVendorHeaderGeneratedIdentifier());
        // Find all the addresses for this vendor and its divisions:
        List<VendorAddress> vendorDivisionAddresses = new ArrayList(
                SpringContext.getBean(BusinessObjectService.class).findMatchingOrderBy(VendorAddress.class,
                        fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true));

        // This set stores the vendorDetailedAssignedIds for the vendor divisions which is
        // bascically the division numbers 0, 1, 2, ...
        HashSet<Integer> vendorDetailedIds = new HashSet();
        // This set stores the vendor division numbers of the ones which have one address of the desired type
        HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet();

        for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) {
            // We need to exclude the first one Since we already checked for this in valid AddressType above.
            if (vendorDivisionAddress.getVendorDetailAssignedIdentifier() != 0) {
                vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
                if (vendorDivisionAddress.getVendorAddressTypeCode()
                        .equalsIgnoreCase(vendorAddressTypeRequiredCode)) {
                    vendorDivisionsIdsWithDesiredAddressType
                            .add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
                }
            }
        }

        // If the number of divisions with the desired address type is less than the number of divisions for his vendor
        if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) {
            Iterator itr = vendorDetailedIds.iterator();
            Integer value;
            String vendorId;

            while (itr.hasNext()) {
                value = (Integer) itr.next();
                if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) {
                    vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-'
                            + value.toString();
                    String[] parameters = new String[] { vendorId, vendorTypeCode,
                            vendorAddressTypeRequiredCode };

                    //divisions without the desired address type should only be an warning
                    GlobalVariables.getMessageMap().putWarningWithoutFullErrorPath(
                            MAINTAINABLE_ERROR_PREFIX + vendorAddressTabPrefix
                                    + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                            VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters);
                }
            }
        }

    }
    return valid;
}

From source file:ch.ethz.epics.export.GoogleImageSitemap.java

public static String getImageSitemapEntry(XPort xport, CumulusTools ct, Log log, String globalId, Document doc,
        String lang) throws JDOMException, IOException {

    Element recordNode = getSingleNode(doc, "//epics:record");
    String recName = recordNode.getAttributeValue("recordName", XPort.nsEpics);

    log.debug("- image sitemap building for internal id='" + recName + "'");
    Document sitemap = new Document();

    // urlset sitemap root
    Element urlset = new Element("urlset", nsSitemap);
    urlset.addNamespaceDeclaration(nsImageSitemap);
    sitemap.setRootElement(urlset);//from w  ww  .j ava2  s  .  c om

    Element url = new Element("url", nsSitemap);
    urlset.addContent(url);

    // <loc> tag specifies the URL for an original image on your site
    Element c = new Element("loc", nsSitemap);
    String baseUrl = (String) xport.getParam("index.baseUrl");
    c.setText(baseUrl + "images/" + globalId + ".jpg");
    url.addContent(c);

    /** 
     * The <priority> value specifies the importance of a particular image relative to 
     * other images on the same site
     */
    c = new Element("priority", nsSitemap);
    c.setText("0.5");
    url.addContent(c);

    /**
     * The <lastmod> value identifies the time that the content at the URL was last modified. We recommend 
     * you set this value to the most recent time that the image last changed. This information enables 
     * crawlers to avoid recrawling content that has not changed.
     */
    c = new Element("lastmod", nsSitemap);
    // uses e-pics record modification date
    Element recMod = getSingleNode(doc, "//epics:field[@epics:id='{af4b2e02-5f6a-11d2-8f20-0000c0e166dc}']");
    String strDate = recMod.getChildTextNormalize("content", XPort.nsEpics);

    SimpleDateFormat df = ct.getDefaultDateFormat();
    java.util.Date dtRecMod;
    try {
        dtRecMod = df.parse(strDate);
        SimpleDateFormat w3c = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        strDate = w3c.format(dtRecMod);
        c.setText(strDate);
        url.addContent(c);
    } catch (ParseException e1) {
        // cannot parse date: log warning, leave away lastmod
        log.warn("can't parse record modification date for " + globalId);
    }

    /** 
     * The <changefreq> value indicates how frequently the content at a particular URL is likely to 
     * change. We recommend you set this value to indicate how frequently the image changes. 
     */
    c = new Element("changefreq", nsSitemap);
    c.setText("monthly");
    url.addContent(c);

    /** 
     * The <expires> tag identifies the time that the content expires. The value of the <expires> tag 
     * should be a timestamp in W3C DATETIME format.
     */
    // e-pics: add 2 years to now
    c = new Element("expires", nsSitemap);
    SimpleDateFormat w3c = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Calendar cNow = Calendar.getInstance();
    cNow.add(Calendar.YEAR, 2);
    Date dt = cNow.getTime();
    strDate = w3c.format(dt);
    c.setText(strDate);
    url.addContent(c);

    // image:image
    Element imageTag = new Element("image", nsImageSitemap);
    url.addContent(imageTag);

    // image:landing_page
    Element cLandingPage = new Element("landing_page", nsImageSitemap);
    imageTag.addContent(cLandingPage);

    /**
     * The <image:loc> tag identifies the URL where the user will be directed when clicking on the image
     * from Google search results. Please note that this value must be properly encoded.
     */
    c = new Element("loc", nsImageSitemap);
    baseUrl = (String) xport.getParam("index.baseUrl");
    c.setText(baseUrl + globalId + ".html");
    cLandingPage.addContent(c);

    /**
     * The <image:language> tag identifies the language for each landing page defined by <image:landing_page>
     */
    // e-pics: primarily german content
    c = new Element("language", nsImageSitemap);
    c.setText(lang);
    cLandingPage.addContent(c);

    /**
     * The <image:title> tag specifies the title of the image. There should be a maximum of one title 
     * per landing page.
     */
    Element e = getSingleNode(doc, "//epics:field[@epics:id='{af4b2e3d-5f6a-11d2-8f20-0000c0e166dc}']");
    String title = e.getChildText("content", XPort.nsEpics);
    if (title != null && title.length() > 0) {
        c = new Element("title", nsImageSitemap);
        c.setText(title);
        cLandingPage.addContent(c);
    }

    /**
     * The <image:caption> tag's value provides context for an image. Please note that this value must be XMLencoded.
    * There should be a maximum of one caption per landing page.
     */
    e = getSingleNode(doc, "//epics:field[@epics:id='{af4b2e34-5f6a-11d2-8f20-0000c0e166dc}']");
    String caption = e.getChildText("content", XPort.nsEpics);
    if (caption != null && caption.length() > 0) {
        c = new Element("caption", nsImageSitemap);
        c.setText(caption);
        cLandingPage.addContent(c);
    }

    /**
     * The <image:category> tag's value specifies one or more groups, subjects or categories that 
     * describe the image. Multiple categories should be included in separate category tags. 
     * Comma-separated values within a single category tag will be considered one single category.
     */
    //ArrayList<String> keywords = new ArrayList<String>();
    HashSet<String> keywords = new HashSet<String>();
    XPath xpath = XPath.newInstance("//epics:category");
    xpath.addNamespace(XPort.nsEpics);
    List catNodes = xpath.selectNodes(doc);
    Iterator it = catNodes.iterator();
    String locationName = "";
    while (it.hasNext()) {
        e = (Element) it.next();
        String catName = e.getTextNormalize();

        log.debug("catName: " + catName);

        // KJ/20081203: use all keywords
        /* last keyword:
        String kw = catName.replaceAll(".* >? (.*)", "$1");
        log.debug("got keyword: "+kw);
        if (kw != null && kw.length() > 0) {
          keywords.addAll(Arrays.asList(kw.split(", ")));
        }
        */
        /*
        if (catName != null && catName.length() > 0) {
           keywords.addAll(Arrays.asList(catName.split("> ")));
           log.debug("got keywords: "+keywords);
        }
        */

        // add keywords with duplicates removed
        if (catName != null && catName.length() > 0) {

            List<String> kw = Arrays.asList(catName.split(">"));

            for (String k : kw) {

                if (!keywords.contains(k) && k.trim().length() > 1) {
                    log.debug("got keyword: " + k);
                    keywords.add(k.trim());
                }
            }

        }

        String nCatName = catName.replaceAll("\\s*>", ", ");
        if (nCatName != null && nCatName.length() > 0) {
            // KJ/20081203: don't add categories - use keywords instead

            //c = new Element("category", nsImageSitemap);
            //c.setText(nCatName);                
            //cLandingPage.addContent(c);   

            // E-Pics ETHBIB.Bildarchiv *spezial*
            if (catName.contains("Politische Geographie")) {
                log.debug("found location = " + catName);

                catName = catName.replaceAll(", Kanton > ", ", ");
                catName = catName.replaceAll(", Stadt > ", ", ");

                locationName = catName.replaceAll(".*?Politische Geographie\\s*>*(.*)", "$1");

                log.debug("reduced location to = " + locationName);
                locationName = locationName.replaceAll("\\s*>", ",");
                log.debug("reduced location to = " + locationName);
            }
        }

        /*
        if (nCatName.contains("Sachkatalog")) {
           String kwlist = catName.replaceAll(".*?Sachkatalog\\s*>*(.*)", "$1");
           if (kwlist != null && kwlist.length() > 0) {
         keywords.addAll(Arrays.asList(kwlist.split(", ")));
           }
        }
        */

    }

    /**
     * The <image:keyword> tag contains a single keyword that describes an image. By properly tagging 
     * images, you will help us to rank them in the Google Image Index. Please provide keywords that 
     * are as specific and descriptive as possible. Broad keywords may or may not be used in indexing. 
     * Keywords should be included in separate keyword tags, and comma-separated values within a single 
     * keyword tag will be considered one single keyword.
     */
    it = keywords.iterator();
    while (it.hasNext()) {
        String kw = (String) it.next();

        c = new Element("keyword", nsImageSitemap);
        c.setText(kw);
        cLandingPage.addContent(c);
    }

    /**
     * The <image:family_friendly> tag's value indicates whether the image only contains content that 
     * is suitable for children. Acceptable values for this tag are yes and no. Please use reasonable 
     * judgment when determining values for this tag. One way to define family-friendly is whether 
     * the image could appear in a G-rated movie.
     */
    c = new Element("family_friendly", nsImageSitemap);
    //TODO
    //e = (Element)xpath.selectSingleNode("//epics:field[@epics:id='{af4b2e34-5f6a-11d2-8f20-0000c0e166dc}']");
    //String familyFriendly = e.getChildText("epics:content");
    c.setText("yes");
    imageTag.addContent(c);

    /**
     * The <image:geo_location> tag is used to specify a geographical location. This can be a string 
     * the form of an address, city name, or latitude and longitude pair. Please note that this value 
     * must be XML-encoded.
     */
    c = new Element("geo_location", nsImageSitemap);
    if (locationName != null) {
        c.setText(locationName);
        imageTag.addContent(c);
    }

    /**
     * The <image:geo_location> tag is used to specify a geographical location. This can be a string 
     * the form of an address, city name, or latitude and longitude pair. Please note that this value 
     * must be XML-encoded.
     */

    // E-Pics: Creative Commons Namensnennung, Non-commercial, no derivatives
    c = new Element("license", nsImageSitemap);
    c.setText("http://creativecommons.org/licenses/by-nc-nd/2.5/ch/");
    imageTag.addContent(c);

    /**
     * The <image:quality> tag's value specifies the quality of the image relative to other images. 
     * This information may be used to rank images from the same site relative to one another on 
     * search result pages. Unlike <priority>, it is not used to prioritize images indexed by Google.
     */
    // E-Pics: not used
    //c = new Element("quality", nsImageSitemap);
    //c.setText("1.0");                
    //imageTag.addContent(c);            

    /**
     * The <image:publication_date> tag identifies the original publication date of the image in YYYY-MM-DD format.
    * The value of the <image:publication_date> tag should be a timestamp in W3C DATETIME format.
     */
    // E-Pics: EXIF Date created -or- TODO: Date field
    c = new Element("publication_date", nsImageSitemap);
    Element pubDate = getSingleNode(doc, "//epics:field[@epics:id='{af4b2e51-5f6a-11d2-8f20-0000c0e166dc}']");
    if (pubDate != null) {
        strDate = pubDate.getChildTextNormalize("content", XPort.nsEpics);
    } else {
        // try to get date field
        Element dateField = getSingleNode(doc,
                "//epics:field[@epics:id='{132267c2-4148-4b76-b851-88409d7d2799}']");
        if (dateField != null) {
            strDate = dateField.getChildTextNormalize("content", XPort.nsEpics);
            if (strDate != null && strDate.length() > 0) {
                if (!strDate.contains(".") && !strDate.contains("/")) {
                    // year only
                    strDate = "01.01." + strDate; //+" 00:00:00 CET";
                } else if (strDate.contains("/") && strDate.length() > 0) {
                    // mm/YYYY
                    String[] dateDetails = strDate.split("\\/");
                    if (dateDetails.length == 2) {
                        strDate = "01." + dateDetails[0] + "." + dateDetails[1];
                        //strDate += " 00:00:00 CET";
                    }
                } else {
                    //strDate = strDate+" 00:00:00 CET";
                }
                log.debug("converted dateonly value = " + strDate);
            }
        }
    }
    if (strDate != null && strDate.length() > 0) {
        df = ct.getDefaultDateFormat();
        java.util.Date dtPubDate;
        try {
            dtPubDate = df.parse(strDate);
            w3c = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            strDate = w3c.format(dtPubDate);
            c.setText(strDate);

            // KJ: 20090619 - Google does not like publication dates < 1970
            // therefore they are removed from the sitemap
            //imageTag.addContent(c);

        } catch (ParseException e1) {
            // cannot parse date: log warning, leave away lastmod
            log.warn("can't parse publication date for " + globalId, e1);
        }
    }

    /**
     * The <image:size> tag specifies the size of the image in pixels. The images that you make 
     * available to Google's crawlers should be the same size as the images that you display to 
     * users on your site.
     */
    // E-Pics: will need size of derivative image
    Element mediumImage = getSingleNode(doc, "//epics:field[@epics:fieldName='Image']");
    String finalSize = mediumImage.getAttributeValue("size", XPort.nsEpics);
    if (finalSize != null) {
        c = new Element("size", nsImageSitemap);
        c.setText(finalSize);
        imageTag.addContent(c);
    }

    /**
     * The <image:watermarking> tag's value indicates whether watermarking exists on the image. The 
     * only valid values of this tag are yes and no. If the value is yes, then you have the option 
     * of specifying the percentage attribute:
     */
    // E-Pics: maximum of 5% for creative commons license
    c = new Element("watermarking", nsImageSitemap);
    c.setText("yes");
    c.setAttribute("percentage", "5");
    imageTag.addContent(c);

    // write XML fragment into string
    StringWriter sw = new StringWriter();
    Format xmlFormatDebug = Format.getPrettyFormat().setOmitDeclaration(true);
    xmlFormatDebug.setEncoding("UTF-8");
    XMLOutputter xmlOutput = new XMLOutputter(xmlFormatDebug);
    Element sitemapRoot = sitemap.getRootElement();
    xmlOutput.output((Element) sitemapRoot.getContent(0), sw);

    String part = sw.toString();
    part = part.replaceAll(" xmlns=\"http://www.google.com/schemas/sitemap/0.9\"", "");
    part = part.replaceAll(" xmlns\\:image=\"http://www.google.com/schemas/sitemap/0.9\"", "");

    return part;
}

From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java

/**
 * recursively compute the number of leaves. fill in the icInfoMap as we go
 * along/*from w w  w.jav  a  2  s . com*/
 * 
 * @param concept
 *            concept for which we should get the leaves
 * @param leafCache
 *            cache of concept's leaves
 * @param icInfoMap
 *            to be updated with leaf counts
 * @param cg
 * @param w
 * @param visitedNodes
 *            list of nodes that have already been visited - we don't need
 *            to revisit them when getting the leaves
 * @return
 * @throws IOException
 */
private HashSet<Integer> getLeaves(ConcRel concept, SoftReference<HashSet<Integer>>[] leafCache,
        Map<String, IntrinsicICInfo> icInfoMap, ConceptGraph cg, BufferedWriter w,
        HashSet<Integer> visitedNodes) throws IOException {
    // look in cache
    SoftReference<HashSet<Integer>> refLeaves = leafCache[concept.getNodeIndex()];
    if (refLeaves != null && refLeaves.get() != null) {
        return refLeaves.get();
    }
    // not in cache - compute recursively
    HashSet<Integer> leaves = new HashSet<Integer>();
    leafCache[concept.getNodeIndex()] = new SoftReference<HashSet<Integer>>(leaves);
    if (concept.isLeaf()) {
        // for leaves, just add the concept id
        leaves.add(concept.getNodeIndex());
    } else {
        IntrinsicICInfo icInfo = icInfoMap.get(concept.getConceptID());
        // have we already computed the leaf count for this node?
        // if yes, then we can ignore previously visited nodes
        // if no, then compute it now and revisit previously visited nodes
        // if we have to
        boolean needLeaves = (icInfo != null && icInfo.getLeafCount() == 0);
        HashSet<Integer> visitedNodesLocal = visitedNodes;
        if (needLeaves || visitedNodesLocal == null) {
            // allocate a set to keep track of nodes we've already visited
            // so that we don't revisit them. if we have already computed
            // this node's leaf count then we reuse whatever the caller gave
            // us if non null, else allocate a new one.
            // if we haven't already computed this node's leaf count,
            // allocate a new set to avoid duplications in the traversal for
            // this node
            visitedNodesLocal = new HashSet<Integer>();
        }
        // for inner nodes, recurse
        for (ConcRel child : concept.getChildren()) {
            // if we've already visited a node, then don't bother adding
            // that node's leaves - we already have them
            if (!visitedNodesLocal.contains(child.getNodeIndex())) {
                leaves.addAll(getLeaves(child, leafCache, icInfoMap, cg, w, visitedNodesLocal));
            }
        }
        // add this node to the set of visited nodes so we know not to
        // revisit. This is only of importance if the caller gave us
        // a non-empty set.
        if (visitedNodes != null && visitedNodes != visitedNodesLocal) {
            visitedNodes.add(concept.getNodeIndex());
            visitedNodes.addAll(visitedNodesLocal);
        }
        // update the leaf count if we haven't done so already
        if (needLeaves) {
            icInfo.setLeafCount(leaves.size());
            // output leaves if desired
            if (w != null) {
                w.write(concept.getConceptID());
                w.write("\t");
                w.write(Integer.toString(leaves.size()));
                w.write("\t");
                Iterator<Integer> iter = leaves.iterator();
                while (iter.hasNext()) {
                    w.write(cg.getConceptList().get(iter.next()).getConceptID());
                    w.write(" ");
                }
                w.newLine();
            }
        }
    }
    return leaves;
}

From source file:helma.objectmodel.db.Transactor.java

/**
 * Commit the current transaction, persisting all changes to DB.
 *
 * @throws Exception .../*w  w  w  .j  ava 2 s. co  m*/
 */
public synchronized void commit() throws Exception {
    if (killed) {
        throw new DatabaseException("commit() called on killed transactor thread");
    } else if (!active) {
        return;
    }
    int inserted = 0;
    int updated = 0;
    int deleted = 0;

    ArrayList insertedNodes = null;
    ArrayList updatedNodes = null;
    ArrayList deletedNodes = null;
    ArrayList modifiedParentNodes = null;
    // if nodemanager has listeners collect dirty nodes
    boolean hasListeners = nmgr.hasNodeChangeListeners();

    if (hasListeners) {
        insertedNodes = new ArrayList();
        updatedNodes = new ArrayList();
        deletedNodes = new ArrayList();
        modifiedParentNodes = new ArrayList();
    }

    if (!dirtyNodes.isEmpty()) {
        Object[] dirty = dirtyNodes.values().toArray();

        // the set to collect DbMappings to be marked as changed
        HashSet dirtyDbMappings = new HashSet();
        Log eventLog = nmgr.app.getEventLog();

        for (int i = 0; i < dirty.length; i++) {
            Node node = (Node) dirty[i];

            // update nodes in db
            int nstate = node.getState();

            if (nstate == Node.NEW) {
                nmgr.insertNode(nmgr.db, txn, node);
                dirtyDbMappings.add(node.getDbMapping());
                node.setState(Node.CLEAN);

                // register node with nodemanager cache
                nmgr.registerNode(node);

                if (hasListeners) {
                    insertedNodes.add(node);
                }

                inserted++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("inserted node: " + node.getPrototype() + "/" + node.getID());
                }
            } else if (nstate == Node.MODIFIED) {
                // only mark DbMapping as dirty if updateNode returns true
                if (nmgr.updateNode(nmgr.db, txn, node)) {
                    dirtyDbMappings.add(node.getDbMapping());
                }
                node.setState(Node.CLEAN);

                // update node with nodemanager cache
                nmgr.registerNode(node);

                if (hasListeners) {
                    updatedNodes.add(node);
                }

                updated++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("updated node: " + node.getPrototype() + "/" + node.getID());
                }
            } else if (nstate == Node.DELETED) {
                nmgr.deleteNode(nmgr.db, txn, node);
                dirtyDbMappings.add(node.getDbMapping());

                // remove node from nodemanager cache
                nmgr.evictNode(node);

                if (hasListeners) {
                    deletedNodes.add(node);
                }

                deleted++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("removed node: " + node.getPrototype() + "/" + node.getID());
                }
            }

            node.clearWriteLock();
        }

        // set last data change times in db-mappings
        // long now = System.currentTimeMillis();
        for (Iterator i = dirtyDbMappings.iterator(); i.hasNext();) {
            DbMapping dbm = (DbMapping) i.next();
            if (dbm != null) {
                dbm.setLastDataChange();
            }
        }
    }

    long now = System.currentTimeMillis();

    if (!parentNodes.isEmpty()) {
        // set last subnode change times in parent nodes
        for (Iterator i = parentNodes.iterator(); i.hasNext();) {
            Node node = (Node) i.next();
            node.markSubnodesChanged();
            if (hasListeners) {
                modifiedParentNodes.add(node);
            }
        }
    }

    if (hasListeners) {
        nmgr.fireNodeChangeEvent(insertedNodes, updatedNodes, deletedNodes, modifiedParentNodes);
    }

    // clear the node collections
    recycle();

    if (active) {
        active = false;
        nmgr.db.commitTransaction(txn);
        txn = null;
    }

    StringBuffer msg = new StringBuffer(tname).append(" done in ").append(now - tstart).append(" millis");
    if (inserted + updated + deleted > 0) {
        msg.append(" [+").append(inserted).append(", ~").append(updated).append(", -").append(deleted)
                .append("]");
    }
    nmgr.app.logAccess(msg.toString());

    // unset transaction name
    tname = null;
}