Example usage for com.google.common.base Function getClass

List of usage examples for com.google.common.base Function getClass

Introduction

In this page you can find the example usage for com.google.common.base Function getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.eucalyptus.util.TypeMappers.java

private static void registerMapper(Class from, Class to, Function mapper) {
    EventRecord/*  ww w  . j  a  va2 s  .  co  m*/
            .here(TypeMapperDiscovery.class, EventType.BOOTSTRAP_INIT_DISCOVERY, "mapper",
                    from.getCanonicalName(), to.getCanonicalName(), mapper.getClass().getCanonicalName())
            .info();
    String key = Joiner.on("=>").join(from, to);
    checkParam(knownMappers.get(from), not(hasItem(to)));
    checkParam(mappers, not(hasKey(key)));
    knownMappers.put(from, to);
    mappers.put(key, mapper);

}

From source file:org.apache.tajo.engine.function.FunctionLoader.java

/**
 * This method finds and build FunctionDesc for the legacy function and UD(A)F system.
 *
 * @return A list of FunctionDescs/*from  w w w  .  ja  va  2  s .c o  m*/
 */
public static List<FunctionDesc> findLegacyFunctions() {
    List<FunctionDesc> sqlFuncs = new ArrayList<>();

    Set<Class> functionClasses = ClassUtil.findClasses(Function.class, "org.apache.tajo.engine.function");

    for (Class eachClass : functionClasses) {
        if (eachClass.isInterface() || Modifier.isAbstract(eachClass.getModifiers())) {
            continue;
        }
        Function function = null;
        try {
            function = (Function) eachClass.newInstance();
        } catch (Exception e) {
            LOG.warn(eachClass + " cannot instantiate Function class because of " + e.getMessage(), e);
            continue;
        }
        String functionName = function.getClass().getAnnotation(Description.class).functionName();
        String[] synonyms = function.getClass().getAnnotation(Description.class).synonyms();
        String description = function.getClass().getAnnotation(Description.class).description();
        String detail = function.getClass().getAnnotation(Description.class).detail();
        String example = function.getClass().getAnnotation(Description.class).example();
        TajoDataTypes.Type returnType = function.getClass().getAnnotation(Description.class).returnType();
        ParamTypes[] paramArray = function.getClass().getAnnotation(Description.class).paramTypes();

        String[] allFunctionNames = null;
        if (synonyms != null && synonyms.length > 0) {
            allFunctionNames = new String[1 + synonyms.length];
            allFunctionNames[0] = functionName;
            System.arraycopy(synonyms, 0, allFunctionNames, 1, synonyms.length);
        } else {
            allFunctionNames = new String[] { functionName };
        }

        for (String eachFunctionName : allFunctionNames) {
            for (ParamTypes params : paramArray) {
                ParamOptionTypes[] paramOptionArray;
                if (params.paramOptionTypes() == null
                        || params.paramOptionTypes().getClass().getAnnotation(ParamTypes.class) == null) {
                    paramOptionArray = new ParamOptionTypes[0];
                } else {
                    paramOptionArray = params.paramOptionTypes().getClass().getAnnotation(ParamTypes.class)
                            .paramOptionTypes();
                }

                TajoDataTypes.Type[] paramTypes = params.paramTypes();
                if (paramOptionArray.length > 0)
                    paramTypes = params.paramTypes().clone();

                for (int i = 0; i < paramOptionArray.length + 1; i++) {
                    FunctionDesc functionDesc = new FunctionDesc(eachFunctionName, function.getClass(),
                            function.getFunctionType(), CatalogUtil.newSimpleDataType(returnType),
                            paramTypes.length == 0 ? CatalogUtil.newSimpleDataTypeArray()
                                    : CatalogUtil.newSimpleDataTypeArray(paramTypes));

                    functionDesc.setDescription(description);
                    functionDesc.setExample(example);
                    functionDesc.setDetail(detail);
                    sqlFuncs.add(functionDesc);

                    if (i != paramOptionArray.length) {
                        paramTypes = new TajoDataTypes.Type[paramTypes.length
                                + paramOptionArray[i].paramOptionTypes().length];
                        System.arraycopy(params.paramTypes(), 0, paramTypes, 0, paramTypes.length);
                        System.arraycopy(paramOptionArray[i].paramOptionTypes(), 0, paramTypes,
                                paramTypes.length, paramOptionArray[i].paramOptionTypes().length);
                    }
                }
            }
        }
    }

    return sqlFuncs;
}

From source file:org.jclouds.azure.storage.blob.blobstore.internal.BaseAzureBlobStore.java

protected <F, T> Future<T> wrapFuture(Future<? extends F> future, Function<F, T> function) {
    return new FutureFunctionWrapper<F, T>(future, function,
            logFactory.getLogger(function.getClass().getName()));
}

