Search in sources :

Example 51 with JsonReader

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();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) RepositoryException(org.apache.sling.ide.transport.RepositoryException) ResourceProxy(org.apache.sling.ide.transport.ResourceProxy) RepositoryException(org.apache.sling.ide.transport.RepositoryException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthScope(org.apache.commons.httpclient.auth.AuthScope) JsonReader(com.google.gson.stream.JsonReader) JsonToken(com.google.gson.stream.JsonToken) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials)

Example 52 with JsonReader

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;
}
Also used : StringReader(java.io.StringReader) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException)

Example 53 with JsonReader

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();
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonWriter(com.google.gson.stream.JsonWriter) JsonReader(com.google.gson.stream.JsonReader)

Example 54 with JsonReader

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();
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) JsonWriter(com.google.gson.stream.JsonWriter) LinkedHashMap(java.util.LinkedHashMap) JsonElement(com.google.gson.JsonElement) TypeAdapter(com.google.gson.TypeAdapter) JsonReader(com.google.gson.stream.JsonReader) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 55 with JsonReader

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());
    }
}
Also used : Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) Date(java.util.Date) LinkedList(java.util.LinkedList) AchillesFile(com.odysseusinc.arachne.portal.model.achilles.AchillesFile) Characterization(com.odysseusinc.arachne.portal.model.achilles.Characterization) DataNode(com.odysseusinc.arachne.portal.model.DataNode) JsonReader(com.google.gson.stream.JsonReader) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) JsonParser(com.google.gson.JsonParser) Async(org.springframework.scheduling.annotation.Async) Transactional(javax.transaction.Transactional)

Aggregations

JsonReader (com.google.gson.stream.JsonReader)100 StringReader (java.io.StringReader)38 JsonElement (com.google.gson.JsonElement)31 IOException (java.io.IOException)20 JsonObject (com.google.gson.JsonObject)19 Test (org.junit.Test)19 InputStreamReader (java.io.InputStreamReader)18 JsonParser (com.google.gson.JsonParser)12 HumanReadableException (com.facebook.buck.util.HumanReadableException)10 Gson (com.google.gson.Gson)10 JsonWriter (com.google.gson.stream.JsonWriter)10 TypeToken (com.google.gson.reflect.TypeToken)8 Map (java.util.Map)8 JsonToken (com.google.gson.stream.JsonToken)6 HashMap (java.util.HashMap)6 InputStream (java.io.InputStream)5 StringWriter (java.io.StringWriter)5 Type (java.lang.reflect.Type)5 ArrayList (java.util.ArrayList)5 GsonBuilder (com.google.gson.GsonBuilder)4