Example usage for com.google.common.collect ImmutableListMultimap get

List of usage examples for com.google.common.collect ImmutableListMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableListMultimap get.

Prototype

@Override
public ImmutableList<V> get(@Nullable K key) 

Source Link

Document

Returns an immutable list of the values for the given key.

Usage

From source file:org.obiba.opal.web.gwt.app.client.magma.view.SummaryTabView.java

private void renderCategoricalSummary(SummaryStatisticsDto dto) {
    CategoricalSummaryDto categorical = dto
            .getExtension(CategoricalSummaryDto.SummaryStatisticsDtoExtensions.categorical).cast();

    final double[] totals = { 0d, 0d };
    ImmutableListMultimap<Boolean, FrequencyDto> categoriesByMissing = Multimaps.index(
            JsArrays.toIterable(categorical.getFrequenciesArray()), new Function<FrequencyDto, Boolean>() {
                @Nullable//from w w  w  . ja  va  2  s.  com
                @Override
                public Boolean apply(@Nullable FrequencyDto input) {
                    // when boolean, is missing is not set
                    if (input != null && !input.getMissing()) {
                        totals[0] += input.getFreq();
                        return false;
                    }

                    totals[1] += input == null ? 0 : input.getFreq();
                    return true;
                }
            });

    summary.add(new CategoricalSummaryView(dto.getResource(), categorical, categoriesByMissing.get(false),
            categoriesByMissing.get(true), totals[0], totals[1], categorical.getOtherFrequency()));
}

From source file:org.obiba.opal.web.gwt.app.client.magma.view.SummaryTabView.java

