Skip to content

Commit

Permalink
Support local refs for jsonschema2pojo.org
Browse files Browse the repository at this point in the history
Close #183.
  • Loading branch information
joelittlejohn committed May 25, 2014
1 parent 06d8df2 commit 9ee5107
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class Schema {
private JsonNode content;
private JType javaType;

protected Schema(URI id, JsonNode content) {
public Schema(URI id, JsonNode content) {
this.id = id;
this.content = content;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,24 @@ public Schema create(Schema parent, String path) {
if (path.equals("#")) {
return parent;
}

path = stripEnd(path, "#?&/");

URI id = (parent == null || parent.getId() == null) ? URI.create(path) : parent.getId().resolve(path);

if (selfReferenceWithoutParentFile(parent, path)) {
schemas.put(id, new Schema(id, fragmentResolver.resolve(parent.getContent(), path)));
return schemas.get(id);
}

return create(id);

}

private boolean selfReferenceWithoutParentFile(Schema parent, String path) {
return parent != null && parent.getId() == null && path.startsWith("#/");
}

public synchronized void clearCache() {
schemas.clear();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,22 @@

package org.jsonschema2pojo.integration.ref;

import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.*;
import static org.hamcrest.Matchers.*;
import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.*;
import static org.junit.Assert.*;

import java.io.IOException;

import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.rules.RuleFactory;
import org.junit.BeforeClass;
import org.junit.Test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;

public class FragmentRefIT {

private static Class<?> fragmentRefsClass;
Expand Down Expand Up @@ -53,5 +62,14 @@ public void refToFragmentOfAnotherSchemaIsReadSuccessfully() throws NoSuchMethod
assertThat(aClass.getName(), is("com.example.AdditionalPropertyValue"));

}

@Test
public void selfRefWithoutParentFile() throws IOException {
JCodeModel codeModel = new JCodeModel();
JsonNode schema = new ObjectMapper().readTree("{\"type\":\"object\", \"properties\":{\"a\":{\"$ref\":\"#/b\"}}, \"b\":\"string\"}");

JPackage p = codeModel._package("com.example");
new RuleFactory().getSchemaRule().apply("Example", schema, p, new Schema(null, schema));
}

}

0 comments on commit 9ee5107

Please # to comment.