Search in sources :

Example 66 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project timbuctoo by HuygensING.

the class LocalFileUserAccess method addUser.

@Override
public void addUser(User user) throws AuthenticationUnavailableException {
    final List<User> users;
    try {
        synchronized (usersFile) {
            users = objectMapper.readValue(usersFile.toFile(), new TypeReference<List<User>>() {
            });
        }
        users.add(user);
        objectMapper.writeValue(usersFile.toFile(), users.toArray(new User[users.size()]));
    } catch (IOException e) {
        JsonBasedUserStore.LOG.error("Cannot read {}", usersFile.toAbsolutePath());
        JsonBasedUserStore.LOG.error("Exception thrown", e);
        throw new AuthenticationUnavailableException(e.getMessage());
    }
}
Also used : AuthenticationUnavailableException(nl.knaw.huygens.timbuctoo.security.exceptions.AuthenticationUnavailableException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException)

Example 67 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project timbuctoo by HuygensING.

the class LocalFileVreAuthorizationAccess method getOrCreateAuthorization.

@Override
public VreAuthorization getOrCreateAuthorization(String vreId, String userId, String userRole) throws AuthorizationUnavailableException {
    Optional<VreAuthorization> authOptional = getAuthorization(vreId, userId);
    if (authOptional.isPresent()) {
        return authOptional.get();
    } else {
        try {
            synchronized (authorizationsFolder) {
                File file = getFileOfVre(vreId);
                List<VreAuthorization> authorizations = Lists.newArrayList();
                if (file.exists()) {
                    authorizations = objectMapper.readValue(file, new TypeReference<List<VreAuthorization>>() {
                    });
                }
                VreAuthorization vreAuthorization = VreAuthorization.create(vreId, userId, userRole);
                authorizations.add(vreAuthorization);
                objectMapper.writeValue(file, authorizations.toArray(new VreAuthorization[authorizations.size()]));
                return vreAuthorization;
            }
        } catch (IOException e) {
            throw new AuthorizationUnavailableException(e.getMessage());
        }
    }
}
Also used : TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) File(java.io.File) AuthorizationUnavailableException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.AuthorizationUnavailableException) VreAuthorization(nl.knaw.huygens.timbuctoo.security.dto.VreAuthorization)

Example 68 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project timbuctoo by HuygensING.

the class CnwPersonSearchDescription method createRef.

@Override
public EntityRef createRef(Vertex vertex) {
    final ObjectMapper objectMapper = new ObjectMapper();
    EntityRef entityRef = super.createRef(vertex);
    Map<String, Object> data = entityRef.getData();
    try {
        final TypeReference<List<String>> listTypeReference = new TypeReference<List<String>>() {
        };
        data.put("networkDomains", objectMapper.readValue((String) vertex.value("cnwperson_networkDomains"), listTypeReference));
        data.put("characteristics", objectMapper.readValue((String) vertex.value("cnwperson_characteristics"), listTypeReference));
        data.put("combinedDomains", objectMapper.readValue((String) vertex.value("cnwperson_combinedDomains"), listTypeReference));
        data.put("memberships", objectMapper.readValue((String) vertex.value("cnwperson_memberships"), listTypeReference));
        data.put("periodicals", objectMapper.readValue((String) vertex.value("cnwperson_periodicals"), listTypeReference));
    } catch (IOException e) {
        LOG.error("Cannot read value for cnwperson with tim_id: {}", vertex.value("tim_id"), e);
    }
    entityRef.setData(data);
    return entityRef;
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) EntityRef(nl.knaw.huygens.timbuctoo.search.EntityRef) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 69 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project timbuctoo by HuygensING.

the class TinkerPopToEntityMapper method mapEntity.

