Wire: Can you help with example? Wire (android studio).

Created on 23 Sep 2015  路  10Comments  路  Source: square/wire

Sorry for inconvenience, but second day don't understand how to use wire library in my android studio project (gradle). Would you give example project? I want to see how to complete my project for use awesome protobuf. Please!

documentation

Most helpful comment

If you're like me and not super comfortable with gradle, here's a quick overview of specifically what you can do in your build.gradle to auto-generate java from your *.proto files using the wire compiler. Change the protoPath and wireGeneratedPath based on your source layout.

def protoPath = 'src/proto'
def wireGeneratedPath = 'build/generated/source/wire'

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.squareup.wire:wire-compiler:2.2.0'
    }
}

android {
    sourceSets {
        main {
            java {
                include wireGeneratedPath
            }
        }
    }
}

dependencies {
    compile 'com.squareup.wire:wire-runtime:2.2.0'
    // Leave this out if you're not doing integration testing...
    androidTestCompile 'com.squareup.wire:wire-runtime:2.2.0'
}

// This handles the protocol buffer generation with wire
task generateWireClasses {
    description = 'Generate Java classes from protocol buffer (.proto) schema files for use with squareup\'s wire library'
    delete(wireGeneratedPath)
    fileTree(dir: protoPath, include: '**/*.proto').each { File file ->
        doLast {
            javaexec {
                main = 'com.squareup.wire.WireCompiler'
                classpath = buildscript.configurations.classpath
                args = ["--proto_path=${protoPath}", "--java_out=${wireGeneratedPath}", "${file}"]
            }
        }
    }
}

preBuild.dependsOn generateWireClasses

All 10 comments

+1. I'm trying to find the compiler-with-dependencies jar, I can't find it anywhere.

when you use maven, just run the command
mvn generate-sources

I'm use GRADLE, not maven.

may I run this command in Android Studio (Gradle)?

Update:

I've found solution, but it's so inconvenient...

You can either invoke the command-line interface using a JavaExec task or add the Wire compiler as a buildscript classpath dependency and use its API directly. We're currently doing the former. We are (slowly) working on a Gradle plugin: https://github.com/square/wire-gradle-plugin, but it's not really ready yet.

Nothing particularly actionable here. Let's get that new Gradle plugin done.

@Gilb007 What is the solution?

1) download jar file (compiler)
2) write *.proto file (structure)
3) gave *.proto file to compiler and get java file.

If it's not helpfull, I've will elaborate.

If you're like me and not super comfortable with gradle, here's a quick overview of specifically what you can do in your build.gradle to auto-generate java from your *.proto files using the wire compiler. Change the protoPath and wireGeneratedPath based on your source layout.

def protoPath = 'src/proto'
def wireGeneratedPath = 'build/generated/source/wire'

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.squareup.wire:wire-compiler:2.2.0'
    }
}

android {
    sourceSets {
        main {
            java {
                include wireGeneratedPath
            }
        }
    }
}

dependencies {
    compile 'com.squareup.wire:wire-runtime:2.2.0'
    // Leave this out if you're not doing integration testing...
    androidTestCompile 'com.squareup.wire:wire-runtime:2.2.0'
}

// This handles the protocol buffer generation with wire
task generateWireClasses {
    description = 'Generate Java classes from protocol buffer (.proto) schema files for use with squareup\'s wire library'
    delete(wireGeneratedPath)
    fileTree(dir: protoPath, include: '**/*.proto').each { File file ->
        doLast {
            javaexec {
                main = 'com.squareup.wire.WireCompiler'
                classpath = buildscript.configurations.classpath
                args = ["--proto_path=${protoPath}", "--java_out=${wireGeneratedPath}", "${file}"]
            }
        }
    }
}

preBuild.dependsOn generateWireClasses

The example by @stuckj works a treat. I modified it a bit so the classes are only built when any .proto file changes.
task generateWireClasses { [...] FileTree wireClasses = fileTree(wireGeneratedPath) { include '**/*.class' } FileTree wireProtos = fileTree(protoPath) { include '**/*.proto' } inputs.files(wireProtos) outputs.files(wireClasses) [...] }

I made the task incremental.

//Incremental task to create java files for the source proto files.
abstract class ProtoToJava extends DefaultTask {
    @Incremental
    @PathSensitive(PathSensitivity.NAME_ONLY)
    @InputDirectory
    abstract DirectoryProperty getInputDir();

    @OutputDirectory
    abstract DirectoryProperty getOutputDir();

    @TaskAction
    void execute(InputChanges inputChanges) {
        println(inputChanges.isIncremental()
                ? 'Executing incrementally'
                : 'Executing non-incrementally'
        )

        boolean areFilesChanged = inputChanges.isIncremental() && !inputChanges.getFileChanges(inputDir).isEmpty()
        println("areFilesChanged: ${areFilesChanged}, isIncremental: ${inputChanges.isIncremental()}")

        if (!(areFilesChanged || !inputChanges.isIncremental())) {
            //Build is incremental and source files are not changed. No need to recompile.
            return
        }

        if (outputDir.asFile.present) {
            //Delete outputDir if present. Fresh copy will generated and placed there.
            println("outputDir: ${outputDir.asFile.get().path} present")

            outputDir.asFile.get().delete()
        } else {
            println("outputDir: ${outputDir.asFile.get().path} not present")
        }

        //Wire compiler classPath is located in app level build.gradle. Take it and transform to
        //FileCollection
        //credit: https://github.com/NativeScript/android-runtime/pull/1061/files

        Pattern pattern = Pattern.compile("^(.+)classpath\$")

        List<String> classPathFilePaths = new ArrayList<>()
        project.buildscript.configurations
                .all { Configuration config ->
                    Matcher matcher = pattern.matcher(config.name)
                    if (matcher.find() || config.name == "classpath") {
                        classPathFilePaths = config.resolve().collect { file -> file.path }
                    }
                }

        FileCollection classPathFileCollection = project.files(classPathFilePaths)

        project.javaexec {
            main = 'com.squareup.wire.WireCompiler'
            classpath = classPathFileCollection
            args = ["--proto_path=${inputDir.asFile.get().path}", "--java_out=${outputDir.asFile.get().path}"]
        }
    }
}

Put this in buildSrc as ProtoToJava.groovy and change the generateWireClasses task from @stuckj example to this

task generateWireClasses(type: ProtoToJava) {
    inputDir = file(protoPath)
    outputDir = file(wireGeneratedPath)
}

This requires latest gradle wrapper. I'm using 5.4.1

Was this page helpful?
0 / 5 - 0 ratings