use of com.google.gson.stream.JsonReader in project sling by apache.
the class ListChildrenCommand method execute.
@Override
public Result<ResourceProxy> execute() {
GetMethod get = new GetMethod(getPath());
try {
httpClient.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(repositoryInfo.getUsername(), repositoryInfo.getPassword());
httpClient.getState().setCredentials(new AuthScope(repositoryInfo.getHost(), repositoryInfo.getPort(), AuthScope.ANY_REALM), defaultcreds);
int responseStatus = httpClient.executeMethod(get);
//return EncodingUtil.getString(rawdata, m.getResponseCharSet());
if (!isSuccessStatus(responseStatus))
return failureResultForStatusCode(responseStatus);
ResourceProxy resource = new ResourceProxy(path);
Gson gson = new Gson();
try (JsonReader jsonReader = new JsonReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()))) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
JsonToken token = jsonReader.peek();
if (token == JsonToken.BEGIN_OBJECT) {
ResourceProxy child = new ResourceProxy(PathUtil.join(path, name));
ResourceWithPrimaryType resourceWithPrimaryType = gson.fromJson(jsonReader, ResourceWithPrimaryType.class);
// evaluate its jcr:primaryType as well!
child.addProperty(Repository.JCR_PRIMARY_TYPE, resourceWithPrimaryType.getPrimaryType());
resource.addChild(child);
} else if (token == JsonToken.STRING) {
if (Repository.JCR_PRIMARY_TYPE.equals(name)) {
String primaryType = jsonReader.nextString();
if (primaryType != null) {
// TODO - needed?
resource.addProperty(Repository.JCR_PRIMARY_TYPE, primaryType);
}
}
} else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
}
return AbstractResult.success(resource);
} catch (Exception e) {
return AbstractResult.failure(new RepositoryException(e));
} finally {
get.releaseConnection();
}
}
use of com.google.gson.stream.JsonReader in project gradle by gradle.
the class CommandLineToolVersionLocator method parseJson.
private List<VisualStudioInstallCandidate> parseJson(String json) {
List<VisualStudioInstallCandidate> installs = Lists.newArrayList();
JsonReader reader = new JsonReader(new StringReader(json));
try {
try {
reader.beginArray();
while (reader.hasNext()) {
installs.add(readInstall(reader));
}
reader.endArray();
} finally {
reader.close();
}
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
return installs;
}
use of com.google.gson.stream.JsonReader in project bayou by capergroup.
the class LowLevelSketchExtractor method execute.
public void execute() throws IOException {
RuntimeTypeAdapterFactory<DASTNodeLowLevel> nodeAdapter = RuntimeTypeAdapterFactory.of(DASTNodeLowLevel.class, "node").registerSubtype(DAPICallLowLevel.class, "DAPICall").registerSubtype(DBranchLowLevel.class, "DBranch").registerSubtype(DExceptLowLevel.class, "DExcept").registerSubtype(DLoopLowLevel.class, "DLoop").registerSubtype(DSubTreeLowLevel.class, "DSubTree");
Gson gsonIn = new GsonBuilder().registerTypeAdapterFactory(nodeAdapter).serializeNulls().create();
JsonReader reader = new JsonReader(new FileReader(inFile));
Gson gsonOut = new GsonBuilder().serializeNulls().create();
JsonWriter writer = new JsonWriter(new FileWriter(outFile));
reader.beginObject();
reader.nextName();
reader.beginArray();
writer.setIndent(" ");
writer.beginObject();
writer.name("programs");
writer.beginArray();
System.out.println();
for (int i = 0; reader.hasNext(); i++) {
System.out.print(String.format("\rProcessed %s programs", i));
JSONInputWrapper inputProgram = gsonIn.fromJson(reader, JSONInputWrapper.class);
JsonOutputWrapper outputProgram = new JsonOutputWrapper();
outputProgram.file = inputProgram.file;
outputProgram.ast = inputProgram.ast;
outputProgram.low_level_sketch = inputProgram.ast.getLowLevelSketch();
outputProgram.sequences = inputProgram.sequences;
outputProgram.apicalls = inputProgram.apicalls;
outputProgram.types = inputProgram.types;
gsonOut.toJson(outputProgram, JsonOutputWrapper.class, writer);
}
System.out.println();
reader.close();
writer.endArray();
writer.endObject();
writer.close();
}
use of com.google.gson.stream.JsonReader in project bayou by capergroup.
the class RuntimeTypeAdapterFactory method create.
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (type.getRawType() != baseType) {
return null;
}
final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate);
subtypeToDelegate.put(entry.getValue(), delegate);
}
return new TypeAdapter<R>() {
@Override
public R read(JsonReader in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
if (labelJsonElement == null) {
throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName);
}
String label = labelJsonElement.getAsString();
// registration requires that subtype extends T
@SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
if (delegate == null) {
throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?");
}
return delegate.fromJsonTree(jsonElement);
}
@Override
public void write(JsonWriter out, R value) throws IOException {
Class<?> srcType = value.getClass();
String label = subtypeToLabel.get(srcType);
// registration requires that subtype extends T
@SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
if (delegate == null) {
throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
}
JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName);
}
JsonObject clone = new JsonObject();
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
}
}.nullSafe();
}
use of com.google.gson.stream.JsonReader in project ArachneCentralAPI by OHDSI.
the class AchillesImportServiceImpl method importData.
@Override
@Async(value = "importAchillesReportsExecutor")
@Transactional
public void importData(IDataSource dataSource, File archivedData) throws IOException {
Characterization characterization = new Characterization();
characterization.setDataSource(dataSource);
final Long dataSourceId = dataSource.getId();
final String dataSourceName = dataSource.getName();
final DataNode dataNode = dataSource.getDataNode();
final Long dataNodeId = dataNode.getId();
final String dataNodeName = dataNode.getName();
LOGGER.info(IMPORT_ACHILLES_RESULT_LOG, "Started", dataSourceId, dataSourceName, dataNodeId, dataNodeName);
Timestamp now = new Timestamp(new Date().getTime());
characterization.setDate(now);
Path tempDir = Files.createTempDirectory("achilles_");
entityManager.setFlushMode(FlushModeType.COMMIT);
batch.set(new ArrayList<>());
try {
unzipData(archivedData, tempDir);
List<AchillesFile> files = new LinkedList<>();
JsonParser parser = new JsonParser();
final Characterization result = characterizationRepository.save(characterization);
Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
AchillesFile achillesFile = new AchillesFile();
achillesFile.setFilePath(tempDir.relativize(file).toString());
try (JsonReader reader = new JsonReader(new InputStreamReader(Files.newInputStream(file, READ)))) {
JsonObject jsonObject = parser.parse(reader).getAsJsonObject();
achillesFile.setData(jsonObject);
}
achillesFile.setCharacterization(result);
saveAsBatch(achillesFile);
return CONTINUE;
}
});
flush();
LOGGER.info(IMPORT_ACHILLES_RESULT_LOG, "Finished", dataSourceId, dataSourceName, dataNodeId, dataNodeName);
} finally {
FileUtils.deleteQuietly(tempDir.toFile());
}
}
Aggregations