public ReadEntity mapEntity(GraphTraversal<Vertex, Vertex> entityT, boolean withRelations) {
    final List<TimProperty<?>> properties = Lists.newArrayList();
    TinkerPopPropertyConverter dbPropertyConverter = new TinkerPopPropertyConverter(collection);
    String entityTypeName = collection.getEntityTypeName();
    GraphTraversal[] propertyGetters = collection.getReadableProperties().entrySet().stream().map(prop -> prop.getValue().traversalRaw().sideEffect(x -> x.get().onSuccess(value -> {
        try {
            properties.add(dbPropertyConverter.from(prop.getKey(), value));
        } catch (UnknownPropertyException e) {
            LOG.error("Unknown property", e);
        } catch (IOException e) {
            LOG.error(databaseInvariant, "Property '" + prop.getKey() + "' is not encoded correctly", e.getCause());
        }
    }).onFailure(e -> {
        if (e.getCause() instanceof IOException) {
            LOG.error(databaseInvariant, "Property '" + prop.getKey() + "' is not encoded correctly", e.getCause());
        } else {
            LOG.error("Something went wrong while reading the property '" + prop.getKey() + "'.", e.getCause());
        }
    }))).toArray(GraphTraversal[]::new);
    entityT.asAdmin().clone().union(propertyGetters).forEachRemaining(x -> {
    // Force side effects to happen
    });
    ReadEntityImpl entity = new ReadEntityImpl();
    entity.setProperties(properties);
    Vertex entityVertex = entityT.asAdmin().clone().next();
    // TODO make use conversion for the types
    entity.setRev(getProp(entityVertex, "rev", Integer.class).orElse(-1));
    entity.setDeleted(getProp(entityVertex, "deleted", Boolean.class).orElse(false));
    entity.setPid(getProp(entityVertex, "pid", String.class).orElse(null));
    URI rdfUri = getProp(entityVertex, RDF_URI_PROP, String.class).map(x -> {
        try {
            return new URI(x);
        } catch (URISyntaxException e) {
            return null;
        }
    }).orElse(null);
    entity.setRdfUri(rdfUri);
    Property<String[]> rdfAlternativesProp = entityVertex.property(RDF_SYNONYM_PROP);
    if (rdfAlternativesProp.isPresent()) {
        try {
            entity.setRdfAlternatives(Lists.newArrayList(rdfAlternativesProp.value()));
        } catch (Exception e) {
            LOG.error(databaseInvariant, "Error while reading rdfAlternatives", e);
        }
    }
    Optional<String> typesOptional = getProp(entityVertex, "types", String.class);
    if (typesOptional.isPresent()) {
        try {
            List<String> types = new ObjectMapper().readValue(typesOptional.get(), new TypeReference<List<String>>() {
            });
            entity.setTypes(types);
        } catch (Exception e) {
            LOG.error(databaseInvariant, "Error while generating variation refs", e);
            entity.setTypes(Lists.newArrayList(entityTypeName));
        }
    } else {
        entity.setTypes(Lists.newArrayList(entityTypeName));
    }
    Optional<String> modifiedStringOptional = getProp(entityVertex, "modified", String.class);
    if (modifiedStringOptional.isPresent()) {
        try {
            entity.setModified(new ObjectMapper().readValue(modifiedStringOptional.get(), Change.class));
        } catch (IOException e) {
            LOG.error(databaseInvariant, "Change cannot be converted", e);
            entity.setModified(new Change());
        }
    } else {
        entity.setModified(new Change());
    }
    Optional<String> createdStringOptional = getProp(entityVertex, "created", String.class);
    if (createdStringOptional.isPresent()) {
        try {
            entity.setCreated(new ObjectMapper().readValue(createdStringOptional.get(), Change.class));
        } catch (IOException e) {
            LOG.error(databaseInvariant, "Change cannot be converted", e);
            entity.setCreated(new Change());
        }
    } else {
        entity.setCreated(new Change());
    }
    entity.setDisplayName(DisplayNameHelper.getDisplayname(traversalSource, entityVertex, collection).orElse(""));
    entity.setId(getIdOrDefault(entityVertex));
    if (withRelations) {
        entity.setRelations(getRelations(entityVertex, traversalSource, collection));
    }
    customEntityProperties.execute(entity, entityVertex);
    return entity;
}
Also used : StreamIterator.stream(nl.knaw.huygens.timbuctoo.util.StreamIterator.stream) LabelP(org.apache.tinkerpop.gremlin.neo4j.process.traversal.LabelP) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) RDF_SYNONYM_PROP(nl.knaw.huygens.timbuctoo.rdf.Database.RDF_SYNONYM_PROP) Collection(nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection) CustomEntityProperties(nl.knaw.huygens.timbuctoo.database.tinkerpop.CustomEntityProperties) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) Lists(com.google.common.collect.Lists) Map(java.util.Map) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) P(org.apache.tinkerpop.gremlin.process.traversal.P) Edge(org.apache.tinkerpop.gremlin.structure.Edge) Logmarkers.databaseInvariant(nl.knaw.huygens.timbuctoo.logging.Logmarkers.databaseInvariant) Property(org.apache.tinkerpop.gremlin.structure.Property) RelationRef(nl.knaw.huygens.timbuctoo.core.dto.RelationRef) Logger(org.slf4j.Logger) TimProperty(nl.knaw.huygens.timbuctoo.core.dto.property.TimProperty) ReadEntityImpl(nl.knaw.huygens.timbuctoo.core.dto.ReadEntityImpl) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CustomRelationProperties(nl.knaw.huygens.timbuctoo.database.tinkerpop.CustomRelationProperties) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) IOException(java.io.IOException) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) UUID(java.util.UUID) T(org.apache.tinkerpop.gremlin.structure.T) GraphReadUtils.getEntityTypesOrDefault(nl.knaw.huygens.timbuctoo.model.GraphReadUtils.getEntityTypesOrDefault) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Vres(nl.knaw.huygens.timbuctoo.model.vre.Vres) UnknownPropertyException(nl.knaw.huygens.timbuctoo.core.UnknownPropertyException) ReadEntity(nl.knaw.huygens.timbuctoo.core.dto.ReadEntity) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) EmptyGraph(org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph) RDF_URI_PROP(nl.knaw.huygens.timbuctoo.rdf.Database.RDF_URI_PROP) DisplayNameHelper(nl.knaw.huygens.timbuctoo.core.dto.DisplayNameHelper) Vre(nl.knaw.huygens.timbuctoo.model.vre.Vre) Optional(java.util.Optional) GraphReadUtils.getProp(nl.knaw.huygens.timbuctoo.model.GraphReadUtils.getProp) Change(nl.knaw.huygens.timbuctoo.model.Change) GraphTraversalSource(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) Change(nl.knaw.huygens.timbuctoo.model.Change) UnknownPropertyException(nl.knaw.huygens.timbuctoo.core.UnknownPropertyException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UnknownPropertyException(nl.knaw.huygens.timbuctoo.core.UnknownPropertyException) ReadEntityImpl(nl.knaw.huygens.timbuctoo.core.dto.ReadEntityImpl) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) TimProperty(nl.knaw.huygens.timbuctoo.core.dto.property.TimProperty) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 70 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project nzbhydra2 by theotherp.

