Adds a new trait to an existing entity represented by a guid.

@param guid          globally unique identifier for the entity
@param traitInstance trait instance that needs to be added to entity
@throws RepositoryException
963275
@Override
    @GraphTransaction
    public void addTrait(String guid, ITypedStruct traitInstance) throws RepositoryException {
        Preconditions.checkNotNull(guid, "guid cannot be null");
        Preconditions.checkNotNull(traitInstance, "Trait instance cannot be null");

        GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid);
        addTraitImpl(guid, traitInstance);
    }
327167
@Override
    public IDataType onTypeFault(String typeName) throws AtlasException {

        // Type is not cached - check the type store.
        // Any super and attribute types needed by the requested type
        // which are not cached will also be loaded from the store.
        Context context = new Context();
        TypesDef typesDef = getTypeFromStore(typeName, context);
        if (typesDef.isEmpty()) {
            // Type not found in the type store.
            return null;
        }

        // Add all types that were loaded from the store to the cache.
        TransientTypeSystem transientTypeSystem = typeSystem.createTransientTypeSystem(context.getTypesDef(), false);
        Map<String, IDataType> typesAdded = transientTypeSystem.getTypesAdded();
        putAll(typesAdded.values());
        return typesAdded.get(typeName);
    }
460106
public void eInit(XtendTypeDeclaration container, String name, IJvmTypeProvider context) {
		if (this.sarlEnumeration == null) {
			this.container = container;
			this.sarlEnumeration = SarlFactory.eINSTANCE.createSarlEnumeration();
			container.getMembers().add(this.sarlEnumeration);
			if (!Strings.isEmpty(name)) {
				this.sarlEnumeration.setName(name);
			}
		}
	}
533751
public function addTrait(string $traitName, string $alias = null)
    {
        $this->traits[] = $this->addUse($traitName, $alias);

        return $this;
    }
1818
@VisibleForTesting
    public static List<IStruct> getAllTraits(IReferenceableInstance entityDefinition,
                                              TypeSystem typeSystem) throws AtlasException {
        List<IStruct> traitInfo = new LinkedList<>();
        for (String traitName : entityDefinition.getTraits()) {
            IStruct trait = entityDefinition.getTrait(traitName);
            String typeName = trait.getTypeName();
            Map<String, Object> valuesMap = trait.getValuesMap();
            traitInfo.add(new Struct(typeName, valuesMap));
            traitInfo.addAll(getSuperTraits(typeName, valuesMap, typeSystem));
        }
        return traitInfo;
    }
1172665
@Override
    @GraphTransaction
    public void deleteTrait(String guid, String traitNameToBeDeleted) throws TraitNotFoundException, EntityNotFoundException, RepositoryException {
        LOG.debug("Deleting trait={} from entity={}", traitNameToBeDeleted, guid);
        GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid);

        AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid);

        List<String> traitNames = GraphHelper.getTraitNames(instanceVertex);
        if (!traitNames.contains(traitNameToBeDeleted)) {
                throw new TraitNotFoundException(
                        "Could not find trait=" + traitNameToBeDeleted + " in the repository for entity: " + guid);
        }

        try {
            final String entityTypeName = GraphHelper.getTypeName(instanceVertex);
            String relationshipLabel = GraphHelper.getTraitLabel(entityTypeName, traitNameToBeDeleted);
            AtlasEdge edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel);
            if(edge != null) {
                deleteHandler.deleteEdgeReference(edge, DataTypes.TypeCategory.TRAIT, false, true);
            }

            // update the traits in entity once trait removal is successful
            traitNames.remove(traitNameToBeDeleted);
            updateTraits(instanceVertex, traitNames);
        } catch (Exception e) {
            throw new RepositoryException(e);
        }
    }
