Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rules to generate java code from json schema #94

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions JsonRules/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Built application files
*.apk
*.ap_

# Files for the ART/Dalvik VM
*.dex

# Java class files
*.class

# VSCode project file.
.project
.classpath
.settings

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Log Files
*.log

# Android Studio Navigation editor temp files
.navigation/

# Android Studio captures folder
captures/

# IntelliJ
*.iml
.idea

# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks

# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

# Google Services (e.g. APIs or Firebase)
google-services.json

# Freeline
freeline.py
freeline/
freeline_project_description.json

# Ignore poms
*.pom

# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# gradle stuffs
gradlew
gradlew.bat
gradle-wrapper.jar
120 changes: 120 additions & 0 deletions JsonRules/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
plugins {
id 'java-library'
id 'maven-publish'
}

java {
sourceCompatibility = JavaVersion.VERSION_1_7
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not related to this PR, but we probably want to make this a variable (in the versioning file, to be consumed by everyone) at some point - if possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes....I've also done some work here in the plugin as well...to accept any Java version as opposed to just toggling between 7 & 8

It is in-progress here: #95 (mostly complete...just need to add javadocs before I make it live)

targetCompatibility = JavaVersion.VERSION_1_7
}

dependencies {
implementation "org.jsonschema2pojo:jsonschema2pojo-core:1.1.1"
}

apply from: './versioning/version_tasks.gradle'

version = getAppVersionName()

project.ext.vstsUsername = System.getenv("ENV_VSTS_MVN_ANDROIDCOMMON_USERNAME") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDCOMMON_USERNAME") : project.findProperty("vstsUsername")
project.ext.vstsPassword = System.getenv("ENV_VSTS_MVN_ANDROIDCOMMON_ACCESSTOKEN") != null ? System.getenv("ENV_VSTS_MVN_ANDROIDCOMMON_ACCESSTOKEN") : project.findProperty("vstsMavenAccessToken")

task sourcesJar(type: Jar) {
from sourceSets.main.java.srcDirs
classifier = 'sources'
destinationDirectory = reporting.file("$project.buildDir/output/jars")
}

// Task to generate javadoc
task generateJavadoc(type: Javadoc) {
failOnError false
title = "Microsoft Identity Json2POJO Rules"
source = sourceSets.main.java
classpath += project.sourceSets.main.compileClasspath

options.memberLevel = JavadocMemberLevel.PUBLIC
options.addStringOption('Xdoclint:none', '-quiet')

exclude '**/BuildConfig.Java'
exclude '**/R.java'
destinationDir = reporting.file("$project.buildDir/output/javadoc")
}

// Task to generate javadoc.jar
task javadocJar(type: Jar, dependsOn: generateJavadoc) {
from javadoc.destinationDir
classifier 'javadoc'
destinationDirectory = reporting.file("$project.buildDir/output/jars")
}

jar {
manifest {
attributes('Implementation-Title': project.name,
'Implementation-Version': project.version)
}
}

publishing {
publications {
aar(MavenPublication) {
groupId 'com.microsoft.identity.json'
artifactId 'rules'
from components.java

pom {
name = 'common4j'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

common4j?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copy paste 😁 I'll fix it

description = 'This library contains rules for generating Java classes from Json ' +
'schema using the jsonschema2pojo library.'
url = 'https://github.com/AzureAD/android-complete'
developers {
developer {
id = 'microsoft'
name = 'Microsoft'
}
}
licenses {
license {
name = 'MIT License'
}
}
inceptionYear = '2021'
scm {
url = 'https://github.com/AzureAD/android-complete'
}
properties = [
branch : 'master',
version: project.version
]
}
}
}

repositories {
maven {
name "vsts-maven-adal-android"
url "https://identitydivision.pkgs.visualstudio.com/_packaging/AndroidADAL/maven/v1"
credentials {
username project.ext.vstsUsername
password project.ext.vstsPassword
}
}
maven {
name "vsts-maven-android"
url 'https://identitydivision.pkgs.visualstudio.com/IDDP/_packaging/Android/maven/v1'
credentials {
username project.vstsUsername
password project.vstsPassword
}
}
}
}

sourceSets {
main {
java.srcDirs = ['src/main']
}
test {
java.srcDirs = ['src/test']
}
}

12 changes: 12 additions & 0 deletions JsonRules/changelog
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Version 0.0.3
----------------------------
- Update Map Rule to generate Map that maps Strings keys to Object values

Version 0.0.2
----------------------------
- Add a Rule to generate private no-arg constructor if both constructors and setters disabled

Version 0.0.1
----------------------------
- Add a MapRule to generate Map fields
- Add a custom rule factory that that overrides the TypeRule and also provides a MapRule
5 changes: 5 additions & 0 deletions JsonRules/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.identity.json.rules;

import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;

import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.rules.ObjectRule;
import org.jsonschema2pojo.util.ParcelableHelper;
import org.jsonschema2pojo.util.ReflectionHelper;

/**
* A custom {@link ObjectRule} that has the capability to generate private constructor if the
* config specified to NOT generate constructor AND also NOT generate any setters.
* <p>
* We do this because if no constructor is generated, then JAVA will by default have a public
* NO-arg constructor for the class. This is a problem because this would allow someone to
* instantiate the object without actually populating any of its fields and also not having the
* ability to populate any fields post object construction because setters were not generated. To
* overcome this problem, we would simply generate a PRIVATE no-arg constructor so that no one can
* actually instantiate the object without any properties on it.
*/
public class AuthClientJsonSchemaObjectRule extends ObjectRule {

private AuthClientJsonSchemaRuleFactory ruleFactory;

protected AuthClientJsonSchemaObjectRule(AuthClientJsonSchemaRuleFactory ruleFactory, ParcelableHelper parcelableHelper, ReflectionHelper reflectionHelper) {
super(ruleFactory, parcelableHelper, reflectionHelper);
this.ruleFactory = ruleFactory;
}

@Override
public JType apply(final String nodeName, final JsonNode node, final JsonNode parent,
final JPackage jPackage, final Schema schema) {
final JType jType = super.apply(nodeName, node, parent, jPackage, schema);
if (jType instanceof JDefinedClass
&& !ruleFactory.getGenerationConfig().isIncludeConstructors()
&& !ruleFactory.getGenerationConfig().isIncludeSetters()) {
new PrivateConstructorRule().apply(nodeName, node, parent, (JDefinedClass) jType, schema);
}
return jType;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.identity.json.rules;

import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassContainer;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;

import org.jsonschema2pojo.rules.Rule;
import org.jsonschema2pojo.rules.RuleFactory;
import org.jsonschema2pojo.util.ParcelableHelper;

/**
* A {@link RuleFactory} that provides a custom implementation of the {@link org.jsonschema2pojo.rules.TypeRule}
* and also provides an additional {@link MapRule} as well.
*/
public class AuthClientJsonSchemaRuleFactory extends RuleFactory {
Copy link
Member

@rpdome rpdome Jun 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit, add a brief comment on what is typerule, and objectrule.


@Override
public Rule<JClassContainer, JType> getTypeRule() {
return new AuthClientJsonSchemaTypeRule(this);
}

/**
* Provides a rule instance that should be applied when an "object"
* declaration is found in the schema.
*
* @return a schema rule that can handle the "object" declaration.
*/
public Rule<JClassContainer, JClass> getMapRule() {
return new MapRule();
}

@Override
public Rule<JPackage, JType> getObjectRule() {
return new AuthClientJsonSchemaObjectRule(this, new ParcelableHelper(), getReflectionHelper());
}
}
Loading