Search in sources :

Example 6 with CProgram

use of net.morimekta.providence.reflect.contained.CProgram in project providence by morimekta.

the class RPCOptions method getDefinition.

public PService getDefinition() throws ParseException, IOException {
    Map<String, File> includeMap = FormatUtils.getIncludeMap(getRc(), includes);
    if (service.isEmpty()) {
        throw new ArgumentException("Missing service type name");
    }
    Set<File> rootSet = new TreeSet<File>();
    for (File file : includeMap.values()) {
        rootSet.add(file.getParentFile());
    }
    String programName = service.substring(0, service.lastIndexOf("."));
    TypeLoader loader = new TypeLoader(rootSet, new ThriftProgramParser());
    try {
        if (!includeMap.containsKey(programName)) {
            throw new ArgumentException("No program " + programName + " found in include path.\n" + "Found: " + Strings.join(", ", new TreeSet<Object>(includeMap.keySet())));
        }
        loader.load(includeMap.get(programName));
    } catch (IOException e) {
        throw new ArgumentException(e.getLocalizedMessage());
    }
    String filePath = includeMap.get(programName).getCanonicalFile().getAbsolutePath();
    PService srv = loader.getProgramRegistry().getService(service, null);
    if (srv == null) {
        CProgram document = loader.getProgramRegistry().registryForPath(filePath).getProgram();
        Set<String> services = new TreeSet<>(document.getServices().stream().map(s -> s.getQualifiedName()).collect(Collectors.toSet()));
        throw new ArgumentException("Unknown service %s in %s.\n" + "Found %s", service, programName, services.size() == 0 ? "none" : Strings.join(", ", services));
    }
    return srv;
}
Also used : TypeLoader(net.morimekta.providence.reflect.TypeLoader) IOException(java.io.IOException) TreeSet(java.util.TreeSet) CProgram(net.morimekta.providence.reflect.contained.CProgram) ArgumentException(net.morimekta.console.args.ArgumentException) File(java.io.File) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) PService(net.morimekta.providence.descriptor.PService)

Example 7 with CProgram

use of net.morimekta.providence.reflect.contained.CProgram in project providence by morimekta.

the class HazelcastPortableProgramFormatter method appendProgramClass.