From source file:org.eiichiro.bootleg.Pipeline.java

/**
 * Sets the specified {@code Function} to the next processing stage with the 
 * specified index and the class name of the {@code Function} as the stage 
 * name./*  www. jav a  2 s .  co  m*/
 * 
 * @param index The index the specified {@code Function} to be set.
 * @param function The {@code Function} set to the next processing stage.
 * @return This {@code Pipeline} instance.
 */
public Pipeline<T> set(int index, Function<T, T> function) {
    return set(index, function.getClass().getName(), function);
}

From source file:org.eiichiro.bootleg.Pipeline.java

/**
 * Sets the specified {@code Function} to the next processing stage with the 
 * class name of the {@code Function} as the stage name.
 * //from  w ww.j a  v a 2s . c o  m
 * @param function The {@code Function} set to the next processing stage.
 * @return This {@code Pipeline} instance.
 */
public Pipeline<T> set(Function<T, T> function) {
    return set(stages.size(), function.getClass().getName(), function);
}

From source file:com.ning.arecibo.collector.process.CollectorEventProcessor.java

@Inject
public CollectorEventProcessor(final List<EventHandler> eventHandlers,
        @EventFilter final Function<Event, Event> filter) throws IOException {
    this.eventHandlers = eventHandlers;
    this.filter = filter;
    log.info("Event processor filter: {}", filter.getClass().toString());
}

From source file:org.jclouds.rest.internal.InvokeHttpMethod.java

private Function<HttpResponse, ?> getTransformer(String commandName, HttpCommand command) {
    HttpRequest request = command.getCurrentRequest();
    Function<HttpResponse, ?> transformer = transformerForRequest.apply(request);
    logger.trace("<< response from %s is parsed by %s", commandName, transformer.getClass().getSimpleName());
    return transformer;
}

From source file:org.jclouds.rest.internal.AsyncRestClientProxy.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private ListenableFuture<?> createListenableFuture(Method method, Object[] args) throws ExecutionException {
    method = annotationProcessor.getDelegateOrNull(method);
    logger.trace("Converting %s.%s", declaring.getSimpleName(), method.getName());
    Function<Exception, ?> exceptionParser = annotationProcessor
            .createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(method);
    // in case there is an exception creating the request, we should at least
    // pass in args
    if (exceptionParser instanceof InvocationContext) {
        ((InvocationContext) exceptionParser).setContext((HttpRequest) null);
    }/*from   ww  w  .j av a  2  s . c  o m*/
    ListenableFuture<?> result;
    try {
        GeneratedHttpRequest<T> request = annotationProcessor.createRequest(method, args);
        if (exceptionParser instanceof InvocationContext) {
            ((InvocationContext) exceptionParser).setContext(request);
        }
        logger.trace("Converted %s.%s to %s", declaring.getSimpleName(), method.getName(),
                request.getRequestLine());

        Function<HttpResponse, ?> transformer = annotationProcessor.createResponseParser(method, request);
        logger.trace("Response from %s.%s is parsed by %s", declaring.getSimpleName(), method.getName(),
                transformer.getClass().getSimpleName());

        logger.debug("Invoking %s.%s", declaring.getSimpleName(), method.getName());
        result = commandFactory.create(request, transformer).execute();

    } catch (RuntimeException e) {
        AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class);
        if (aex != null)
            e = aex;
        if (exceptionParser != null) {
            try {
                return Futures.immediateFuture(exceptionParser.apply(e));
            } catch (Exception ex) {
                return Futures.immediateFailedFuture(ex);
            }
        }
        return Futures.immediateFailedFuture(e);
    }

    if (exceptionParser != null) {
        logger.trace("Exceptions from %s.%s are parsed by %s", declaring.getSimpleName(), method.getName(),
                exceptionParser.getClass().getSimpleName());
        result = new ExceptionParsingListenableFuture(result, exceptionParser);
    }
    return result;
}

From source file:com.eucalyptus.util.RestrictedTypes.java

/**
 * Uses the provided {@code lookupFunction} to resolve the {@code identifier} to the underlying
 * object {@code T} with privileges determined by the current messaging context.
 * //from  w w w. j a  va 2  s.  c  o  m
 * @param <T> type of object which needs looking up
 * @param identifier identifier of the desired object
 * @param resolverFunction class which resolves string identifiers to the underlying object
 * @return the object corresponding with the given {@code identifier}
 * @throws AuthException if the user is not authorized
 * @throws PersistenceException if an error occurred in the underlying retrieval mechanism
 * @throws NoSuchElementException if the requested {@code identifier} does not exist and the user
 *           is authorized.
 * @throws IllegalContextAccessException if the current request context cannot be determined.
 */
