List of usage examples for com.google.common.collect ListMultimap get
@Override List<V> get(@Nullable K key);
Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.
From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.java
/** * Determines whether the generic {@code --help} was requested or help was * requested for a specific class and invokes the appropriate * {@link PipelineOptionsFactory#printHelp(PrintStream)} and * {@link PipelineOptionsFactory#printHelp(PrintStream, Class)} variant. * Prints to the specified {@link PrintStream}, and exits if requested. * * <p>Visible for testing.//from w w w .j a va2 s . co m * {@code printStream} and {@code exit} used for testing. */ @SuppressWarnings("unchecked") static boolean printHelpUsageAndExitIfNeeded(ListMultimap<String, String> options, PrintStream printStream, boolean exit) { if (options.containsKey("help")) { final String helpOption = Iterables.getOnlyElement(options.get("help")); // Print the generic help if only --help was specified. if (Boolean.TRUE.toString().equals(helpOption)) { printHelp(printStream); if (exit) { System.exit(0); } else { return true; } } // Otherwise attempt to print the specific help option. try { Class<?> klass = Class.forName(helpOption); if (!PipelineOptions.class.isAssignableFrom(klass)) { throw new ClassNotFoundException("PipelineOptions of type " + klass + " not found."); } printHelp(printStream, (Class<? extends PipelineOptions>) klass); } catch (ClassNotFoundException e) { // If we didn't find an exact match, look for any that match the class name. Iterable<Class<? extends PipelineOptions>> matches = Iterables.filter(getRegisteredOptions(), new Predicate<Class<? extends PipelineOptions>>() { @Override public boolean apply(Class<? extends PipelineOptions> input) { if (helpOption.contains(".")) { return input.getName().endsWith(helpOption); } else { return input.getSimpleName().equals(helpOption); } } }); try { printHelp(printStream, Iterables.getOnlyElement(matches)); } catch (NoSuchElementException exception) { printStream.format("Unable to find option %s.%n", helpOption); printHelp(printStream); } catch (IllegalArgumentException exception) { printStream.format("Multiple matches found for %s: %s.%n", helpOption, Iterables.transform(matches, ReflectHelpers.CLASS_NAME)); printHelp(printStream); } } if (exit) { System.exit(0); } else { return true; } } return false; }
From source file:eu.esdihumboldt.cst.internal.FunctionExecutor.java
/** * Execute a property transformation.//from www . j a v a2 s . com * * @param transformation the transformation factory * @param cell the alignment cell * @param sources the named source entities and nodes * @param targets the named target entities and nodes */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void executeTransformation(PropertyTransformationFactory transformation, Cell cell, ListMultimap<String, Pair<SourceNode, Entity>> sources, ListMultimap<String, Pair<TargetNode, Entity>> targets) { TransformationLog cellLog = new CellLog(reporter, cell); PropertyTransformation<?> function; try { // TODO cache function objects? function = transformation.createExtensionObject(); } catch (Exception e) { cellLog.error(cellLog.createMessage("Error creating transformation function.", e)); return; } TransformationEngine engine = engines.get(transformation.getEngineId(), cellLog); if (engine == null) { // TODO instead try another transformation cellLog.error(cellLog.createMessage( "Skipping property transformation: No matching transformation engine found", null)); return; } // configure function // set expected result ListMultimap<String, PropertyEntityDefinition> expectedResult = ArrayListMultimap .create(targets.keySet().size(), 1); for (Entry<String, Pair<TargetNode, Entity>> targetEntry : targets.entries()) { EntityDefinition def = targetEntry.getValue().getSecond().getDefinition(); expectedResult.put(targetEntry.getKey(), toPropertyEntityDefinition(def)); } function.setExpectedResult(expectedResult); // set source variables ListMultimap<String, PropertyValue> variables = ArrayListMultimap.create(); for (Entry<String, Pair<SourceNode, Entity>> sourceEntry : sources.entries()) { EntityDefinition def = sourceEntry.getValue().getSecond().getDefinition(); SourceNode sourceNode = sourceEntry.getValue().getFirst(); if (TransformationTreeUtil.isEager(cell, sourceNode, cellLog, context.getServiceProvider())) { // eager source - all values Object[] values = sourceNode.getAllValues(); if (values != null) { for (int i = 0; i < values.length; i++) { PropertyValue propertyValue = new PropertyValueImpl(values[i], toPropertyEntityDefinition(def)); variables.put(sourceEntry.getKey(), propertyValue); } } } else { // non-eager source - one value Object value = sourceNode.getValue(); PropertyValue propertyValue = new PropertyValueImpl(value, toPropertyEntityDefinition(def)); variables.put(sourceEntry.getKey(), propertyValue); } } function.setVariables(variables); // set parameters function.setParameters(cell.getTransformationParameters()); // set context function.setExecutionContext(context.getCellContext(cell)); // set target type TypeDefinition targetType = null; if (!targets.isEmpty()) { TargetNode target = targets.values().iterator().next().getFirst(); targetType = target.getEntityDefinition().getType(); } function.setTargetType(targetType); function.setTypeCell(typeCell.get()); // execute function try { ((PropertyTransformation) function).execute(transformation.getIdentifier(), engine, transformation.getExecutionParameters(), cellLog, cell); } catch (Throwable e) { // TODO instead try another transformation? cellLog.error(cellLog.createMessage( "Skipping property transformation: Executing property transformation failed.", e)); return; } // apply function results ListMultimap<String, Object> results = function.getResults(); if (results != null) { for (String name : results.keySet()) { List<Object> values = results.get(name); List<Pair<TargetNode, Entity>> nodes = targets.get(name); if (nodes.size() > values.size()) { cellLog.warn(cellLog.createMessage(MessageFormat .format("Transformation result misses values for result with name {0}", name), null)); } if (values.size() > nodes.size()) { cellLog.warn(cellLog.createMessage( MessageFormat.format( "More transformation results than target nodes for result with name {0}", name), null)); } int count = Math.min(values.size(), nodes.size()); // FIXME if multiple target nodes should be implemented ever // ith value is ignored if ith node already has a value // instead it should probably look to put ith value into i+1th // node... for (int i = 0; i < count; i++) { Object value = values.get(i); TargetNode node = nodes.get(i).getFirst(); if (value instanceof MultiValue) { MultiValue originalValue = (MultiValue) value; MultiValue processedValue = new MultiValue(originalValue.size()); for (Object o : originalValue) { processedValue.add(processValue(cellLog, function, o, node)); } value = processedValue; } else { value = processValue(cellLog, function, value, node); } /* * TODO * * set node value only if no result has already been set. If * a value is already there and we are in a lower priority * executor, we do not overwrite. */ if (!node.isDefined()) { node.setResult(value); } } } } }
From source file:eu.esdihumboldt.cst.functions.core.FormattedString.java
@Override protected Object evaluate(String transformationIdentifier, TransformationEngine engine, ListMultimap<String, PropertyValue> variables, String resultName, PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log) throws TransformationException, NoResultException { String pattern = getParameterChecked(PARAMETER_PATTERN).as(String.class); // replace transformation variables pattern = getExecutionContext().getVariables().replaceVariables(pattern); // name/value mapping Map<String, Object> values = new LinkedHashMap<String, Object>(); List<PropertyValue> vars = variables.get(ENTITY_VARIABLE); for (PropertyValue var : vars) { // determine the variable value Object value;//www . j a v a 2s.c om try { value = var.getValueAs(String.class); } catch (ConversionException e) { value = var.getValue(); } FormattedStringFunction.addValue(values, value, var.getProperty()); } // replace markers in pattern // FIXME this is quick and dirty! does not handle escaping int i = 0; for (Entry<String, Object> entry : values.entrySet()) { String name = entry.getKey(); pattern = pattern.replaceAll(Pattern.quote("{" + name + "}"), "{" + i + "}"); i++; } try { return MessageFormat.format(pattern, values.values().toArray()); } catch (IllegalArgumentException e) { // missing inputs result in an invalid pattern // TODO better way to handle missing inputs // FIXME an error should still be reported for invalid patterns throw new NoResultException(e); } }
From source file:org.glowroot.agent.impl.Transaction.java
private static void addProtobufChildEntries(TraceEntryImpl entry, ListMultimap<TraceEntryImpl, TraceEntryImpl> parentChildMap, long transactionStartTick, long captureTick, int depth, TraceEntryVisitor entryVisitor, SharedQueryTextCollection sharedQueryTextCollection, boolean removeSingleAuxEntry) { if (!parentChildMap.containsKey(entry)) { // check containsKey to avoid creating garbage empty list via ListMultimap return;/*www. j av a2s .co m*/ } Collection<TraceEntryImpl> childEntries = parentChildMap.get(entry); for (TraceEntryImpl childEntry : childEntries) { boolean singleAuxEntry = childEntries.size() == 1 && childEntry.isAuxThreadRoot() && !childEntry.hasLocationStackTrace(); if (singleAuxEntry && removeSingleAuxEntry) { addProtobufChildEntries(childEntry, parentChildMap, transactionStartTick, captureTick, depth, entryVisitor, sharedQueryTextCollection, removeSingleAuxEntry); } else { childEntry.accept(depth, transactionStartTick, captureTick, entryVisitor, sharedQueryTextCollection); addProtobufChildEntries(childEntry, parentChildMap, transactionStartTick, captureTick, depth + 1, entryVisitor, sharedQueryTextCollection, false); } } }
From source file:org.sonar.plsqlopen.checks.UnnecessaryAliasInQueryCheck.java
@Override public void visitNode(AstNode node) { if (node.hasAncestor(dmlStatements)) { // if the current node is inside another DML statement (i.e. subquery), the node should be // ignored because it is considered in the analysis of the outer statement return;/*from w w w. ja v a 2 s . co m*/ } ListMultimap<String, TableReference> tableReferences = ArrayListMultimap.create(); for (AstNode fromClause : node.getDescendants(DmlGrammar.DML_TABLE_EXPRESSION_CLAUSE)) { AstNode table = fromClause.getFirstChild(DmlGrammar.TABLE_REFERENCE); AstNode alias = fromClause.getFirstChild(DmlGrammar.ALIAS); if (table != null) { tableReferences.put(table.getTokenOriginalValue().toLowerCase(), new TableReference(table, alias)); } } for (String tableName : tableReferences.keySet()) { List<TableReference> references = tableReferences.get(tableName); checkReference(references); } }
From source file:com.greensopinion.finance.services.reports.ReportsService.java
public IncomeVersusExpensesReport incomeVersusExpenses() { IncomeVersusExpensesReport report = new IncomeVersusExpensesReport(); Transactions transactions = transactionsService.retrieve(); ListMultimap<Long, Transaction> transactionsByMonth = ArrayListMultimap.create(); for (Transaction transaction : transactions.getTransactions()) { Long yearMonth = yearMonth(transaction.getDate()); transactionsByMonth.put(yearMonth, transaction); }/*from w w w . j a v a 2 s. co m*/ List<Long> sortedMonths = new ArrayList<>(transactionsByMonth.keySet()); Collections.sort(sortedMonths); for (final Long yearMonth : sortedMonths) { String name = monthName(yearMonth); report.addMonth(new Month(yearMonth, name, transactionsByMonth.get(yearMonth))); } return report; }
From source file:com.google.gerrit.server.ApprovalCopier.java
private Iterable<PatchSetApproval> getForPatchSet(ReviewDb db, ChangeControl ctl, PatchSet ps, Iterable<PatchSetApproval> dontCopy) throws OrmException { checkNotNull(ps, "ps should not be null"); ChangeData cd = changeDataFactory.create(db, ctl); try {/*from w ww . ja va 2 s . c o m*/ ProjectState project = projectCache.checkedGet(cd.change().getDest().getParentKey()); ListMultimap<PatchSet.Id, PatchSetApproval> all = cd.approvals(); checkNotNull(all, "all should not be null"); Table<String, Account.Id, PatchSetApproval> wontCopy = HashBasedTable.create(); for (PatchSetApproval psa : dontCopy) { wontCopy.put(psa.getLabel(), psa.getAccountId(), psa); } Table<String, Account.Id, PatchSetApproval> byUser = HashBasedTable.create(); for (PatchSetApproval psa : all.get(ps.getId())) { if (!wontCopy.contains(psa.getLabel(), psa.getAccountId())) { byUser.put(psa.getLabel(), psa.getAccountId(), psa); } } TreeMap<Integer, PatchSet> patchSets = getPatchSets(cd); try (Repository repo = repoManager.openRepository(project.getProject().getNameKey()); RevWalk rw = new RevWalk(repo)) { // Walk patch sets strictly less than current in descending order. Collection<PatchSet> allPrior = patchSets.descendingMap().tailMap(ps.getId().get(), false).values(); for (PatchSet priorPs : allPrior) { List<PatchSetApproval> priorApprovals = all.get(priorPs.getId()); if (priorApprovals.isEmpty()) { continue; } ChangeKind kind = changeKindCache.getChangeKind(project.getProject().getNameKey(), rw, repo.getConfig(), ObjectId.fromString(priorPs.getRevision().get()), ObjectId.fromString(ps.getRevision().get())); for (PatchSetApproval psa : priorApprovals) { if (wontCopy.contains(psa.getLabel(), psa.getAccountId())) { continue; } if (byUser.contains(psa.getLabel(), psa.getAccountId())) { continue; } if (!canCopy(project, psa, ps.getId(), kind)) { wontCopy.put(psa.getLabel(), psa.getAccountId(), psa); continue; } byUser.put(psa.getLabel(), psa.getAccountId(), copy(psa, ps.getId())); } } return labelNormalizer.normalize(ctl, byUser.values()).getNormalized(); } } catch (IOException e) { throw new OrmException(e); } }
From source file:fi.aluesarjat.prototype.SearchServiceImpl.java
private List<Predicate> getSearchFilters(ListMultimap<UID, UID> facetRestrictions, Map<ParamExpression<UID>, UID> bindings) { List<Predicate> filters = new ArrayList<Predicate>(); int dimensionRestrictionCount = 0; for (UID facet : facetRestrictions.keySet()) { List<UID> values = facetRestrictions.get(facet); if (facet.equals(SCV.Dataset)) { filters.add(item.has(SCV.dataset, dataset)); if (values.size() == 1) { bindings.put(dataset, values.get(0)); } else { filters.add(dataset.in(values)); }//w w w.j a v a2 s.c om } else { UID dimensionPredicate = ScovoExtDatasetHandler.getDimensionProperty(facet); filters.addAll(equalsIn(item, dimensionPredicate, values, "dimensionRestriction", ++dimensionRestrictionCount)); } } return filters; }
From source file:org.robotframework.ide.eclipse.main.plugin.hyperlink.detectors.HyperlinksToKeywordsDetector.java
protected final List<IHyperlink> detectHyperlinks(final RobotSuiteFile suiteFile, final IRegion fromRegion, final String keywordName) { final List<IHyperlink> hyperlinks = new ArrayList<>(); final AccessibleKeywordsEntities context = createEntities(suiteFile); final ListMultimap<String, KeywordEntity> keywordProposal = context.findPossibleKeywords(keywordName, false);//from w w w. j a va 2s. co m final Optional<String> nameToUse = GherkinStyleSupport.firstNameTransformationResult(keywordName, new NameTransformation<String>() { @Override public Optional<String> transform(final String gherkinNameVariant) { return context.isKeywordAccessible(keywordProposal, gherkinNameVariant) ? Optional.of(gherkinNameVariant) : Optional.<String>empty(); } }); if (!nameToUse.isPresent()) { return hyperlinks; } final String name = nameToUse.get().isEmpty() ? keywordName : nameToUse.get().toString(); final int lengthOfRemovedPrefix = keywordName.length() - name.length(); final IRegion adjustedFromRegion = new Region(fromRegion.getOffset() + lengthOfRemovedPrefix, fromRegion.getLength() - lengthOfRemovedPrefix); final ListMultimap<KeywordScope, KeywordEntity> keywords = context.getPossibleKeywords(keywordProposal, name); final List<IHyperlink> definitionHyperlinks = new ArrayList<>(); final List<IHyperlink> documentationHyperlinks = new ArrayList<>(); for (final KeywordScope scope : KeywordScope.defaultOrder()) { for (final KeywordEntity keyword : keywords.get(scope)) { final KeywordHyperlinkEntity keywordEntity = (KeywordHyperlinkEntity) keyword; switch (scope) { case LOCAL: String lbl = "[" + keywordEntity.getNameFromDefinition() + ", line: " + keywordEntity.destinationPosition.getLine() + "] [" + keywordEntity.exposingResource.getFile().getFullPath() + "]"; definitionHyperlinks.add(createLocalKeywordHyperlink(keywordEntity, adjustedFromRegion, lbl)); documentationHyperlinks.add(new UserKeywordDocumentationHyperlink(adjustedFromRegion, keywordEntity.exposingResource, keywordEntity.userKeyword, lbl)); break; case RESOURCE: lbl = "[" + keywordEntity.getNameFromDefinition() + ", line: " + keywordEntity.destinationPosition.getLine() + "] [" + keywordEntity.exposingResource.getFile().getFullPath() + "]"; definitionHyperlinks .add(createResourceKeywordHyperlink(keywordEntity, adjustedFromRegion, lbl)); documentationHyperlinks.add(new UserKeywordDocumentationHyperlink(adjustedFromRegion, keywordEntity.exposingResource, keywordEntity.userKeyword, lbl)); break; default: definitionHyperlinks.add(new KeywordInLibrarySourceHyperlink(adjustedFromRegion, suiteFile.getFile().getProject(), keywordEntity.libSpec, keywordEntity.kwSpec)); documentationHyperlinks.add(new KeywordDocumentationHyperlink(adjustedFromRegion, suiteFile.getFile().getProject(), keywordEntity.libSpec, keywordEntity.kwSpec)); break; } } } if (definitionHyperlinks.size() > 0) { hyperlinks.add(definitionHyperlinks.get(0)); } if (documentationHyperlinks.size() > 0) { hyperlinks.add(documentationHyperlinks.get(0)); } if (definitionHyperlinks.size() > 1) { hyperlinks.add(new CompoundHyperlink(name, adjustedFromRegion, newArrayList(filter(definitionHyperlinks, RedHyperlink.class)), "Show All Definitions")); } if (documentationHyperlinks.size() > 1) { hyperlinks.add(new CompoundHyperlink(name, adjustedFromRegion, newArrayList(filter(documentationHyperlinks, RedHyperlink.class)), "Show All Documentations")); } return hyperlinks; }
From source file:eu.esdihumboldt.cst.functions.inspire.GeographicalName.java
/** * @see AbstractSingleTargetPropertyTransformation#evaluate(String, * TransformationEngine, ListMultimap, String, * PropertyEntityDefinition, Map, TransformationLog) *//* www . j a v a 2 s. co m*/ @Override protected Object evaluate(String transformationIdentifier, TransformationEngine engine, ListMultimap<String, PropertyValue> variables, String resultName, PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log) throws TransformationException, NoResultException { // list of all source properties List<PropertyValue> inputs = variables.get(null); if (inputs.isEmpty()) { // no input, so don't create any structure throw new NoResultException(); } // get all parameters defined by the wizard page String ipa = getParameterChecked(PROPERTY_PRONUNCIATIONIPA).as(String.class); // we need a default value and a try/catch-block because in older // version we couldn't edit the pronunciationSoundLink text field String sound = ""; try { sound = getParameterChecked(PROPERTY_PRONUNCIATIONSOUNDLINK).as(String.class); } catch (Exception e) { // do nothing } String language = getParameterChecked(PROPERTY_LANGUAGE).as(String.class); String sourceOfName = getParameterChecked(PROPERTY_SOURCEOFNAME).as(String.class); String nameStatus = getParameterChecked(PROPERTY_NAMESTATUS).as(String.class); String nativeness = getParameterChecked(PROPERTY_NATIVENESS).as(String.class); String gender = getParameterChecked(PROPERTY_GRAMMA_GENDER).as(String.class); String number = getParameterChecked(PROPERTY_GRAMMA_NUMBER).as(String.class); // get the script and transliteration parameters // should have the same order like source properties ListMultimap<String, ParameterValue> params = getParameters(); List<ParameterValue> scripts = params.get(PROPERTY_SCRIPT); List<ParameterValue> trans = params.get(PROPERTY_TRANSLITERATION); if (inputs.size() != scripts.size() || inputs.size() != trans.size()) { throw new TransformationException( "Number of inputs does not match number of configured spellings, can't determine script and transliteration of spellings."); // XXX could this be dealt with if the property "text" would be used // again for this purpose? } // definition of the target property TypeDefinition targetType = resultProperty.getDefinition().getPropertyType(); // instance that can be changed (add property/instance as child) DefaultInstance targetInstance = new DefaultInstance(targetType, null); // search for the child named "GeographicalName" PropertyDefinition targetChildGeoName = Util.getChild("GeographicalName", targetType); // get type definition to create the "GeographicalName" instance TypeDefinition geoType = targetChildGeoName.getPropertyType(); // name/GeographicalName/ DefaultInstance geoInstance = new DefaultInstance(geoType, null); targetInstance.addProperty(targetChildGeoName.getName(), geoInstance); // name/GeographicalName/grammaticalGender/ if (gender != null && !gender.isEmpty()) { PropertyDefinition geoChildGramGender = Util.getChild("grammaticalGender", geoType); TypeDefinition grammarGenderType = geoChildGramGender.getPropertyType(); DefaultInstance grammarGenderInst = new DefaultInstance(grammarGenderType, null); grammarGenderInst.setValue(gender); geoInstance.addProperty(geoChildGramGender.getName(), grammarGenderInst); } // name/GeographicalName/grammaticalNumber if (number != null && !number.isEmpty()) { PropertyDefinition geoChildGramNumber = Util.getChild("grammaticalNumber", geoType); TypeDefinition grammarNumberType = geoChildGramNumber.getPropertyType(); DefaultInstance grammarNumberInst = new DefaultInstance(grammarNumberType, null); // set value of the grammaticalNumber instance grammarNumberInst.setValue(number); geoInstance.addProperty(geoChildGramNumber.getName(), grammarNumberInst); } // name/GeographicalName/language if (language != null && !language.isEmpty()) { PropertyDefinition geoChildLanguage = Util.getChild("language", geoType); TypeDefinition languageType = geoChildLanguage.getPropertyType(); DefaultInstance languageInstance = new DefaultInstance(languageType, null); // set value of the language instance languageInstance.setValue(language); geoInstance.addProperty(geoChildLanguage.getName(), languageInstance); } // name/GeographicalName/nameStatus if (nameStatus != null && !nameStatus.isEmpty()) { PropertyDefinition geoChildNameStatus = Util.getChild("nameStatus", geoType); TypeDefinition nameStatusType = geoChildNameStatus.getPropertyType(); DefaultInstance nameStatusInstance = new DefaultInstance(nameStatusType, null); // set value of the nameStatus instance nameStatusInstance.setValue(nameStatus); geoInstance.addProperty(geoChildNameStatus.getName(), nameStatusInstance); } // name/GeographicalName/nativeness if (nativeness != null && !nativeness.isEmpty()) { PropertyDefinition geoChildNativeness = Util.getChild("nativeness", geoType); TypeDefinition nativenessType = geoChildNativeness.getPropertyType(); DefaultInstance nativenessInstance = new DefaultInstance(nativenessType, null); // set value of the nativeness instance nativenessInstance.setValue(nativeness); geoInstance.addProperty(geoChildNativeness.getName(), nativenessInstance); } if ((ipa != null && !ipa.isEmpty()) || (sound != null && !sound.isEmpty())) { // name/GeographicalName/pronunciation PropertyDefinition geoChildPronun = Util.getChild("pronunciation", geoType); TypeDefinition pronunType = geoChildPronun.getPropertyType(); DefaultInstance pronunInstance = new DefaultInstance(pronunType, null); geoInstance.addProperty(geoChildPronun.getName(), pronunInstance); // name/GeographicalName/pronunciation/PronunciationOfName PropertyDefinition pronunChildPronOfName = Util.getChild("PronunciationOfName", pronunType); TypeDefinition pronOfNameType = pronunChildPronOfName.getPropertyType(); DefaultInstance pronOfNameInst = new DefaultInstance(pronOfNameType, null); pronunInstance.addProperty(pronunChildPronOfName.getName(), pronOfNameInst); if (ipa != null && !ipa.isEmpty()) { // name/GeographicalName/pronunciation/PronunciationOfName/pronunciationIPA PropertyDefinition pronOfNameChildIPA = Util.getChild("pronunciationIPA", pronOfNameType); TypeDefinition pronunIpaType = pronOfNameChildIPA.getPropertyType(); DefaultInstance pronunIpaInstance = new DefaultInstance(pronunIpaType, null); pronunIpaInstance.setValue(ipa); pronOfNameInst.addProperty(pronOfNameChildIPA.getName(), pronunIpaInstance); } if (sound != null && !sound.isEmpty()) { // name/GeographicalName/pronunciation/PronunciationOfName/pronunciationSoundLink PropertyDefinition pronOfNameChildSound = Util.getChild("pronunciationSoundLink", pronOfNameType); TypeDefinition pronunSoundType = pronOfNameChildSound.getPropertyType(); DefaultInstance pronunSoundInstance = new DefaultInstance(pronunSoundType, null); pronunSoundInstance.setValue(sound); pronOfNameInst.addProperty(pronOfNameChildSound.getName(), pronunSoundInstance); } } // name/GeographicalName/sourceOfName if (sourceOfName != null && !sourceOfName.isEmpty()) { PropertyDefinition geoChildSource = Util.getChild("sourceOfName", geoType); TypeDefinition sourceType = geoChildSource.getPropertyType(); DefaultInstance sourceInstance = new DefaultInstance(sourceType, null); // set value of the sourceOfName instance sourceInstance.setValue(sourceOfName); geoInstance.addProperty(geoChildSource.getName(), sourceInstance); } // name/GeographicalName/spelling PropertyDefinition geoChildSpelling = Util.getChild("spelling", geoType); TypeDefinition spellingType = geoChildSpelling.getPropertyType(); // name/GeographicalName/spelling/SpellingOfName PropertyDefinition spellingChildSpellOfName = Util.getChild("SpellingOfName", spellingType); TypeDefinition spellOfNameType = spellingChildSpellOfName.getPropertyType(); // create a "spelling" instance for each spelling for (int i = 0; i < scripts.size(); i++) { DefaultInstance spellingInstance = new DefaultInstance(spellingType, null); DefaultInstance spellOfNameInst = new DefaultInstance(spellOfNameType, null); // name/GeographicalName/spelling/SpellingOfName/script PropertyDefinition spellOfNameChildScript = Util.getChild("script", spellOfNameType); TypeDefinition scriptType = spellOfNameChildScript.getPropertyType(); DefaultInstance scriptInstance = new DefaultInstance(scriptType, null); // name/GeographicalName/spelling/SpellingOfName/text PropertyDefinition spellOfNameChildText = Util.getChild("text", spellOfNameType); // name/GeographicalName/spelling/SpellingOfName/transliterationScheme PropertyDefinition spellOfNameChildTransliteration = Util.getChild("transliterationScheme", spellOfNameType); TypeDefinition transliterationType = spellOfNameChildTransliteration.getPropertyType(); DefaultInstance transliterationInstance = new DefaultInstance(transliterationType, null); // build the spelling instance scriptInstance.setValue(scripts.get(i).as(String.class)); transliterationInstance.setValue(trans.get(i).as(String.class)); spellOfNameInst.addProperty(spellOfNameChildScript.getName(), scriptInstance); // set text value from inputs spellOfNameInst.addProperty(spellOfNameChildText.getName(), inputs.get(i).getValue()); spellOfNameInst.addProperty(spellOfNameChildTransliteration.getName(), transliterationInstance); spellingInstance.addProperty(spellingChildSpellOfName.getName(), spellOfNameInst); geoInstance.addProperty(geoChildSpelling.getName(), spellingInstance); } return targetInstance; }