Search in sources :

Example 6 with RequestContext

use of org.apache.atlas.RequestContext in project incubator-atlas by apache.

the class GraphBackedMetadataRepository method updateEntities.

@Override
@GraphTransaction
public CreateUpdateEntitiesResult updateEntities(ITypedReferenceableInstance... entitiesUpdated) throws RepositoryException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("updating entity {}", entitiesUpdated);
    }
    try {
        TypedInstanceToGraphMapper instanceToGraphMapper = new TypedInstanceToGraphMapper(graphToInstanceMapper, deleteHandler);
        instanceToGraphMapper.mapTypedInstanceToGraph(TypedInstanceToGraphMapper.Operation.UPDATE_FULL, entitiesUpdated);
        CreateUpdateEntitiesResult result = new CreateUpdateEntitiesResult();
        RequestContext requestContext = RequestContext.get();
        result.setEntityResult(createEntityResultFromContext(requestContext));
        GuidMapping mapping = instanceToGraphMapper.createGuidMapping();
        result.setGuidMapping(mapping);
        return result;
    } catch (AtlasException e) {
        throw new RepositoryException(e);
    }
}
Also used : CreateUpdateEntitiesResult(org.apache.atlas.CreateUpdateEntitiesResult) RepositoryException(org.apache.atlas.repository.RepositoryException) RequestContext(org.apache.atlas.RequestContext) AtlasException(org.apache.atlas.AtlasException) GuidMapping(org.apache.atlas.model.instance.GuidMapping) GraphTransaction(org.apache.atlas.annotation.GraphTransaction)

Example 7 with RequestContext

use of org.apache.atlas.RequestContext in project incubator-atlas by apache.

the class TypedInstanceToGraphMapper method mapTypedInstanceToGraph.

void mapTypedInstanceToGraph(Operation operation, ITypedReferenceableInstance... typedInstances) throws AtlasException {
    RequestContext requestContext = RequestContext.get();
    Collection<IReferenceableInstance> allNewInstances = new ArrayList<>();
    for (ITypedReferenceableInstance typedInstance : typedInstances) {
        allNewInstances.addAll(walkClassInstances(typedInstance));
    }
    TypeUtils.Pair<List<ITypedReferenceableInstance>, List<ITypedReferenceableInstance>> instancesPair = createVerticesAndDiscoverInstances(allNewInstances);
    List<ITypedReferenceableInstance> entitiesToCreate = instancesPair.left;
    List<ITypedReferenceableInstance> entitiesToUpdate = instancesPair.right;
    FullTextMapper fulltextMapper = new FullTextMapper(this, graphToTypedInstanceMapper);
    switch(operation) {
        case CREATE:
            List<String> ids = addOrUpdateAttributesAndTraits(operation, entitiesToCreate);
            addFullTextProperty(entitiesToCreate, fulltextMapper);
            requestContext.recordEntityCreate(ids);
            break;
        case UPDATE_FULL:
        case UPDATE_PARTIAL:
            ids = addOrUpdateAttributesAndTraits(Operation.CREATE, entitiesToCreate);
            requestContext.recordEntityCreate(ids);
            ids = addOrUpdateAttributesAndTraits(operation, entitiesToUpdate);
            requestContext.recordEntityUpdate(ids);
            addFullTextProperty(entitiesToCreate, fulltextMapper);
            addFullTextProperty(entitiesToUpdate, fulltextMapper);
            break;
        default:
            throw new UnsupportedOperationException("Not handled - " + operation);
    }
    for (ITypedReferenceableInstance instance : typedInstances) {
        addToEntityCache(requestContext, instance);
    }
}
Also used : ITypedReferenceableInstance(org.apache.atlas.typesystem.ITypedReferenceableInstance) ArrayList(java.util.ArrayList) IReferenceableInstance(org.apache.atlas.typesystem.IReferenceableInstance) ArrayList(java.util.ArrayList) List(java.util.List) RequestContext(org.apache.atlas.RequestContext)

Example 8 with RequestContext

use of org.apache.atlas.RequestContext in project incubator-atlas by apache.

the class TypedInstanceToGraphMapper method addReverseReference.