1310365
private void addValues(final Document doc, final PropertyData prop) throws RepositoryException
   {
      int propType = prop.getType();
      String fieldName = resolver.createJCRName(prop.getQPath().getName()).getAsString();
      if (propType == PropertyType.BINARY)
      {
         InternalQName propName = prop.getQPath().getName();
         List<ValueData> data = null;
         if (node.getQPath().getName().equals(Constants.JCR_CONTENT) && isIndexed(propName))
         {

            // seems nt:file found, try for nt:resource props
            PropertyData pmime = node.getProperty(Constants.JCR_MIMETYPE.getAsString());
            if (pmime == null && !node.containAllProperties())
            {
               pmime =
                  (PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_MIMETYPE, 0),
                     ItemType.PROPERTY);
            }

            if (pmime != null && pmime.getValues() != null && !pmime.getValues().isEmpty())
            {
               // ok, have a reader
               // if the prop obtainer from cache it will contains a values,
               // otherwise read prop with values from DM
               PropertyData propData =
                  prop.getValues() != null && !prop.getValues().isEmpty() ? prop : ((PropertyData)stateProvider
                     .getItemData(node, new QPathEntry(Constants.JCR_DATA, 0), ItemType.PROPERTY));

               // index if have jcr:mimeType sibling for this binary property only
               try
               {
                  if (propData == null || (data = propData.getValues()) == null || data.isEmpty())
                  {
                     if (LOG.isDebugEnabled())
                     {
                        LOG.debug("No value found for the property located at " + prop.getQPath().getAsString());
                     }
                     return;
                  }

                  DocumentReader dreader =
                     extractor.getDocumentReader(ValueDataUtil.getString(pmime.getValues().get(0)));

                  // check the jcr:encoding property
                  PropertyData encProp = node.getProperty(Constants.JCR_ENCODING.getAsString());
                  if (encProp == null && !node.containAllProperties())
                  {
                     encProp =
                        (PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_ENCODING, 0),
                           ItemType.PROPERTY);
                  }

                  String encoding = null;
                  if (encProp != null && encProp.getValues() != null && !encProp.getValues().isEmpty())
                  {
                     // encoding parameter used
                     encoding = ValueDataUtil.getString(encProp.getValues().get(0));
                  }
                  else
                  {
                     if (LOG.isDebugEnabled())
                     {
                        LOG.debug("No encoding found for the node located at " + node.getQPath().getAsString());
                     }
                  }

                  if (dreader instanceof AdvancedDocumentReader)
                  {
                     // its a tika document reader that supports getContentAsReader
                     for (ValueData pvd : data)
                     {
                        // tikaDocumentReader will close inputStream, so no need to close it at finally 
                        // statement

                        InputStream is = null;
                        is = pvd.getAsStream();
                        Reader reader;
                        if (encoding != null)
                        {
                           reader = ((AdvancedDocumentReader)dreader).getContentAsReader(is, encoding);
                        }
                        else
                        {
                           reader = ((AdvancedDocumentReader)dreader).getContentAsReader(is);
                        }
                        doc.add(createFulltextField(reader));
                     }
                  }
                  else
                  {
                     // old-style document reader
                     for (ValueData pvd : data)
                     {
                        InputStream is = null;
                        try
                        {
                           is = pvd.getAsStream();
                           Reader reader;
                           if (encoding != null)
                           {
                              reader = new StringReader(dreader.getContentAsText(is, encoding));
                           }
                           else
                           {
                              reader = new StringReader(dreader.getContentAsText(is));
                           }
                           doc.add(createFulltextField(reader));
                        }
                        finally
                        {
                           try
                           {
                              is.close();
                           }
                           catch (Throwable e) //NOSONAR
                           {
                              if (LOG.isTraceEnabled())
                              {
                                 LOG.trace("An exception occurred: " + e.getMessage());
                              }
                           }
                        }
                     }
                  }

                  if (data.size() > 1)
                  {
                     // real multi-valued
                     addMVPName(doc, prop.getQPath().getName());
                  }

               }
               catch (DocumentReadException e)
               {
                  if (LOG.isDebugEnabled())
                  {
                     LOG.debug("Cannot extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
                  }
                  else
                  {
                     LOG.warn("Cannot extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier());
                  }
               }
               catch (HandlerNotFoundException e)
               {
                  // no handler - no index
                  if (LOG.isDebugEnabled())
                  {
                     LOG.debug("Can not indexing the document by path " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
                  }
               }
               catch (IOException e)
               {
                  // no data - no index
                  if (LOG.isDebugEnabled())
                  {
                     LOG.debug("An IO exception occurred while trying to extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
                  }
                  else
                  {
                     LOG.warn("An IO exception occurred while trying to extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier());
                  }
               }
               catch (Exception e)
               {
                  if (LOG.isDebugEnabled())
                  {
                     LOG.debug("An exception occurred while trying to extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
                  }
                  else
                  {
                     LOG.warn("An exception occurred while trying to extract the full text content of the property " + propData.getQPath().getAsString()
                        + ", propery id '" + propData.getIdentifier());
                  }
               }
            }
            else
            {
               if (LOG.isDebugEnabled())
               {
                  LOG.debug("no mime type found for the node located at " + node.getQPath().getAsString());
               }
            }
         }
      }
      else
      {
         try
         {
            // if the prop obtainer from cache it will contains a values, otherwise
            // read prop with values from DM
            // We access to the Item by path to avoid having to rebuild the path if needed in case
            // the indexingLoadBatchingThreshold is enabled only otherwise we get it from the id like
            // before
            PropertyData propData =
               prop.getValues() != null && !prop.getValues().isEmpty() ? prop : (PropertyData)(loadPropertyByName
                  ? stateProvider.getItemData(node, new QPathEntry(prop.getQPath().getName(), 0), ItemType.PROPERTY)
                  : stateProvider.getItemData(prop.getIdentifier()));

            List<ValueData> data;
            if (propData == null || (data = propData.getValues()) == null || data.isEmpty())
            {
               if (LOG.isDebugEnabled())
               {
                  LOG.warn("null value found at property " + prop.getQPath().getAsString());
               }
               return;
            }

            InternalQName name = prop.getQPath().getName();
            for (ValueData value : data)
            {
               switch (propType)
               {
                  case PropertyType.BOOLEAN :
                     if (isIndexed(name))
                     {
                        addBooleanValue(doc, fieldName, ValueDataUtil.getBoolean(value));
                     }
                     break;
                  case PropertyType.DATE :
                     if (isIndexed(name))
                     {
                        addCalendarValue(doc, fieldName, ValueDataUtil.getDate(value));
                     }
                     break;
                  case PropertyType.DOUBLE :
                     if (isIndexed(name))
                     {
                        addDoubleValue(doc, fieldName, ValueDataUtil.getDouble(value));
                     }
                     break;
                  case PropertyType.LONG :
                     if (isIndexed(name))
                     {
                        addLongValue(doc, fieldName, ValueDataUtil.getLong(value));
                     }
                     break;
                  case PropertyType.REFERENCE :
                     if (isIndexed(name))
                     {
                        addReferenceValue(doc, fieldName, ValueDataUtil.getString(value));
                     }
                     break;
                  case PropertyType.PATH :
                     if (isIndexed(name))
                     {
                        addPathValue(doc, fieldName,
                           resolver.createJCRPath(ValueDataUtil.getPath(value)).getAsString(false));
                     }
                     break;
                  case PropertyType.STRING :
                     if (isIndexed(name))
                     {
                        // never fulltext index jcr:uuid String
                        if (name.equals(Constants.JCR_UUID))
                        {
                           addStringValue(doc, fieldName, ValueDataUtil.getString(value), false, false, DEFAULT_BOOST,
                              true);
                        }
                        else
                        {
                           addStringValue(doc, fieldName, ValueDataUtil.getString(value), true,
                              isIncludedInNodeIndex(name), getPropertyBoost(name), useInExcerpt(name));
                        }
                     }
                     break;
                  case PropertyType.NAME :
                     // jcr:primaryType and jcr:mixinTypes are required for correct
                     // node type resolution in queries
                     if (isIndexed(name) || name.equals(Constants.JCR_PRIMARYTYPE)
                        || name.equals(Constants.JCR_MIXINTYPES))
                     {
                        addNameValue(doc, fieldName, resolver.createJCRName(ValueDataUtil.getName(value)).getAsString());
                     }
                     break;
                  case ExtendedPropertyType.PERMISSION :
                     break;
                  default :
                     throw new IllegalArgumentException("illegal internal value type " + propType);
               }
               // add length
               // add not planed
               if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
               {
                  addLength(doc, fieldName, value, propType);
               }
            }
            if (data.size() > 1)
            {
               // real multi-valued
               addMVPName(doc, prop.getQPath().getName());
            }
         }
         catch (RepositoryException e)
         {
            LOG.error("Index of property value error. " + prop.getQPath().getAsString() + ".", e);
            throw new RepositoryException("Index of property value error. " + prop.getQPath().getAsString() + ". " + e,
               e);
         }
      }
   }
467579
@Override
    public ITypedReferenceableInstance getEntityDefinition(String guid) throws AtlasException {
        guid = ParamChecker.notEmpty(guid, "entity id");

        final ITypedReferenceableInstance instance = repository.getEntityDefinition(guid);
        return instance;
    }
299257
public void eInit(XtendTypeDeclaration container, String name, IJvmTypeProvider context) {
		if (this.sarlAnnotationType == null) {
			this.container = container;
			this.sarlAnnotationType = SarlFactory.eINSTANCE.createSarlAnnotationType();
			container.getMembers().add(this.sarlAnnotationType);
			if (!Strings.isEmpty(name)) {
				this.sarlAnnotationType.setName(name);
			}
		}
	}
210763
public void setRepository(String repository) {
        if (meta == null) {
            meta = new EventMeta();
        }
        meta.setRepository(repository);
    }
51288
public EntityResult updateEntityAttribute(final String guid, final String attribute, String value)
            throws AtlasServiceException {
        LOG.debug("Updating entity id: {}, attribute name: {}, attribute value: {}", guid, attribute, value);
        JSONObject response = callAPIWithRetries(API.UPDATE_ENTITY_PARTIAL, value, new ResourceCreator() {
            @Override
            public WebResource createResource() {
                API api = API.UPDATE_ENTITY_PARTIAL;
                WebResource resource = getResource(api, guid);
                resource = resource.queryParam(ATTRIBUTE_NAME, attribute);
                return resource;
            }
        });
        return extractEntityResult(response);
    }
968716
public void eInit(XtendExecutable context, String name, IJvmTypeProvider typeContext) {
		setTypeResolutionContext(typeContext);
		this.context = context;
			this.parameter = SarlFactory.eINSTANCE.createSarlFormalParameter();
			this.parameter.setName(name);
			this.parameter.setParameterType(newTypeRef(this.context, Object.class.getName()));
			this.context.getParameters().add(this.parameter);
	}
833617
public void addInstance(IReferenceableInstance instance) throws AtlasException {

        ClassType classType = typeSystem.getDataType(ClassType.class, instance.getTypeName());
        ITypedReferenceableInstance newInstance = classType.convert(instance, Multiplicity.REQUIRED);
        findReferencedInstancesToPreLoad(newInstance);
        Id id = instance.getId();
        if(mapper.lookupVertex(id) == null) {
            if(id.isAssigned()) {
                guidsToLookup.add(id);
            }
            else {
                addToClassMap(classType, instance);
            }
        }
    }
848260
private void addMVPName(Document doc, InternalQName name) throws RepositoryException
   {
      try
      {
         String propName = resolver.createJCRName(name).getAsString();
         doc.add(new Field(FieldNames.MVP, propName, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS,
            Field.TermVector.NO));
      }
      catch (NamespaceException e)
      {
         // will never happen, prefixes are created dynamically
         if (LOG.isTraceEnabled())
         {
            LOG.trace("An exception occurred: " + e.getMessage());
         }
      }
   }
145187
@GET
    @Path("{guid}/traitDefinitions")
    @Produces(Servlets.JSON_MEDIA_TYPE)
    public Response getTraitDefinitionsForEntity(@PathParam("guid") String guid){
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> EntityResource.getTraitDefinitionsForEntity({})", guid);
        }

        AtlasPerfTracer perf = null;
        try {
            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityResource.getTraitDefinitionsForEntity(" + guid + ")");
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Fetching all trait definitions for entity={}", guid);
            }

            final List<AtlasClassification> classifications = entitiesStore.getClassifications(guid);

            JSONArray traits = new JSONArray();
            for (AtlasClassification classification : classifications) {
                IStruct trait = restAdapters.getTrait(classification);
                traits.put(new JSONObject(InstanceSerialization.toJson(trait, true)));
            }

            JSONObject response = new JSONObject();
            response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId());
            response.put(AtlasClient.RESULTS, traits);
            response.put(AtlasClient.COUNT, traits.length());

            return Response.ok(response).build();
        } catch (AtlasBaseException e) {
            LOG.error("Unable to get trait definition for entity {}", guid, e);
            throw toWebApplicationException(e);
        } catch (IllegalArgumentException e) {
            LOG.error("Unable to get trait definition for entity {}", guid, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
        } catch (WebApplicationException e) {
            LOG.error("Unable to get trait definitions for entity {}", guid, e);
            throw e;
        } catch (Throwable e) {
            LOG.error("Unable to get trait definitions for entity {}", guid, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        } finally {
            AtlasPerfTracer.log(perf);

            if (LOG.isDebugEnabled()) {
                LOG.debug("<== EntityResource.getTraitDefinitionsForEntity({})", guid);
            }
        }
    }
595531
public void addEntity(String alias, String entityName) {
    EntityType entityType = Model.getType(entityName);
    if (null == entityType) { throw new RuntimeException("cannot find entity type for " + entityName); }
    entityTypes.put(alias, entityType);
  }
493126
public void addDocumentParticipantObject(String documentUniqueId, String repositoryUniqueId, String homeCommunityId)
	{
		List<TypeValuePairType> tvp = new LinkedList<>();
        //SEK - 10/19/2011 - added check for empty or null, RE: Issue Tracker artifact artf2295 (was Issue 135)
 		if (!EventUtils.isEmptyOrNull(repositoryUniqueId)) {
			tvp.add(getTypeValuePair("Repository Unique Id", repositoryUniqueId.getBytes()));
		}
		if (!EventUtils.isEmptyOrNull(homeCommunityId)) {
			tvp.add(getTypeValuePair("ihe:homeCommunityID", homeCommunityId.getBytes()));
		}
		
		addParticipantObjectIdentification(
				new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.ReportNumber(), 
				null, 
				null, 
				tvp, 
				documentUniqueId, 
				RFC3881ParticipantObjectTypeCodes.SYSTEM, 
				RFC3881ParticipantObjectTypeRoleCodes.REPORT,
				null, 
				null);
	}