@Override
public void appendProgramClass(CProgram document) throws GeneratorException {
    if (document.getDocumentation() != null) {
        new BlockCommentBuilder(writer).comment(document.getDocumentation()).finish();
    }
    if (javaOptions.generated_annotation_version) {
        writer.formatln("@%s(\"%s %s\")", Generated.class.getName(), generatorOptions.generator_program_name, generatorOptions.program_version);
    } else {
        writer.formatln("@%s(\"%s\")", Generated.class.getName(), generatorOptions.generator_program_name);
    }
    writer.formatln("public class %s {", helper.getHazelcastFactoryClassName(document)).begin().newline();
    Optional<CConst> factoryID = document.getConstants().stream().filter(t -> t.getName().equals(FACTORY_ID)).findFirst();
    if (!factoryID.isPresent()) {
        throw new GeneratorException("Need to provide \"const i32 FACTORY_ID = ?\" in the thrift file for " + "hazelcast generation!");
    } else {
        CConst c = factoryID.get();
        String type = helper.getValueType(c.getDescriptor());
        String name = c.getName();
        writer.formatln("public static final %s %s = %s.%s;", type, name, helper.getConstantsClassName(document), name).newline();
    }
    List<CStructDescriptor> messages = new ArrayList<>();
    for (PDeclaredDescriptor c : document.getDeclaredTypes()) {
        try {
            if (PType.MESSAGE == c.getType() && c instanceof CStructDescriptor) {
                CStructDescriptor message = (CStructDescriptor) c;
                if (message.hasAnnotation(ThriftAnnotation.JAVA_HAZELCAST_CLASS_ID)) {
                    writer.formatln("public static final int %s = %s;", getHazelcastClassId(message.getName()), message.getAnnotationValue(ThriftAnnotation.JAVA_HAZELCAST_CLASS_ID));
                    messages.add(message);
                }
            }
        } catch (Exception e) {
            throw new GeneratorException(e.getMessage());
        }
    }
    writer.newline();
    appendPopulateMethod(messages);
    if (messages.isEmpty()) {
        throw new GeneratorException("No annotations available to generate!");
    } else {
        writer.formatln("private static class %s implements %s {", FACTORY_IMPL, PortableFactory.class.getName()).begin().newline();
        appendCreateMethod(messages);
        appendGetDefinitions(messages);
        writer.end().appendln("}");
    }
    writer.end().appendln("}").newline();
}
Also used : IndentedPrintWriter(net.morimekta.util.io.IndentedPrintWriter) Portable(com.hazelcast.nio.serialization.Portable) PDeclaredDescriptor(net.morimekta.providence.descriptor.PDeclaredDescriptor) ClassDefinition(com.hazelcast.nio.serialization.ClassDefinition) JMessage(net.morimekta.providence.generator.format.java.utils.JMessage) ArrayList(java.util.ArrayList) PType(net.morimekta.providence.PType) Generated(javax.annotation.Generated) BaseProgramFormatter(net.morimekta.providence.generator.format.java.shared.BaseProgramFormatter) ClassDefinitionBuilder(com.hazelcast.nio.serialization.ClassDefinitionBuilder) HazelcastPortableMessageFormatter(net.morimekta.providence.generator.format.java.messages.extras.HazelcastPortableMessageFormatter) BlockCommentBuilder(net.morimekta.providence.generator.format.java.utils.BlockCommentBuilder) PList(net.morimekta.providence.descriptor.PList) PortableFactory(com.hazelcast.nio.serialization.PortableFactory) JUtils.getHazelcastClassId(net.morimekta.providence.generator.format.java.utils.JUtils.getHazelcastClassId) Config(com.hazelcast.config.Config) JavaOptions(net.morimekta.providence.generator.format.java.JavaOptions) CConst(net.morimekta.providence.reflect.contained.CConst) PDescriptor(net.morimekta.providence.descriptor.PDescriptor) CProgram(net.morimekta.providence.reflect.contained.CProgram) GeneratorException(net.morimekta.providence.generator.GeneratorException) List(java.util.List) JHelper(net.morimekta.providence.generator.format.java.utils.JHelper) JUtils.camelCase(net.morimekta.providence.generator.format.java.utils.JUtils.camelCase) CStructDescriptor(net.morimekta.providence.reflect.contained.CStructDescriptor) Optional(java.util.Optional) PSet(net.morimekta.providence.descriptor.PSet) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) JField(net.morimekta.providence.generator.format.java.utils.JField) ThriftAnnotation(net.morimekta.providence.util.ThriftAnnotation) Generated(javax.annotation.Generated) ArrayList(java.util.ArrayList) BlockCommentBuilder(net.morimekta.providence.generator.format.java.utils.BlockCommentBuilder) GeneratorException(net.morimekta.providence.generator.GeneratorException) CConst(net.morimekta.providence.reflect.contained.CConst) PDeclaredDescriptor(net.morimekta.providence.descriptor.PDeclaredDescriptor) CStructDescriptor(net.morimekta.providence.reflect.contained.CStructDescriptor) GeneratorException(net.morimekta.providence.generator.GeneratorException) PortableFactory(com.hazelcast.nio.serialization.PortableFactory)

Example 8 with CProgram

use of net.morimekta.providence.reflect.contained.CProgram in project providence by morimekta.

the class TypeLoader method loadInternal.

