Example usage for java.lang Void TYPE

List of usage examples for java.lang Void TYPE

Introduction

In this page you can find the example usage for java.lang Void TYPE.

Prototype

Class TYPE

To view the source code for java.lang Void TYPE.

Click Source Link

Document

The Class object representing the pseudo-type corresponding to the keyword void .

Usage

From source file:net.ageto.gyrex.persistence.jdbc.pool.internal.commands.ListPools.java

private TreeMap<String, String> readPoolConfig(final BoneCPDataSource dataSource) {
    final TreeMap<String, String> poolConfig = new TreeMap<String, String>();
    final BoneCPConfig config = dataSource.getConfig();
    for (final Method method : BoneCPConfig.class.getDeclaredMethods()) {
        String key = null;//from   w  w  w .ja  v  a  2s .  c  o m
        if (method.getName().startsWith("is")) {
            key = WordUtils.uncapitalize(method.getName().substring(2));
        } else if (method.getName().startsWith("get")) {
            key = WordUtils.uncapitalize(method.getName().substring(3));
        } else {
            continue;
        }

        // skip deprecated methods
        if ((null != method.getAnnotation(Deprecated.class)) || key.equals("maxConnectionAge")) {
            continue;
        }

        if ((method.getParameterTypes().length == 0) && (method.getReturnType() != Void.TYPE)) {
            try {
                final Object value = method.invoke(config);
                if (null != value) {
                    poolConfig.put(key, String.valueOf(value));
                }
            } catch (final Exception e) {
                // ignored
            }
        }
    }
    return poolConfig;
}

From source file:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileMethodCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod();
    Method testedMethod = mrInfo.getMethod();

    VelocityContext context = new VelocityContext();

    context.put("mFunction", testedMethod);
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));
    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsNotVoid", !(testedMethod.getReturnType().equals(Void.TYPE)));

    writeCode(context, templateMethodName);

    String javaSourceName = javaDestinationDir + directoryName + "/" + templateMethodName + ".java";
    String javaClassDirectory = compiledClassDestinationDir + directoryName;

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);//  ww  w.j  a  v a2 s .  co  m

    Compiler.compile(javaSourceName, classPaths);
}

From source file:org.unitils.mock.report.impl.ObservedInvocationsReport.java

/**
 * Creates a string representation of the given invocation.
 * If arguments and result values are small enough, they are displayed inline, else the value is replaced by
 * a name generated by the {@link #createLargeValueName} method.
 *
 * @param observedInvocation     The invocation to format, not null
 * @param currentLargeObjects    The current the large values, not null
 * @param largeObjectNames       All large values names per value, not null
 * @param largeObjectNameIndexes The current indexes to use for the large value names (per value type), not null
 * @param fieldValuesAndNames    The values and name of the instance fields in the test object
 * @return The string representation, not null
 *//*from w w  w .  j  av a2  s .  c  om*/
protected String formatObservedInvocation(ObservedInvocation observedInvocation,
        List<FormattedObject> currentLargeObjects, Map<Object, String> largeObjectNames,
        Map<Class<?>, Integer> largeObjectNameIndexes, Map<Object, String> fieldValuesAndNames) {
    StringBuilder result = new StringBuilder();
    Method method = observedInvocation.getMethod();

    // append the mock and method name
    result.append(observedInvocation.getProxyName());
    result.append('.');
    result.append(method.getName());

    // append the arguments
    result.append('(');
    List<Argument<?>> arguments = observedInvocation.getArguments();
    if (!arguments.isEmpty()) {
        for (Argument<?> argument : arguments) {
            Class<?> argumentType = argument.getType();
            Object argumentValue = argument.getValue();
            Object argumentValueAtInvocationTime = argument.getValueAtInvocationTime();

            result.append(formatValue(argumentValueAtInvocationTime, argumentValue, argumentType,
                    currentLargeObjects, largeObjectNames, largeObjectNameIndexes, fieldValuesAndNames));
            result.append(", ");
        }
        // remove the last comma
        result.setLength(result.length() - 2);
    }
    result.append(")");

    // append the result value, if the method is non-void
    Class<?> resultType = method.getReturnType();
    if (Void.TYPE != resultType) {
        result.append(" -> ");
        Object resultValue = observedInvocation.getResult();
        Object resultAtInvocationTime = observedInvocation.getResultAtInvocationTime();
        result.append(formatValue(resultAtInvocationTime, resultValue, resultType, currentLargeObjects,
                largeObjectNames, largeObjectNameIndexes, fieldValuesAndNames));
    }
    return result.toString();
}

