Example usage for com.google.common.base Functions compose

List of usage examples for com.google.common.base Functions compose

Introduction

In this page you can find the example usage for com.google.common.base Functions compose.

Prototype

public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) 

Source Link

Document

Returns the composition of two functions.

Usage

From source file:org.decisiondeck.jlp.problem.LpProblemImpl.java

@Override
public void setConstraintsNamer(Function<LpConstraint<T>, String> namer) {
    if (namer == null) {
        m_constraintNamer = new DefaultConstraintNamer<T>();
    } else {//from  w  w  w . j  a  v  a2  s. c  om
        final Function<String, String> nullToEmptyString = new Function<String, String>() {
            @Override
            public String apply(String input) {
                return Strings.nullToEmpty(input);
            }
        };
        m_constraintNamer = Functions.compose(nullToEmptyString, namer);
    }
}

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

/**
 * Writes out a builder for a component or subcomponent.
 *
 * @param input the component or subcomponent
 * @param componentApiName the API name of the component we're building (not our impl)
 * @param componentImplName the implementation name of the component we're building
 * @param componentWriter the class we're adding this builder to
 * @param componentContributionFields a map of member selects so we can later use the fields
 *//*from   www . jav a  2s .c o m*/
private ClassWriter writeBuilder(BindingGraph input, ClassName componentApiName, ClassName componentImplName,
        ClassWriter componentWriter, Map<TypeElement, MemberSelect> componentContributionFields) {
    ClassWriter builderWriter;
    Optional<BuilderSpec> builderSpec = input.componentDescriptor().builderSpec();
    switch (input.componentDescriptor().kind()) {
    case COMPONENT:
    case PRODUCTION_COMPONENT:
        builderWriter = componentWriter.addNestedClass("Builder");
        builderWriter.addModifiers(STATIC);

        // Only top-level components have the factory builder() method.
        // Mirror the user's builder API type if they had one.
        MethodWriter builderFactoryMethod = builderSpec.isPresent()
                ? componentWriter.addMethod(builderSpec.get().builderDefinitionType().asType(), "builder")
                : componentWriter.addMethod(builderWriter, "builder");
        builderFactoryMethod.addModifiers(PUBLIC, STATIC);
        builderFactoryMethod.body().addSnippet("return new %s();", builderWriter.name());
        break;
    case SUBCOMPONENT:
        verify(builderSpec.isPresent()); // we only write subcomponent builders if there was a spec
        builderWriter = componentWriter.addNestedClass(componentApiName.simpleName() + "Builder");
        break;
    default:
        throw new IllegalStateException();
    }
    builderWriter.addModifiers(FINAL);
    builderWriter.addConstructor().addModifiers(PRIVATE);
    if (builderSpec.isPresent()) {
        builderWriter.addModifiers(PRIVATE);
        TypeElement builderType = builderSpec.get().builderDefinitionType();
        switch (builderType.getKind()) {
        case CLASS:
            builderWriter.setSuperType(builderType);
            break;
        case INTERFACE:
            builderWriter.addImplementedType(builderType);
            break;
        default:
            throw new IllegalStateException("not a class or interface: " + builderType);
        }
    } else {
        builderWriter.addModifiers(PUBLIC);
    }

    // the full set of types that calling code uses to construct a component instance
    ImmutableMap<TypeElement, String> componentContributionNames = ImmutableMap
            .copyOf(Maps.asMap(
                    Sets.union(
                            Sets.union(input.transitiveModules().keySet(),
                                    input.componentDescriptor().dependencies()),
                            input.componentDescriptor().executorDependency().asSet()),
                    Functions.compose(CaseFormat.UPPER_CAMEL.converterTo(LOWER_CAMEL),
                            new Function<TypeElement, String>() {
                                @Override
                                public String apply(TypeElement input) {
                                    return input.getSimpleName().toString();
                                }
                            })));

    MethodWriter buildMethod;
    if (builderSpec.isPresent()) {
        ExecutableElement specBuildMethod = builderSpec.get().buildMethod();
        // Note: we don't use the specBuildMethod.getReturnType() as the return type
        // because it might be a type variable.  We make use of covariant returns to allow
        // us to return the component type, which will always be valid.
        buildMethod = builderWriter.addMethod(componentApiName, specBuildMethod.getSimpleName().toString());
        buildMethod.annotate(Override.class);
    } else {
        buildMethod = builderWriter.addMethod(componentApiName, "build");
    }
    buildMethod.addModifiers(PUBLIC);

    for (Entry<TypeElement, String> entry : componentContributionNames.entrySet()) {
        TypeElement contributionElement = entry.getKey();
        String contributionName = entry.getValue();
        FieldWriter builderField = builderWriter.addField(contributionElement, contributionName);
        builderField.addModifiers(PRIVATE);
        componentContributionFields.put(contributionElement, MemberSelect.instanceSelect(componentImplName,
                Snippet.format("builder.%s", builderField.name())));
        if (componentCanMakeNewInstances(contributionElement)) {
            buildMethod.body().addSnippet("if (%s == null) {", builderField.name())
                    .addSnippet("  this.%s = new %s();", builderField.name(),
                            ClassName.fromTypeElement(contributionElement))
                    .addSnippet("}");
        } else {
            buildMethod.body().addSnippet("if (%s == null) {", builderField.name())
                    .addSnippet("  throw new IllegalStateException(\"%s must be set\");", builderField.name())
                    .addSnippet("}");
        }
        MethodWriter builderMethod;
        boolean returnsVoid = false;
        if (builderSpec.isPresent()) {
            ExecutableElement method = builderSpec.get().methodMap().get(contributionElement);
            if (method == null) { // no method in the API, nothing to write out.
                continue;
            }
            // If the return type is void, we add a method with the void return type.
            // Otherwise we use the builderWriter and take advantage of covariant returns
            // (so that we don't have to worry about setter methods that return type variables).
            if (method.getReturnType().getKind().equals(TypeKind.VOID)) {
                returnsVoid = true;
                builderMethod = builderWriter.addMethod(method.getReturnType(),
                        method.getSimpleName().toString());
            } else {
                builderMethod = builderWriter.addMethod(builderWriter, method.getSimpleName().toString());
            }
            builderMethod.annotate(Override.class);
        } else {
            builderMethod = builderWriter.addMethod(builderWriter, contributionName);
        }
        // TODO(gak): Mirror the API's visibility.
        // (Makes no difference to the user since this class is private,
        //  but makes generated code prettier.)
        builderMethod.addModifiers(PUBLIC);
        builderMethod.addParameter(contributionElement, contributionName);
        builderMethod.body().addSnippet("if (%s == null) {", contributionName)
                .addSnippet("  throw new NullPointerException(%s);", StringLiteral.forValue(contributionName))
                .addSnippet("}").addSnippet("this.%s = %s;", builderField.name(), contributionName);
        if (!returnsVoid) {
            builderMethod.body().addSnippet("return this;");
        }
    }
    buildMethod.body().addSnippet("return new %s(this);", componentImplName);
    return builderWriter;
}