private ProgramTypeRegistry loadInternal(File file, List<String> loadStack) throws IOException {
    loadStack = new ArrayList<>(loadStack);
    file = file.getCanonicalFile();
    if (!file.exists()) {
        throw new IllegalArgumentException("No such file " + file);
    }
    if (!file.isFile()) {
        throw new IllegalArgumentException("Unable to load thrift program: " + file + " is not a file.");
    }
    file = file.getAbsoluteFile();
    String path = file.getPath();
    if (loadStack.contains(path)) {
        // Only show the circular includes, not the path to get there.
        while (!loadStack.get(0).equals(path)) {
            loadStack.remove(0);
        }
        loadStack.add(path);
        String prefix = longestCommonPrefixPath(loadStack);
        if (prefix.length() > 0) {
            loadStack = stripCommonPrefix(loadStack);
            throw new IllegalArgumentException("Circular includes detected: " + prefix + "... " + String.join(" -> ", loadStack));
        }
        throw new IllegalArgumentException("Circular includes detected: " + String.join(" -> ", loadStack));
    }
    loadStack.add(path);
    ProgramTypeRegistry registry = this.programRegistry.registryForPath(path);
    if (programRegistry.containsProgramPath(path)) {
        return registry;
    }
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    ProgramType doc = parser.parse(in, file, includes);
    ArrayList<File> queue = new ArrayList<>();
    if (doc.hasIncludes()) {
        for (String include : doc.getIncludes()) {
            File location = new File(file.getParent(), include).getCanonicalFile();
            if (!location.exists()) {
                if (include.startsWith(".") || include.startsWith(File.separator)) {
                    throw new ParseException("No such file \"" + include + "\" to include from " + file.getName());
                }
                for (File inc : includes) {
                    File i = new File(inc, include);
                    if (i.exists()) {
                        location = i.getCanonicalFile();
                        break;
                    }
                }
            }
            if (location.exists() && !queue.contains(location)) {
                queue.add(location.getAbsoluteFile());
            }
        }
    }
    // Load includes in reverse order, in case of serial dependencies.
    Collections.reverse(queue);
    loadedDocuments.put(path, doc);
    for (File include : queue) {
        registry.registerInclude(programNameFromPath(include.getPath()), loadInternal(include, ImmutableList.copyOf(loadStack)));
    }
    // Now everything it depends on is loaded.
    CProgram program = converter.convert(path, doc);
    programRegistry.putProgram(path, program);
    programRegistry.putProgramType(path, doc);
    return registry;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) BufferedInputStream(java.io.BufferedInputStream) CProgram(net.morimekta.providence.reflect.contained.CProgram) ProgramType(net.morimekta.providence.model.ProgramType) ParseException(net.morimekta.providence.reflect.parser.ParseException) File(java.io.File)

Example 9 with CProgram

use of net.morimekta.providence.reflect.contained.CProgram in project providence by morimekta.

the class JavaGenerator method generate.