From source file:org.jsonschema2pojo.integration.MediaIT.java

@Test
public void shouldCreateStringSetterWithoutEncoding() throws SecurityException, NoSuchMethodException {
    Method setter = classWithMediaProperties.getDeclaredMethod("setUnencoded", String.class);

    assertThat("unencoded setter has return type void", setter.getReturnType(), equalToType(Void.TYPE));
}

From source file:com.github.pfmiles.org.apache.velocity.runtime.parser.node.ASTMethod.java

/**
 *  invokes the method.  Returns null if a problem, the
 *  actual return if the method returns something, or
 *  an empty string "" if the method returns void
 * @param o//from w  w  w.  j  a va 2 s . c  o m
 * @param context
 * @return Result or null.
 * @throws MethodInvocationException
 */
public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException {
    /*
     *  new strategy (strategery!) for introspection. Since we want
     *  to be thread- as well as context-safe, we *must* do it now,
     *  at execution time.  There can be no in-node caching,
     *  but if we are careful, we can do it in the context.
     */
    Object[] params = new Object[paramCount];

    /*
     * sadly, we do need recalc the values of the args, as this can
     * change from visit to visit
     */
    Class[] paramClasses = paramCount > 0 ? new Class[paramCount] : ArrayUtils.EMPTY_CLASS_ARRAY;

    for (int j = 0; j < paramCount; j++) {
        params[j] = jjtGetChild(j + 1).value(context);
        if (params[j] != null) {
            paramClasses[j] = params[j].getClass();
        }
    }
    // recParsing
    if (ParseUtil.class.equals(o) && "recParsing".equals(methodName) && paramCount == 1) {
        Object[] temp = params;
        params = new Object[2];
        params[0] = temp[0];
        params[1] = this.getTemplateName();

        Class[] clsTemp = paramClasses;
        paramClasses = new Class[2];
        paramClasses[0] = clsTemp[0];
        paramClasses[1] = String.class;
    }
    VelMethod method = ClassUtils.getMethod(methodName, params, paramClasses, o, context, this, strictRef);
    if (method == null)
        return null;

    try {
        /*
         *  get the returned object.  It may be null, and that is
         *  valid for something declared with a void return type.
         *  Since the caller is expecting something to be returned,
         *  as long as things are peachy, we can return an empty
         *  String so ASTReference() correctly figures out that
         *  all is well.
         */

        Object obj = method.invoke(o, params);

        if (obj == null) {
            if (method.getReturnType() == Void.TYPE) {
                return "";
            }
        }

        return obj;
    } catch (InvocationTargetException ite) {
        return handleInvocationException(o, context, ite.getTargetException());
    }

    /** Can also be thrown by method invocation **/
    catch (IllegalArgumentException t) {
        return handleInvocationException(o, context, t);
    }

    /**
     * pass through application level runtime exceptions
     */
    catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        String msg = "ASTMethod.execute() : exception invoking method '" + methodName + "' in " + o.getClass();
        log.error(msg, e);
        throw new VelocityException(msg, e);
    }
}

From source file:org.apache.camel.component.cxf.converter.CxfConverter.java