private void renderDefaultSummary(SummaryStatisticsDto dto) {
    DefaultSummaryDto defaultSummaryDto = dto
            .getExtension(DefaultSummaryDto.SummaryStatisticsDtoExtensions.defaultSummary).cast();

    final double[] totals = { 0d, 0d };
    ImmutableListMultimap<Boolean, FrequencyDto> valuesByMissing = Multimaps.index(
            JsArrays.toIterable(defaultSummaryDto.getFrequenciesArray()),
            new Function<FrequencyDto, Boolean>() {
                @Nullable/*w w w  .j a  v  a 2  s .  c  om*/
                @Override
                public Boolean apply(@Nullable FrequencyDto input) {
                    if (input != null && !input.getMissing()) {
                        input.setValue(translations.notEmpty());
                        totals[0] += input.getFreq();
                        return false;
                    }
                    totals[1] += input == null ? 0 : input.getFreq();
                    return true;
                }
            });

    summary.add(new DefaultSummaryView(defaultSummaryDto, valuesByMissing.get(false), valuesByMissing.get(true),
            totals[0], totals[1]));
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

@SuppressWarnings("resource") // Appendable is a StringBuilder.
private void reportMultipleBindingTypes(Deque<ResolvedRequest> path,
        ValidationReport.Builder<BindingGraph> reportBuilder) {
    ResolvedBindings resolvedBinding = path.peek().binding();
    StringBuilder builder = new StringBuilder();
    new Formatter(builder).format(ErrorMessages.MULTIPLE_BINDING_TYPES_FOR_KEY_FORMAT,
            keyFormatter.format(path.peek().request().key()));
    ImmutableListMultimap<BindingType, ContributionBinding> bindingsByType = ContributionBinding
            .bindingTypesFor(resolvedBinding.contributionBindings());
    for (BindingType type : Ordering.natural().immutableSortedCopy(bindingsByType.keySet())) {
        builder.append(INDENT);/*  www.  ja v a  2s . com*/
        builder.append(formatBindingType(type));
        builder.append(" bindings:\n");
        for (ContributionBinding binding : bindingsByType.get(type)) {
            builder.append(INDENT).append(INDENT);
            if (binding instanceof ProvisionBinding) {
                builder.append(provisionBindingFormatter.format((ProvisionBinding) binding));
            } else if (binding instanceof ProductionBinding) {
                builder.append(productionBindingFormatter.format((ProductionBinding) binding));
            }
            builder.append('\n');
        }
    }
    reportBuilder.addItem(builder.toString(), path.getLast().request().requestElement());
}

From source file:pl.llp.aircasting.view.presenter.MeasurementPresenter.java

private CopyOnWriteArrayList<Measurement> prepareFullView() {
    if (fullView != null)
        return fullView;

    Stopwatch stopwatch = new Stopwatch().start();

    String sensorName = sensor.getSensorName();
    MeasurementStream stream = sessionManager.getMeasurementStream(sensorName);
    Iterable<Measurement> measurements;
    if (stream == null) {
        measurements = newArrayList();/* www .  j  av  a 2  s. c  o  m*/
    } else {
        measurements = stream.getMeasurements();
    }

    ImmutableListMultimap<Long, Measurement> forAveraging = index(measurements,
            new Function<Measurement, Long>() {
                @Override
                public Long apply(Measurement measurement) {
                    return measurement.getSecond() / settingsHelper.getAveragingTime();
                }
            });

    Logger.logGraphPerformance("prepareFullView step 1 took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));

    ArrayList<Long> times = newArrayList(forAveraging.keySet());
    sort(times);

    Logger.logGraphPerformance("prepareFullView step 2 took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    List<Measurement> timeboxedMeasurements = newLinkedList();
    for (Long time : times) {
        ImmutableList<Measurement> chunk = forAveraging.get(time);
        timeboxedMeasurements.add(average(chunk));
    }

    Logger.logGraphPerformance("prepareFullView step 3 took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    CopyOnWriteArrayList<Measurement> result = Lists.newCopyOnWriteArrayList(timeboxedMeasurements);

    Logger.logGraphPerformance("prepareFullView step n took " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    fullView = result;
    return result;
}

From source file:edu.mit.streamjit.impl.compiler2.ActorArchetype.java

public void generateCode(String packageName, ModuleClassLoader loader, Iterable<WorkerActor> actors) {
    assert workMethods == null : "already generated code for " + this;
    //If we've removed all instances of this archetype, don't spin an empty class.
    if (Iterables.isEmpty(actors))
        return;/*from   w w  w  .  j a  va2 s . c om*/

    Module module = workerKlass.getParent();
    TypeFactory types = module.types();
    //We need to resolve work before making the state holder class so we
    //pick up its uses.
    Method oldWork = workerKlass.getMethodByVirtual("work",
            types.getMethodType(types.getVoidType(), types.getRegularType(workerKlass)));
    oldWork.resolve();

    Klass stateHolderKlass = makeStateHolderKlass(packageName);
    Klass archetypeKlass = new Klass(packageName + "." + workerKlass.getName() + "Archetype",
            module.getKlass(Object.class), ImmutableList.<Klass>of(), module);
    archetypeKlass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));

    Map<Pair<Class<?>, Class<?>>, Method> methods = new HashMap<>();
    for (WorkerActor a : actors) {
        Class<?> inputType = a.inputType().getRawType(), outputType = a.outputType().getRawType();
        Pair<Class<?>, Class<?>> key = new Pair<Class<?>, Class<?>>(inputType, outputType);
        if (methods.containsKey(key))
            continue;

        //We modify rwork while remapping so we need a fresh clone.
        Method rwork = makeRwork(archetypeKlass, stateHolderKlass);
        for (BasicBlock b : rwork.basicBlocks())
            for (Instruction i : ImmutableList.copyOf(b.instructions()))
                if (i.operands().contains(rwork.arguments().get(0)) ||
                //TODO: also check for superclass fields
                        i.operands().anyMatch(Predicates.<Value>in(workerKlass.fields())))
                    remapEliminatingReceiver(i, inputType, outputType, stateHolderKlass);

        assert rwork.arguments().get(0).uses().isEmpty();
        Method work = new Method(makeWorkMethodName(inputType, outputType), rwork.getType().dropFirstArgument(),
                EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), archetypeKlass);
        Map<Value, Value> vmap = new IdentityHashMap<>();
        vmap.put(rwork.arguments().get(0), null);
        for (int i = 1; i < rwork.arguments().size(); ++i)
            vmap.put(rwork.arguments().get(i), work.arguments().get(i - 1));
        Cloning.cloneMethod(rwork, work, vmap);
        cleanWorkMethod(work);
        methods.put(key, work);
        rwork.eraseFromParent();
    }

    ImmutableMap.Builder<Pair<Class<?>, Class<?>>, MethodHandle> workMethodsBuilder = ImmutableMap.builder();
    try {
        Class<?> stateHolderClass = loader.loadClass(stateHolderKlass.getName());
        this.constructStateHolder = findConstructor(stateHolderClass);
        Class<?> archetypeClass = loader.loadClass(archetypeKlass.getName());
        ImmutableListMultimap<String, java.lang.reflect.Method> methodsByName = Multimaps
                .index(Arrays.asList(archetypeClass.getMethods()), java.lang.reflect.Method::getName);
        for (Pair<Class<?>, Class<?>> p : methods.keySet()) {
            String name = makeWorkMethodName(p.first, p.second);
            workMethodsBuilder.put(p,
                    MethodHandles.publicLookup().unreflect(Iterables.getOnlyElement(methodsByName.get(name))));
        }
    } catch (ClassNotFoundException | IllegalAccessException ex) {
        throw new AssertionError(ex);
    }
    this.workMethods = workMethodsBuilder.build();
}

From source file:org.apache.usergrid.apm.service.StatelessComplexEventProcessingService.java

public void calculateSummarySessionMetrics2(Long appId, String fullAppName,
        List<ClientSessionMetrics> clientSessionMetrics, List<SummarySessionMetrics> dirtySummarySessionMetrics,
        Set<Long> modifiedMinutes) {

    // Empty metrics checker = should not be happening in production
    if (clientSessionMetrics.size() == 0) {
        log.error(//from   w  w  w .  jav a  2 s .  com
                "Something is very odd. Skipping Summary Session Metrics calculation since there is no clientSessionMetrics for app : "
                        + fullAppName);
        return;
    }

    /*For the purpose of backwards compatibility, if sessionId is null, then setting the session id to something meaningful
            
    for(ClientSessionMetrics csm: clientSessionMetrics)
    {
       if(csm.getSessionId() == null && csm.getDeviceId() != null)
       {
    log.warn("Encountered metrics data for appId " +  appId + " where sessionId was not populated. This indicates potentially usage of an old client : " + csm.getDeviceId() );
    String fakeSessionId = csm.getDeviceId().toString() + "_" + csm.getEndHour().toString();
    csm.setSessionId(fakeSessionId);
       }
    } */

    // Group Client Session metrics by sessionId since there could be different messgaes from same device for the same session
    Function<ClientSessionMetrics, String> sessionFunction = new Function<ClientSessionMetrics, String>() {
        @Override
        public String apply(@Nullable ClientSessionMetrics arg0) {
            return arg0.getSessionId();
        }

    };

    ImmutableListMultimap<String, ClientSessionMetrics> csmBySessionId = Multimaps.index(clientSessionMetrics,
            sessionFunction);

    // 2. For each CSM grouping, find CSM with latest timestamp.
    Comparator<ClientSessionMetrics> endMinuteComparator = new Comparator<ClientSessionMetrics>() {
        @Override
        public int compare(ClientSessionMetrics csm0, ClientSessionMetrics csm1) {
            return csm0.getEndMinute().compareTo(csm1.getEndMinute());

        }
    };

    Map<String, ClientSessionMetrics> latestCSM = new HashMap<String, ClientSessionMetrics>();

    for (String sessionId : csmBySessionId.keySet()) {
        ClientSessionMetrics latestClientSessionMetric = Collections.max(csmBySessionId.get(sessionId),
                endMinuteComparator);
        latestCSM.put(sessionId, latestClientSessionMetric);
    }

    //3. Query DB for matching Sessions. 
    //TODO: This potentially could be slow for a high volume app. Need to investigate better approach
    log.info("Querying summary session table for appId " + fullAppName + " for "
            + csmBySessionId.keySet().size() + " sessions");
    List<SummarySessionMetrics> matchingSSM = sessionDBService.getSummarySessionsBySessionId(appId,
            csmBySessionId.keySet());
    log.info("Found " + matchingSSM.size() + " pre-existing sessions in database for app " + fullAppName);

    //      4a. If no match exists, create a new summary session
    //      4b.   If match exists, but match's end time >= to the end time of the CSM being ingested, do nothing
    //      4c.   If the match exists, and the match's end time < to the end time of the CSM being ingested, extend the session.

    // Group Summary Session metrics by sessionId
    //Todo : since matchingSSM has distinct summarySessions, following function may not be needed..confirm
    Function<SummarySessionMetrics, String> sessionFunction2 = new Function<SummarySessionMetrics, String>() {
        @Override
        public String apply(@Nullable SummarySessionMetrics arg0) {
            return arg0.getSessionId();
        }

    };

    ImmutableListMultimap<String, SummarySessionMetrics> ssmBySessionId = Multimaps.index(matchingSSM,
            sessionFunction2);

    //ssmBySessionId.keySet();

    //Find new Sessions
    Set<String> newSessions = Sets.difference(latestCSM.keySet(), ssmBySessionId.keySet());
    log.info("Found " + newSessions.size() + " new sessions for app " + fullAppName);
    //Create new SSM

    for (String sessionId : newSessions) {
        SummarySessionMetrics ssm = createSummarySessionMetrics(latestCSM.get(sessionId));
        modifiedMinutes.add(ssm.getEndMinute());
        dirtySummarySessionMetrics.add(ssm);
    }

    //Update SSM
    for (SummarySessionMetrics ssm : matchingSSM) {
        if (latestCSM.containsKey(ssm.getSessionId())) {
            if (latestCSM.get(ssm.getSessionId()).getEndMinute() > ssm.getEndMinute()) {
                ssm.setPrevSessionEndTime(ssm.getSessionEndTime());
                ssm.setSessionEndTime(latestCSM.get(ssm.getSessionId()).getTimeStamp());
                ssm.setEndBatteryLevel(latestCSM.get(ssm.getSessionId()).getBatteryLevel());
                addModifiedMinutes(modifiedMinutes, ssm);
                dirtySummarySessionMetrics.add(ssm);
            } else {
                log.warn("Got a message that was out of order or the data"
                        + "has been within the same minute for app " + ssm.getFullAppName() + " and SessiondId "
                        + ssm.getSessionId());
            }
        } else {
            log.warn("Matching Summary Session Metrics didn't actually find a match for app "
                    + ssm.getFullAppName() + " SessionId :" + ssm.getSessionId());
        }
    }

}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        ModelSchemaStore store, final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (isTarget(type)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*from w w w . j a  v  a2 s.c o  m*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        final ModelSchema<R> schema = createSchema(extractionContext, store, type, properties, concreteClass);
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.facebook.buck.maven.Publisher.java

public ImmutableSet<DeployResult> publish(ImmutableSet<MavenPublishable> publishables)
        throws DeploymentException {
    ImmutableListMultimap<UnflavoredBuildTarget, UnflavoredBuildTarget> duplicateBuiltinBuileRules = checkForDuplicatePackagedDeps(
            publishables);/* w ww .  j  a  va  2 s .co m*/
    if (duplicateBuiltinBuileRules.size() > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("Duplicate transitive dependencies for publishable libraries found!  This means");
        sb.append(StandardSystemProperty.LINE_SEPARATOR);
        sb.append("that the following libraries would have multiple copies if these libraries were");
        sb.append(StandardSystemProperty.LINE_SEPARATOR);
        sb.append("used together.  The can be resolved by adding a maven URL to each target listed");
        sb.append(StandardSystemProperty.LINE_SEPARATOR);
        sb.append("below:");
        for (UnflavoredBuildTarget unflavoredBuildTarget : duplicateBuiltinBuileRules.keySet()) {
            sb.append(StandardSystemProperty.LINE_SEPARATOR);
            sb.append(unflavoredBuildTarget.getFullyQualifiedName());
            sb.append(" (referenced by these build targets: ");
            Joiner.on(", ").appendTo(sb, duplicateBuiltinBuileRules.get(unflavoredBuildTarget));
            sb.append(")");
        }
        throw new DeploymentException(sb.toString());
    }

    ImmutableSet.Builder<DeployResult> deployResultBuilder = ImmutableSet.builder();
    for (MavenPublishable publishable : publishables) {
        DefaultArtifact coords = new DefaultArtifact(
                Preconditions.checkNotNull(publishable.getMavenCoords().get(),
                        "No maven coordinates specified for published rule ", publishable));
        Path relativePathToOutput = Preconditions.checkNotNull(publishable.getPathToOutput(),
                "No path to output present in ", publishable);
        File mainItem = publishable.getProjectFilesystem().resolve(relativePathToOutput).toFile();

        if (!coords.getClassifier().isEmpty()) {
            deployResultBuilder.add(publish(coords, ImmutableList.of(mainItem)));
        }

        try {
            // If this is the "main" artifact (denoted by lack of classifier) generate and publish
            // pom alongside
            File pom = Pom.generatePomFile(publishable).toFile();
            deployResultBuilder.add(publish(coords, ImmutableList.of(mainItem, pom)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return deployResultBuilder.build();
}

From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*ww  w. ja  v  a  2  s  . com*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.opengamma.strata.measure.fxopt.BlackFxOptionSmileVolatilitiesSpecification.java

@Override
public BlackFxOptionSmileVolatilities volatilities(ZonedDateTime valuationDateTime, DoubleArray parameters,
        ReferenceData refData) {/*from   w  w w  .j a va2  s  .c  o  m*/

    ArgChecker.isTrue(parameters.size() == getParameterCount(), Messages
            .format("Size of parameters must be {}, but found {}", getParameterCount(), parameters.size()));
    ImmutableListMultimap.Builder<Tenor, Pair<FxOptionVolatilitiesNode, Double>> builder = ImmutableListMultimap
            .builder();
    for (Tenor tenor : nodesByTenor.keys()) {
        ImmutableList<Pair<FxOptionVolatilitiesNode, Double>> nodesAndQuotes = nodesByTenor.get(tenor).stream()
                .map(node -> Pair.of(node, parameters.get(nodes.indexOf(node)))).collect(toImmutableList());
        builder.putAll(tenor, nodesAndQuotes);
    }
    ImmutableListMultimap<Tenor, Pair<FxOptionVolatilitiesNode, Double>> nodesAndQuotesByTenor = builder
            .build();

    List<Tenor> tenors = new ArrayList<>(nodesByTenor.keySet());
    Collections.sort(tenors);
    int nTenors = tenors.size();
    int nDeltas = deltas.size();

    double[] expiries = new double[nTenors];
    double[] atm = new double[nTenors];
    double[][] rr = new double[nTenors][nDeltas];
    double[][] str = new double[nTenors][nDeltas];
    for (int i = 0; i < nTenors; ++i) {
        parametersForPeriod(valuationDateTime, nodesAndQuotesByTenor.get(tenors.get(i)), i, expiries, atm, rr,
                str, refData);
    }
    InterpolatedStrikeSmileDeltaTermStructure smiles = InterpolatedStrikeSmileDeltaTermStructure.of(
            DoubleArray.copyOf(expiries), DoubleArray.copyOf(deltas.subList(0, nDeltas)),
            DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), dayCount,
            timeInterpolator, timeExtrapolatorLeft, timeExtrapolatorRight, strikeInterpolator,
            strikeExtrapolatorLeft, strikeExtrapolatorRight);

    return BlackFxOptionSmileVolatilities.of(name, currencyPair, valuationDateTime, smiles);
}