@SuppressWarnings("rawtypes")
private static <T extends RestrictedType> T doPrivileged(final String identifier,
        final Function<? super String, T> resolverFunction, final boolean ignoreOwningAccount)
        throws AuthException, IllegalContextAccessException, NoSuchElementException, PersistenceException {
    checkParam("Resolver function must be not null: " + identifier, resolverFunction, notNullValue());
    Context ctx = Contexts.lookup();
    if (ctx.hasAdministrativePrivileges()) {
        return resolverFunction.apply(identifier);
    } else {
        Class<? extends BaseMessage> msgType = ctx.getRequest().getClass();
        LOG.debug("Attempting to lookup " + identifier + " using lookup: " + resolverFunction.getClass()
                + " typed as " + Classes.genericsToClasses(resolverFunction));
        Class<?> rscType = findResourceClass(resolverFunction);
        Ats ats = findPolicyAnnotations(rscType, msgType);
        PolicyVendor vendor = ats.get(PolicyVendor.class);
        PolicyResourceType type = ats.get(PolicyResourceType.class);
        String action = getIamActionByMessageType();
        String actionVendor = findPolicyVendor(msgType);
        User requestUser = ctx.getUser();
        Map<String, String> evaluatedKeys = ctx.evaluateKeys();
        T requestedObject;
        try {
            requestedObject = resolverFunction.apply(identifier);
            if (requestedObject == null) {
                throw new NoSuchElementException("Failed to lookup requested " + rscType.getCanonicalName()
                        + " with id " + identifier + " using " + resolverFunction.getClass());
            }
        } catch (NoSuchElementException ex) {
            throw ex;
        } catch (PersistenceException ex) {
            Logs.extreme().error(ex, ex);
            LOG.error(ex);
            throw ex;
        } catch (Exception ex) {
            Logs.extreme().error(ex, ex);
            LOG.error(ex);
            throw new PersistenceException("Error occurred while attempting to lookup " + identifier
                    + " using lookup: " + resolverFunction.getClass() + " typed as " + rscType, ex);
        }

        final Principal.PrincipalType principalType;
        final String principalName;
        if (Principals.isSameUser(requestUser, Principals.systemUser())) {
            principalType = Principal.PrincipalType.Service;
            principalName = "ec2.amazon.com";
        } else {
            principalType = Principal.PrincipalType.AWS;
            principalName = Accounts.getUserArn(requestUser);
        }

        Account owningAccount = null;
        if (!ignoreOwningAccount) {
            owningAccount = Principals.nobodyFullName().getAccountNumber()
                    .equals(requestedObject.getOwner().getAccountNumber()) ? null
                            : Accounts.lookupAccountById(requestedObject.getOwner().getAccountNumber());
        }

        final String qualifiedAction = PolicySpec.qualifiedName(actionVendor, action);
        notifyResourceInterceptors(requestedObject, qualifiedAction);
        try {
            if (!Permissions.isAuthorized(principalType, principalName,
                    findPolicy(requestedObject, actionVendor, action),
                    PolicySpec.qualifiedName(vendor.value(), type.value()), identifier, owningAccount,
                    qualifiedAction, requestUser, evaluatedKeys)) {
                throw new AuthException("Not authorized to use " + type.value() + " identified by " + identifier
                        + " as the user " + UserFullName.getInstance(requestUser));
            }
        } finally {
            notifyResourceInterceptors(null, null);
        }
        return requestedObject;
    }
}

From source file:org.jclouds.http.pool.ConnectionPoolTransformingHttpCommandExecutorService.java

/**
 * This is an asynchronous operation that puts the <code>command</code> onto a queue. Later, it
 * will be processed via the {@link #invoke(TransformingHttpCommandExecutorService) invoke}
 * method.//  w  w  w . j  a  v  a2  s  .c o m
 */
public <T> Future<T> submit(HttpCommand command, final Function<HttpResponse, T> responseTransformer,
        Function<Exception, T> exceptionTransformer) {
    exceptionIfNotActive();
    final SynchronousQueue<?> channel = new SynchronousQueue<Object>();
    // should block and immediately parse the response on exit.
    Future<T> future = executorService.submit(new Callable<T>() {
        Logger transformerLogger = logFactory.getLogger(responseTransformer.getClass().getName());

        public T call() throws Exception {
            Object o = channel.take();
            if (o instanceof Exception) {
                throw (Exception) o;
            }
            transformerLogger.debug("Processing intermediate result for: %s", o);
            T result = responseTransformer.apply((HttpResponse) o);
            transformerLogger.debug("Processed intermediate result for: %s", o);
            return result;
        }
    });

    HttpCommandRendezvous<T> rendezvous = new HttpCommandRendezvous<T>(command, channel, future);
    commandQueue.add(rendezvous);
    if (exceptionTransformer != null) {
        return new FutureExceptionParser<T>(rendezvous.getFuture(), exceptionTransformer);
    }
    return rendezvous.getFuture();
}