@Override
@SuppressWarnings("resource")
public void generate(@Nonnull ProgramTypeRegistry registry) throws IOException, GeneratorException {
    CProgram program = registry.getProgram();
    String javaPackage = JUtils.getJavaPackage(program);
    JHelper helper = new JHelper(registry);
    String path = JUtils.getPackageClassPath(javaPackage);
    if (program.getConstants().size() > 0) {
        String file = helper.getConstantsClassName(program) + ".java";
        OutputStream out = new BufferedOutputStream(getFileManager().create(path, file));
        try {
            IndentedPrintWriter writer = new IndentedPrintWriter(out);
            appendFileHeader(writer, helper, program);
            constFomatter(writer, helper).appendProgramClass(program);
            writer.flush();
        } finally {
            try {
                getFileManager().finalize(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    if (javaOptions.hazelcast_portable && program.getConstants().stream().anyMatch(t -> t.getName().equals("FACTORY_ID"))) {
        String file = helper.getHazelcastFactoryClassName(program) + ".java";
        OutputStream out = new BufferedOutputStream(getFileManager().create(path, file));
        try {
            IndentedPrintWriter writer = new IndentedPrintWriter(out);
            appendFileHeader(writer, helper, program);
            hazelcastFomatter(writer, helper).appendProgramClass(program);
            writer.flush();
        } finally {
            try {
                getFileManager().finalize(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    for (PDeclaredDescriptor<?> type : program.getDeclaredTypes()) {
        String file = JUtils.getClassName(type) + ".java";
        OutputStream out = new BufferedOutputStream(getFileManager().create(path, file));
        try {
            IndentedPrintWriter writer = new IndentedPrintWriter(out);
            appendFileHeader(writer, helper, program);
            switch(type.getType()) {
                case MESSAGE:
                    messageFormatter(writer, helper).appendMessageClass((PMessageDescriptor<?, ?>) type);
                    break;
                case ENUM:
                    enumFormatter(writer).appendEnumClass((CEnumDescriptor) type);
                    break;
                default:
                    throw new GeneratorException("Unhandled declaration type.");
            }
            writer.flush();
        } finally {
            try {
                getFileManager().finalize(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    for (CService service : program.getServices()) {
        String file = JUtils.getClassName(service) + ".java";
        OutputStream out = new BufferedOutputStream(getFileManager().create(path, file));
        try {
            IndentedPrintWriter writer = new IndentedPrintWriter(out);
            appendFileHeader(writer, helper, program);
            serviceFormatter(writer, helper).appendServiceClass(service);
            writer.flush();
        } finally {
            try {
                getFileManager().finalize(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) OutputStream(java.io.OutputStream) CService(net.morimekta.providence.reflect.contained.CService) HazelcastPortableProgramFormatter(net.morimekta.providence.generator.format.java.program.extras.HazelcastPortableProgramFormatter) BaseMessageFormatter(net.morimekta.providence.generator.format.java.shared.BaseMessageFormatter) CProgram(net.morimekta.providence.reflect.contained.CProgram) Generator(net.morimekta.providence.generator.Generator) GeneratorException(net.morimekta.providence.generator.GeneratorException) JUtils(net.morimekta.providence.generator.format.java.utils.JUtils) IndentedPrintWriter(net.morimekta.util.io.IndentedPrintWriter) BaseServiceFormatter(net.morimekta.providence.generator.format.java.shared.BaseServiceFormatter) IOException(java.io.IOException) PDeclaredDescriptor(net.morimekta.providence.descriptor.PDeclaredDescriptor) BufferedOutputStream(java.io.BufferedOutputStream) BaseProgramFormatter(net.morimekta.providence.generator.format.java.shared.BaseProgramFormatter) JHelper(net.morimekta.providence.generator.format.java.utils.JHelper) CEnumDescriptor(net.morimekta.providence.reflect.contained.CEnumDescriptor) FileManager(net.morimekta.providence.generator.util.FileManager) BaseEnumFormatter(net.morimekta.providence.generator.format.java.shared.BaseEnumFormatter) PMessageDescriptor(net.morimekta.providence.descriptor.PMessageDescriptor) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) Nonnull(javax.annotation.Nonnull) JHelper(net.morimekta.providence.generator.format.java.utils.JHelper) CProgram(net.morimekta.providence.reflect.contained.CProgram) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) CService(net.morimekta.providence.reflect.contained.CService) IOException(java.io.IOException) GeneratorException(net.morimekta.providence.generator.GeneratorException) BufferedOutputStream(java.io.BufferedOutputStream) IndentedPrintWriter(net.morimekta.util.io.IndentedPrintWriter)

Example 10 with CProgram

use of net.morimekta.providence.reflect.contained.CProgram in project providence by morimekta.

the class JHelper method getJavaPackage.

public String getJavaPackage(PDeclaredDescriptor<?> type) throws GeneratorException {
    String packageContext = type.getProgramName();
    CProgram document = mRegistry.getProgramForName(packageContext);
    return JUtils.getJavaPackage(document);
}
Also used : CProgram(net.morimekta.providence.reflect.contained.CProgram)

Aggregations

CProgram (net.morimekta.providence.reflect.contained.CProgram)14 File (java.io.File)6 Generator (net.morimekta.providence.generator.Generator)5 PDeclaredDescriptor (net.morimekta.providence.descriptor.PDeclaredDescriptor)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 TreeSet (java.util.TreeSet)3 ArgumentException (net.morimekta.console.args.ArgumentException)3 PService (net.morimekta.providence.descriptor.PService)3 CStructDescriptor (net.morimekta.providence.reflect.contained.CStructDescriptor)3 ProgramTypeRegistry (net.morimekta.providence.reflect.util.ProgramTypeRegistry)3 List (java.util.List)2 PMessageDescriptor (net.morimekta.providence.descriptor.PMessageDescriptor)2 GeneratorException (net.morimekta.providence.generator.GeneratorException)2 GeneratorOptions (net.morimekta.providence.generator.GeneratorOptions)2 BaseProgramFormatter (net.morimekta.providence.generator.format.java.shared.BaseProgramFormatter)2 JHelper (net.morimekta.providence.generator.format.java.utils.JHelper)2 IndentedPrintWriter (net.morimekta.util.io.IndentedPrintWriter)2 ImmutableList (com.google.common.collect.ImmutableList)1