private <V, E> void addReverseReference(AtlasVertex<V, E> vertex, String reverseAttributeName, AtlasEdge<V, E> edge) throws AtlasException {
    String typeName = GraphHelper.getTypeName(vertex);
    Id id = GraphHelper.getIdFromVertex(typeName, vertex);
    AtlasVertex<V, E> reverseVertex = edge.getInVertex();
    String reverseTypeName = GraphHelper.getTypeName(reverseVertex);
    Id reverseId = GraphHelper.getIdFromVertex(reverseTypeName, reverseVertex);
    IDataType reverseType = typeSystem.getDataType(IDataType.class, reverseTypeName);
    AttributeInfo reverseAttrInfo = TypesUtil.getFieldMapping(reverseType).fields.get(reverseAttributeName);
    if (reverseAttrInfo.dataType().getTypeCategory() == TypeCategory.MAP) {
        // If the reverse reference is a map, what would be used as the key?
        // Not supporting automatic update of reverse map references.
        LOG.debug("Automatic update of reverse map reference is not supported - reference = {}", GraphHelper.getQualifiedFieldName(reverseType, reverseAttributeName));
        return;
    }
    String propertyName = GraphHelper.getQualifiedFieldName(reverseType, reverseAttributeName);
    String reverseEdgeLabel = GraphHelper.EDGE_LABEL_PREFIX + propertyName;
    AtlasEdge<V, E> reverseEdge = graphHelper.getEdgeForLabel(reverseVertex, reverseEdgeLabel);
    AtlasEdge<V, E> newEdge = null;
    if (reverseEdge != null) {
        newEdge = updateClassEdge(reverseVertex, reverseEdge, id, vertex, reverseAttrInfo, reverseEdgeLabel);
    } else {
        newEdge = addClassEdge(reverseVertex, vertex, reverseEdgeLabel);
    }
    switch(reverseAttrInfo.dataType().getTypeCategory()) {
        case CLASS:
            if (reverseEdge != null && !reverseEdge.getId().toString().equals(newEdge.getId().toString())) {
                // Disconnect old reference
                deleteHandler.deleteEdgeReference(reverseEdge, reverseAttrInfo.dataType().getTypeCategory(), reverseAttrInfo.isComposite, true);
            }
            break;
        case ARRAY:
            // Add edge ID to property value
            List<String> elements = reverseVertex.getProperty(propertyName, List.class);
            if (elements == null) {
                elements = new ArrayList<>();
                elements.add(newEdge.getId().toString());
                reverseVertex.setProperty(propertyName, elements);
            } else {
                if (!elements.contains(newEdge.getId().toString())) {
                    elements.add(newEdge.getId().toString());
                    reverseVertex.setProperty(propertyName, elements);
                }
            }
            break;
    }
    RequestContext requestContext = RequestContext.get();
    GraphHelper.setProperty(reverseVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, requestContext.getRequestTime());
    requestContext.recordEntityUpdate(reverseId._getId());
}
Also used : Id(org.apache.atlas.typesystem.persistence.Id) RequestContext(org.apache.atlas.RequestContext)

Example 9 with RequestContext

use of org.apache.atlas.RequestContext in project incubator-atlas by apache.

the class AtlasAuthenticationFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);
                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }
                if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);
                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser, Servlets.getRequestURI(httpRequest));
                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };
    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");
        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(), "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) User(org.springframework.security.core.userdetails.User) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) RequestContext(org.apache.atlas.RequestContext)

Example 10 with RequestContext

use of org.apache.atlas.RequestContext in project incubator-atlas by apache.

the class FullTextMapper method mapRecursive.

public String mapRecursive(AtlasVertex instanceVertex, boolean followReferences) throws AtlasException {
    String guid = GraphHelper.getGuid(instanceVertex);
    ITypedReferenceableInstance typedReference;
    RequestContext context = RequestContext.get();
    typedReference = context.getInstanceV1(guid);
    if (typedReference != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cache hit: guid = {}, entityId = {}", guid, typedReference.getId()._getId());
        }
    } else {
        typedReference = graphToTypedInstanceMapper.mapGraphToTypedInstance(guid, instanceVertex);
        context.cache(typedReference);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cache miss: guid = {}, entityId = {}", guid, typedReference.getId().getId());
        }
    }
    String fullText = forInstance(typedReference, followReferences);
    StringBuilder fullTextBuilder = new StringBuilder(typedReference.getTypeName()).append(FULL_TEXT_DELIMITER).append(fullText);
    List<String> traits = typedReference.getTraits();
    for (String traitName : traits) {
        String traitText = forInstance((ITypedInstance) typedReference.getTrait(traitName), false);
        fullTextBuilder.append(FULL_TEXT_DELIMITER).append(traitName).append(FULL_TEXT_DELIMITER).append(traitText);
    }
    return fullTextBuilder.toString();
}
Also used : ITypedReferenceableInstance(org.apache.atlas.typesystem.ITypedReferenceableInstance) RequestContext(org.apache.atlas.RequestContext)

Aggregations

RequestContext (org.apache.atlas.RequestContext)12 AtlasException (org.apache.atlas.AtlasException)4 GraphTransaction (org.apache.atlas.annotation.GraphTransaction)4 RepositoryException (org.apache.atlas.repository.RepositoryException)4 AtlasVertex (org.apache.atlas.repository.graphdb.AtlasVertex)4 ITypedReferenceableInstance (org.apache.atlas.typesystem.ITypedReferenceableInstance)3 Id (org.apache.atlas.typesystem.persistence.Id)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 CreateUpdateEntitiesResult (org.apache.atlas.CreateUpdateEntitiesResult)2 GuidMapping (org.apache.atlas.model.instance.GuidMapping)2 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 List (java.util.List)1 FilterChain (javax.servlet.FilterChain)1 ServletRequest (javax.servlet.ServletRequest)1 ServletResponse (javax.servlet.ServletResponse)1 AtlasEntityWithExtInfo (org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo)1 EntityResult (org.apache.atlas.model.legacy.EntityResult)1