001/*******************************************************************************
002 * Copyright (C) 2009-2011 FuseSource Corp.
003 * Copyright (c) 2004 IBM Corporation and others.
004 *
005 * All rights reserved. This program and the accompanying materials
006 * are made available under the terms of the Eclipse Public License v1.0
007 * which accompanies this distribution, and is available at
008 * http://www.eclipse.org/legal/epl-v10.html
009 *
010 *******************************************************************************/
011package org.fusesource.hawtjni.generator;
012
013import java.lang.reflect.Modifier;
014import java.util.List;
015
016import org.fusesource.hawtjni.generator.model.JNIClass;
017import org.fusesource.hawtjni.generator.model.JNIField;
018import org.fusesource.hawtjni.generator.model.JNIType;
019import org.fusesource.hawtjni.generator.model.ReflectClass;
020
021/**
022 * 
023 * @author <a href="http://hiramchirino.com">Hiram Chirino</a>
024 */
025public class ConstantsGenerator extends JNIGenerator {
026
027    public void generate(JNIClass clazz) {
028        List<JNIField> fields = clazz.getDeclaredFields();
029        generate(fields);
030    }
031
032    public void generate(List<JNIField> fields) {
033        sortFields(fields);
034        outputln("int main() {");
035        for (JNIField field : fields) {
036            if ((field.getModifiers() & Modifier.FINAL) == 0)
037                continue;
038            generate(field);
039        }
040        outputln("}");
041    }
042
043    public void generate(JNIField field) {
044        JNIType type = field.getType();
045        output("\tprintf(\"public static final ");
046        output(field.getType().getTypeSignature3(false));
047        output(" ");
048        output(field.getName());
049        output(" = ");
050        if (type.isType("java.lang.String") || type.isType("[B"))
051            output("\"%s\"");
052        else
053            output("0x%x");
054        output(";\\n\", ");
055        output(field.getName());
056        outputln(");");
057    }
058
059    public static void main(String[] args) {
060        if (args.length < 1) {
061            System.out.println("Usage: java ConstantsGenerator <className1> <className2>");
062            return;
063        }
064        try {
065            ConstantsGenerator gen = new ConstantsGenerator();
066            for (String clazzName : args) {
067                Class<?> clazz = Class.forName(clazzName);
068                gen.generate(new ReflectClass(clazz));
069            }
070        } catch (Exception e) {
071            System.out.println("Problem");
072            e.printStackTrace(System.out);
073        }
074    }
075
076}