/**
 * Use a fallback type converter so we can convert the embedded list element 
 * if the value is MessageContentsList.  The algorithm of this converter
 * finds the first non-null list element from the list and applies conversion
 * to the list element./*from   ww w .  j a v a2  s .c  o  m*/
 * 
 * @param type the desired type to be converted to
 * @param exchange optional exchange which can be null
 * @param value the object to be converted
 * @param registry type converter registry
 * @return the converted value of the desired type or null if no suitable converter found
 */
@SuppressWarnings("unchecked")
@FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {

    // CXF-WS MessageContentsList class
    if (MessageContentsList.class.isAssignableFrom(value.getClass())) {
        MessageContentsList list = (MessageContentsList) value;

        for (Object embedded : list) {
            if (embedded != null) {
                if (type.isInstance(embedded)) {
                    return type.cast(embedded);
                } else {
                    TypeConverter tc = registry.lookup(type, embedded.getClass());
                    if (tc != null) {
                        return tc.convertTo(type, exchange, embedded);
                    }
                }
            }
        }
        // return void to indicate its not possible to convert at this time
        return (T) Void.TYPE;
    }

    // CXF-RS Response class
    if (Response.class.isAssignableFrom(value.getClass())) {
        Response response = (Response) value;
        Object entity = response.getEntity();

        TypeConverter tc = registry.lookup(type, entity.getClass());
        if (tc != null) {
            return tc.convertTo(type, exchange, entity);
        }

        // return void to indicate its not possible to convert at this time
        return (T) Void.TYPE;
    }

    return null;
}

From source file:hu.bme.mit.sette.tools.catg.CatgGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO enhance message
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }//from   w  w w . java 2  s.  co  m

        snippetLoop: for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());
            main.imports().add("catg.CATG");

            String[] paramNames = new String[parameterTypes.length];
            List<String> createVariableLines = new ArrayList<>(parameterTypes.length);
            List<String> sysoutVariableLines = new ArrayList<>(parameterTypes.length);

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                String paramName = "param" + (i + 1);
                String varType = CatgGenerator.getTypeString(parameterType);
                String catgRead = CatgGenerator.createCatgRead(parameterType);

                if (varType == null || catgRead == null) {
                    // TODO make better
                    System.err.println("Method has an unsupported parameter type: " + parameterType.getName()
                            + " (method: " + method.getName() + ")");
                    continue snippetLoop;
                }

                paramNames[i] = paramName;
                // e.g.: int param1 = CATG.readInt(0);
                createVariableLines.add(String.format("%s %s = %s;", varType, paramName, catgRead));
                // e.g.: System.out.println("  int param1 = " + param1);
                sysoutVariableLines.add(String.format("System.out.println(\"  %s %s = \" + %s);", varType,
                        paramName, paramName));
                i++;
            }

            main.codeLines().addAll(createVariableLines);

            main.codeLines().add("");

            main.codeLines().add(String.format("System.out.println(\"%s#%s\");", javaClass.getSimpleName(),
                    method.getName()));
            main.codeLines().addAll(sysoutVariableLines);

            String functionCall = String.format("%s.%s(%s)", javaClass.getSimpleName(), method.getName(),
                    StringUtils.join(paramNames, ", "));

            Class<?> returnType = method.getReturnType();

            if (Void.TYPE.equals(returnType) || Void.class.equals(returnType)) {
                // void return type
                main.codeLines().add(functionCall + ';');
                main.codeLines().add("System.out.println(\"  result: void\");");
            } else {
                // non-void return type
                main.codeLines().add("System.out.println(\"  result: \" + " + functionCall + ");");
            }

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:com.hortonworks.hbase.replication.bridge.WritableRpcEngine.java