the class LogContentProvider method getLogsAsJsonLines.

public JsonLogResponse getLogsAsJsonLines(int offset, int limit) throws IOException {
    File logfile = getCurrentLogfile(true);
    if (logfile == null) {
        throw new IOException("Unable to determine log file");
    }
    if (!logfile.exists()) {
        throw new IOException("Determined log file does not exist");
    }
    List<HashMap<String, Object>> objects = new ArrayList<>();
    int count = 0;
    ReversedLinesFileReader reversedLinesFileReader = new ReversedLinesFileReader(logfile, Charset.defaultCharset());
    String line = reversedLinesFileReader.readLine();
    while (offset > 0 && count++ < offset && line != null) {
        line = reversedLinesFileReader.readLine();
    }
    if (count > 0 && line == null) {
        return new JsonLogResponse(Collections.emptyList(), false, offset, 0);
    }
    count = 1;
    ObjectMapper objectMapper = new ObjectMapper();
    while (line != null && count++ <= limit) {
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        HashMap<String, Object> o = objectMapper.readValue(line, typeRef);
        objects.add(o);
        line = reversedLinesFileReader.readLine();
    }
    return new JsonLogResponse(objects, line != null, offset, objects.size());
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)316 IOException (java.io.IOException)130 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)113 Test (org.junit.Test)95 ArrayList (java.util.ArrayList)74 Map (java.util.Map)74 List (java.util.List)60 HashMap (java.util.HashMap)58 File (java.io.File)34 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)27 Collectors (java.util.stream.Collectors)25 InputStream (java.io.InputStream)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 ImmutableMap (com.google.common.collect.ImmutableMap)19 lombok.val (lombok.val)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)14 Collections (java.util.Collections)13 ISE (org.apache.druid.java.util.common.ISE)12 URL (java.net.URL)10