From source file:edu.buaa.satla.analysis.core.predicate.PredicatePrecision.java

static ListMultimap<String, AbstractionPredicate> mergePredicatesPerFunction(
        Multimap<Pair<CFANode, Integer>, AbstractionPredicate> newPredicates) {

    return transformAndMergeKeys(newPredicates,
            Functions.compose(CFAUtils.GET_FUNCTION, Pair.<CFANode>getProjectionToFirst()));
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.elements.Message.java

/**
 * Get the surrounded reflexives message depth.
 * // ww  w  .j  a va  2  s . c om
 * @return the surrounded reflexives message depth.
 */
public int getReflexiveMessageWidth() {
    Collection<ISequenceEvent> events = getSurroundedSameLifelineEvents();
    final Range range = getVerticalRange();
    Predicate<ISequenceEvent> toConsider = new Predicate<ISequenceEvent>() {
        @Override
        public boolean apply(ISequenceEvent input) {
            boolean toConsider = range.includes(input.getVerticalRange());
            if (input instanceof Message) {
                toConsider = toConsider && ((Message) input).isReflective();
            }
            return toConsider;
        }
    };

    List<ISequenceEvent> impactingEvents = Lists.newArrayList(Iterables.filter(events, toConsider));
    Collections.sort(impactingEvents, Ordering.natural()
            .onResultOf(Functions.compose(RangeHelper.lowerBoundFunction(), ISequenceEvent.VERTICAL_RANGE)));
    int subMessagesMaxRight = 0;
    for (Message msg : Iterables.filter(impactingEvents, Message.class)) {
        int reflexiveMessageWidth = msg.getReflexiveMessageWidth();
        int origin = msg.getSourceElement().getProperLogicalBounds().right();
        origin = Math.max(origin, msg.getTargetElement().getProperLogicalBounds().right());
        subMessagesMaxRight = Math.max(subMessagesMaxRight, origin + reflexiveMessageWidth);
    }

    int maxRight = 0;
    for (AbstractNodeEvent node : Iterables.filter(impactingEvents, AbstractNodeEvent.class)) {
        maxRight = Math.max(maxRight, node.getProperLogicalBounds().right());
    }

    int origin = getSourceElement().getProperLogicalBounds().right();
    origin = Math.max(origin, getTargetElement().getProperLogicalBounds().right());

    int width = LayoutConstants.MESSAGE_TO_SELF_BENDPOINT_HORIZONTAL_GAP;
    width = Math.max(width, maxRight - origin + LayoutConstants.MESSAGE_TO_SELF_HORIZONTAL_GAP);
    width = Math.max(width, subMessagesMaxRight - origin + LayoutConstants.MESSAGE_TO_SELF_HORIZONTAL_GAP);

    return width;
}

From source file:org.opencms.workplace.tools.modules.CmsCloneModuleThread.java

/**
 * Adjusts the module configuration file and the formatter configurations.<p>
 *
 * @param targetModule the target module
 * @param resTypeMap the resource type mapping
 *
 * @throws CmsException if something goes wrong
 * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding
 *///from  www .  j a v a2 s .c  o m
private void adjustConfigs(CmsModule targetModule, Map<I_CmsResourceType, I_CmsResourceType> resTypeMap)
        throws CmsException, UnsupportedEncodingException {

    String modPath = CmsWorkplace.VFS_PATH_MODULES + targetModule.getName() + "/";
    CmsObject cms = getCms();
    if (((m_cloneInfo.getSourceNamePrefix() != null) && (m_cloneInfo.getTargetNamePrefix() != null))
            || !m_cloneInfo.getSourceNamePrefix().equals(m_cloneInfo.getTargetNamePrefix())) {
        // replace resource type names in formatter configurations
        List<CmsResource> resources = cms.readResources(modPath, CmsResourceFilter.requireType(OpenCms
                .getResourceManager().getResourceType(CmsFormatterConfigurationCache.TYPE_FORMATTER_CONFIG)));
        String source = "<Type><!\\[CDATA\\[" + m_cloneInfo.getSourceNamePrefix();
        String target = "<Type><!\\[CDATA\\[" + m_cloneInfo.getTargetNamePrefix();
        Function<String, String> replaceType = new ReplaceAll(source, target);

        for (CmsResource resource : resources) {
            transformResource(resource, replaceType);
        }
        resources.clear();
    }

    // replace resource type names in module configuration
    try {
        CmsResource config = cms.readResource(modPath + CmsADEManager.CONFIG_FILE_NAME, CmsResourceFilter
                .requireType(OpenCms.getResourceManager().getResourceType(CmsADEManager.MODULE_CONFIG_TYPE)));
        Function<String, String> substitution = Functions.identity();
        // compose the substitution functions from simple substitution functions for each type

        for (Map.Entry<I_CmsResourceType, I_CmsResourceType> mapping : resTypeMap.entrySet()) {
            substitution = Functions.compose(
                    new ReplaceAll(mapping.getKey().getTypeName(), mapping.getValue().getTypeName()),
                    substitution);
        }

        // Either replace prefix in or prepend it to the folder name value

        Function<String, String> replaceFolderName = new ReplaceAll(
                "(<Folder>[ \n]*<Name><!\\[CDATA\\[)(" + m_cloneInfo.getSourceNamePrefix() + ")?",
                "$1" + m_cloneInfo.getTargetNamePrefix());
        substitution = Functions.compose(replaceFolderName, substitution);
        transformResource(config, substitution);
    } catch (CmsVfsResourceNotFoundException e) {
        LOG.info(e.getLocalizedMessage(), e);
    }
}

From source file:com.clarkparsia.empire.codegen.BeanGenerator.java

/**
 * Given an ontology/schema, generate Empire compatible Java beans for each class in the ontology.
 * @param thePackageName the name of the packages the source should belong to
 * @param theOntology the location of the ontology to load
 * @param theFormat the RDF format the ontology is in
 * @param theDirToSave where to save the generated source code
 * @throws Exception if there is an error while generating the source
 *//* w w  w .  j a v a  2  s  .  c  o m*/
public static void generateSourceFiles(String thePackageName, URL theOntology, RDFFormat theFormat,
        File theDirToSave) throws Exception {
    NAMES_TO_COUNT.clear();

    Repository aRepository = Repositories.createInMemoryRepo();

    Repositories.add(aRepository, theOntology.openStream(), theFormat);

    Collection<Resource> aClasses = Sets.newHashSet(Iterators.transform(new MultiIterator<Statement>(
            AdunaIterations.iterator(Repositories.getStatements(aRepository, null, RDF.TYPE, RDFS.CLASS)),
            AdunaIterations.iterator(Repositories.getStatements(aRepository, null, RDF.TYPE, OWL.CLASS))),
            new StatementToSubject()));

    aClasses = Collections2.filter(aClasses, new Predicate<Resource>() {
        public boolean apply(Resource theRes) {
            return theRes instanceof URI;
        }
    });

    Collection<Resource> aIndClasses = Sets.newHashSet(Iterators.transform(
            AdunaIterations.iterator(Repositories.getStatements(aRepository, null, RDF.TYPE, null)),
            Functions.compose(Functions2.<Value, Resource>cast(Resource.class), new StatementToObject())));

    aClasses.addAll(aIndClasses);

    aClasses = Collections2.filter(aClasses, new Predicate<Resource>() {
        public boolean apply(final Resource theValue) {
            return !theValue.stringValue().startsWith(RDFS.NAMESPACE)
                    && !theValue.stringValue().startsWith(RDF.NAMESPACE)
                    && !theValue.stringValue().startsWith(OWL.NAMESPACE);
        }
    });

    Map<Resource, Collection<URI>> aMap = new HashMap<Resource, Collection<URI>>();

    for (Resource aClass : aClasses) {
        if (aClass instanceof BNode) {
            continue;
        }
        Collection<URI> aProps = Sets.newHashSet(Iterators.transform(
                AdunaIterations.iterator(Repositories.getStatements(aRepository, null, RDFS.DOMAIN, aClass)),
                Functions.compose(Functions2.<Resource, URI>cast(URI.class), new StatementToSubject())));

        // infer properties based on usage in actual instance data
        for (BindingSet aBinding : AdunaIterations.iterable(Repositories.selectQuery(aRepository,
                QueryLanguage.SPARQL, "select distinct ?p where { ?s rdf:type <" + aClass + ">. ?s ?p ?o }"))) {
            aProps.add((URI) aBinding.getValue("p"));
        }

        // don't include rdf:type as a property
        aProps = Collections2.filter(aProps, new Predicate<URI>() {
            public boolean apply(final URI theValue) {
                return !RDF.TYPE.equals(theValue);
            }
        });

        aMap.put(aClass, aProps);
    }

    if (!theDirToSave.exists()) {
        if (!theDirToSave.mkdirs()) {
            throw new IOException("Could not create output directory");
        }
    }

    for (Resource aClass : aMap.keySet()) {
        String aSrc = toSource(thePackageName, aRepository, aClass, aMap);

        if (aSrc == null) {
            continue;
        }

        File aFile = new File(theDirToSave, className(aClass) + ".java");

        System.out.println("Writing source to file: " + aFile.getName());

        Files.write(aSrc, aFile, Charsets.UTF_8);
    }
}

From source file:com.eucalyptus.ws.util.HmacUtils.java

private static Function<String, List<String>> forMap(final Map<String, List<String>> values,
        Function<String, String> keyConversion) {
    return Functions.compose(Functions.forMap(values, Collections.<String>emptyList()), keyConversion);
}

From source file:com.twitter.aurora.scheduler.state.TaskStateMachine.java

/**
 * Attempt to transition the state machine to the provided state.
 * At the time this method returns, any work commands required to satisfy the state transition
 * will be appended to the work queue./*from w  ww  .  jav  a 2  s  .c om*/
 *
 * @param status Status to apply to the task.
 * @param auditMessage The audit message to associate with the transition.
 * @param mutation Mutate operation to perform while updating the task.
 * @return {@code true} if the state change was allowed, {@code false} otherwise.
 */
public synchronized boolean updateState(final ScheduleStatus status,
        Function<IScheduledTask, IScheduledTask> mutation, final Optional<String> auditMessage) {

    checkNotNull(status);
    checkNotNull(mutation);
    checkNotNull(auditMessage);

    /**
     * Don't bother applying noop state changes.  If we end up modifying task state without a
     * state transition (e.g. storing resource consumption of a running task), we need to find
     * a different way to suppress noop transitions.
     */
    if (stateMachine.getState().getState() != status) {
        Function<IScheduledTask, IScheduledTask> operation = Functions.compose(mutation,
                new Function<IScheduledTask, IScheduledTask>() {
                    @Override
                    public IScheduledTask apply(IScheduledTask task) {
                        ScheduledTask builder = task.newBuilder();
                        builder.addToTaskEvents(new TaskEvent().setTimestamp(clock.nowMillis())
                                .setStatus(status).setMessage(auditMessage.orNull())
                                .setScheduler(LOCAL_HOST_SUPPLIER.get()));
                        return IScheduledTask.build(builder);
                    }
                });
        return stateMachine.transition(State.create(status, operation));
    }

    return false;
}

From source file:com.eucalyptus.compute.common.internal.tags.FilterSupport.java

private static <T> Function<? super String, Predicate<? super T>> explodedLiteralFilter(
        final Function<? super T, ?> extractor, final Function<String, Collection> explodeFunction) {
    return new Function<String, Predicate<? super T>>() {
        @SuppressWarnings("unchecked")
        @Override/*from w ww . jav a2  s  . com*/
        public Predicate<T> apply(final String filterValue) {
            Collection values = explodeFunction.apply(filterValue);
            return values == null ? Predicates.<T>alwaysTrue()
                    : Predicates.compose(Predicates.<Object>in(values),
                            Functions.compose(extractor, Functions.<T>identity()));
        }
    };
}

From source file:com.eucalyptus.compute.common.internal.tags.FilterSupport.java

private static <T> Function<? super String, Predicate<? super T>> stringFilter(
        final Function<? super T, String> extractor) {
    return stringSetFilter(Functions.compose(FilterSupport.<String>toSet(), extractor));
}