/** Expert: Make multiple, parallel calls to a set of servers. */
@Override//from   ww  w .  j  av  a 2  s . co m
public Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs,
        Class<? extends VersionedProtocol> protocol, User ticket, Configuration conf)
        throws IOException, InterruptedException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++) {
        invocations[i] = new Invocation(method, protocol, params[i]);
    }

    Writable[] wrappedValues = client.call(invocations, addrs, protocol, ticket);

    if (method.getReturnType() == Void.TYPE) {
        return null;
    }

    Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length);
    for (int i = 0; i < values.length; i++) {
        if (wrappedValues[i] != null) {
            values[i] = ((HbaseObjectWritable) wrappedValues[i]).get();
        }
    }

    return values;
}

From source file:java2typescript.jackson.module.visitors.TSJsonObjectFormatVisitor.java

protected AbstractType getTSTypeForProperty(BeanProperty writer) throws JsonMappingException {
    if (writer == null) {
        throw new IllegalArgumentException("Null writer");
    }//from  w ww .j a  va 2 s.c om
    JavaType type = writer.getType();
    if (type.getRawClass().equals(Void.TYPE)) {
        return VoidType.getInstance();
    }

    AbstractType customType = conf.getCustomTypes().get(type.getRawClass().getName());
    if (customType != null) {
        return customType;
    }

    try {
        JsonSerializer<Object> ser = getSer(writer);

        if (ser != null) {
            if (type == null) {
                throw new IllegalStateException("Missing type for property '" + writer.getName() + "'");
            }
            return getTSTypeForHandler(this, ser, type, conf);
        } else {
            return AnyType.getInstance();
        }

    } catch (Exception e) {
        throw new RuntimeException(String.format(//
                "Error when serializing %s, you should add a custom mapping for it", type.getRawClass()), e);
    }

}

From source file:org.getobjects.foundation.kvc.KVCWrapper.java

public PropertyDescriptor[] getPropertyDescriptors(Class _class) throws Exception {
    /**/* w ww  .  j a va 2 s.com*/
     * Our idea of KVC differs from what the Bean API proposes. Instead of
     * having get<name> and set<name> methods, we expect <name> and 
     * set<name> methods.
     * 
     * HH: changed to allow for getXYZ style accessors.
     */

    Map<String, Method> settersMap = new HashMap<String, Method>();
    Map<String, Method> gettersMap = new HashMap<String, Method>();

    Method methods[] = getPublicDeclaredMethods(_class);

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method == null)
            continue;

        String name = method.getName();
        int nameLen = name.length();
        int paraCount = method.getParameterTypes().length;

        if (name.startsWith("set")) {
            if (method.getReturnType() != Void.TYPE)
                continue;
            if (paraCount != 1)
                continue;
            if (nameLen == 3)
                continue;

            char[] chars = name.substring(3).toCharArray();
            chars[0] = Character.toLowerCase(chars[0]);
            String decapsedName = new String(chars);

            if (logger.isDebugEnabled()) {
                logger.debug("Recording setter method [" + method + "] for name \"" + decapsedName + "\"");
            }
            settersMap.put(decapsedName, method);
        } else {
            /* register as a getter */
            if (method.getReturnType() == Void.TYPE)
                continue;
            if (paraCount > 0)
                continue;

            if (name.startsWith("get")) {
                char[] chars = name.substring(3).toCharArray();
                chars[0] = Character.toLowerCase(chars[0]);
                name = new String(chars);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Recording getter method [" + method + "] for name \"" + name + "\"");
            }
            gettersMap.put(name, method);
        }

    }

    Set<PropertyDescriptor> pds = new HashSet<PropertyDescriptor>();

    /* merge all names from getters and setters */
    Set<String> names = new HashSet<String>(gettersMap.keySet());
    names.addAll(settersMap.keySet());

    for (String name : names) {
        Method getter = gettersMap.get(name);
        Method setter = settersMap.get(name);
        if (getter == null && setter == null)
            continue;

        /* this is JavaBeans stuff */
        PropertyDescriptor descriptor = new PropertyDescriptor(name, getter, setter);
        pds.add(descriptor);
    }
    return pds.toArray(new PropertyDescriptor[0]);
}