prepare composite index.

@param indexedColumns
@param entityType
@return
421089
private String prepareCompositeIndexName(String indexedColumns, final EntityType entityType, EntityMetadata metadata)
    {
        StringTokenizer tokenizer = new StringTokenizer(indexedColumns, ",");
        StringBuilder builder = new StringBuilder();
        while (tokenizer.hasMoreTokens())
        {
            String fieldName = (String) tokenizer.nextElement();

            StringTokenizer stringTokenizer = new StringTokenizer(fieldName, ".");
            // if need to select embedded columns
            if (stringTokenizer.countTokens() > 1)
            {
                fieldName = stringTokenizer.nextToken();
                String embeddedFieldName = stringTokenizer.nextToken();
                Attribute embeddable = entityType.getAttribute(fieldName);

                EmbeddableType embeddedEntity = (EmbeddableType) kunderaMetadata.getApplicationMetadata()
                        .getMetaModelBuilder(metadata.getPersistenceUnit()).getEmbeddables()
                        .get(((AbstractAttribute) embeddable).getBindableJavaType());

                Attribute embeddedAttribute = embeddedEntity.getAttribute(embeddedFieldName);

                builder.append(((AbstractAttribute) embeddedAttribute).getJPAColumnName());
            }
            else
            {
                builder.append(((AbstractAttribute) entityType.getAttribute(fieldName)).getJPAColumnName());
            }
            builder.append(",");

        }

        // scan embeddable as well for

        builder.deleteCharAt(builder.length() - 1);

        return builder.toString();
    }
809713
private <T, Y> TypedQuery<T> createTypedQueryIn(Class<T> entityCls,
            SingularAttribute<T, Y> attribute, List<Y> values) {
        EntityManager entityManager = this.entityManagerProvider.get();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = builder.createQuery(entityCls);
        Root<T> root = criteriaQuery.from(entityCls);
        Path<Y> path = root.get(attribute);
        CriteriaBuilder.In<Y> in = builder.in(path);
        if (values != null) {
            for (Y val : values) {
                in.value(val);
            }
        }
        return entityManager.createQuery(criteriaQuery.where(in));
    }
939453
private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
    {
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
            throw SchemaException::indexNameInvalid($indexName);
        }

        foreach ($columnNames as $columnName) {
            if (! $this->hasColumn($columnName)) {
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
            }
        }

        return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
    }
827329
public static MappingColumn getMappingColumn(final Class<?> entityType, final String camelColumnName) {
		return getMappingColumn(entityType, SqlKind.NONE, camelColumnName);
	}
571683
public List<ThriftRow> toIndexThriftRow(Object e, EntityMetadata m, String columnFamily)
    {
        List<ThriftRow> indexThriftRows = new ArrayList<ThriftRow>();

        byte[] rowKey = getThriftColumnValue(e, m.getIdAttribute());

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());

        // Add thrift rows for embeddables
        Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(m.getEntityClazz());
        EntityType entityType = metaModel.entity(m.getEntityClazz());

        for (String embeddedFieldName : embeddables.keySet())
        {
            EmbeddableType embeddedColumn = embeddables.get(embeddedFieldName);

            // Index embeddable only when specified by user
            Field embeddedField = (Field) entityType.getAttribute(embeddedFieldName).getJavaMember();
            if (!MetadataUtils.isEmbeddedAtributeIndexable(embeddedField))
            {
                continue;
            }

            Object embeddedObject = PropertyAccessorHelper.getObject(e,
                    (Field) entityType.getAttribute(embeddedFieldName).getJavaMember());
            if (embeddedObject == null)
            {
                continue;
            }
            if (embeddedObject instanceof Collection)
            {
                ElementCollectionCacheManager ecCacheHandler = ElementCollectionCacheManager.getInstance();

                for (Object obj : (Collection) embeddedObject)
                {
                    for (Object column : embeddedColumn.getAttributes())
                    {

                        Attribute columnAttribute = (Attribute) column;
                        String columnName = columnAttribute.getName();
                        if (!MetadataUtils.isColumnInEmbeddableIndexable(embeddedField, columnName))
                        {
                            continue;
                        }
                        // Column Value
                        String id = (String) CassandraDataTranslator.decompose(
                                ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType(), rowKey, false);
                        String superColumnName = ecCacheHandler.getElementCollectionObjectName(id, obj);

                        ThriftRow tr = constructIndexTableThriftRow(columnFamily, embeddedFieldName, obj,
                                columnAttribute, rowKey, superColumnName);
                        if (tr != null)
                        {
                            indexThriftRows.add(tr);
                        }
                    }
                }
            }
            else
            {
                for (Object column : embeddedColumn.getAttributes())
                {
                    Attribute columnAttribute = (Attribute) column;
                    String columnName = columnAttribute.getName();
                    Class<?> columnClass = ((AbstractAttribute) columnAttribute).getBindableJavaType();
                    if (!MetadataUtils.isColumnInEmbeddableIndexable(embeddedField, columnName)
                            || columnClass.equals(byte[].class))
                    {
                        continue;
                    }

                    // No EC Name
                    ThriftRow tr = constructIndexTableThriftRow(columnFamily, embeddedFieldName, embeddedObject,
                            (Attribute) column, rowKey, "");
                    if (tr != null)
                    {
                        indexThriftRows.add(tr);
                    }
                }
            }
        }
        return indexThriftRows;
    }
258897
void writeEntityTypes(Collection<EntityType> entityTypes, XlsxWriter writer) {
    LinkedList<EntityType> sortedEntityTypes = sortEntityTypesAbstractFirst(entityTypes);
    if (!writer.hasSheet(EMX_ENTITIES)) {
      writer.createSheet(EMX_ENTITIES, newArrayList(ENTITIES_ATTRS.keySet()));
    }
    writer.writeRows(sortedEntityTypes.stream().map(EntityTypeMapper::map), EMX_ENTITIES);
  }
195687
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        List entities = new ArrayList<E>();
        for (Object key : keys)
        {
            entities.add(find(entityClass, key));
        }
        return entities;
    }
116915
public void setIndexedAttributes(java.util.Collection<AttributeKeyAndValue> indexedAttributes) {
        if (indexedAttributes == null) {
            this.indexedAttributes = null;
            return;
        }

        this.indexedAttributes = new java.util.ArrayList<AttributeKeyAndValue>(indexedAttributes);
    }
41611
List<String> getColumnList(EntityMetadata m, MetamodelImpl metamodel, String[] results,
        EmbeddableType compoundKey) {
        List<String> columns = new ArrayList<String>();
        if (results != null && results.length > 0) {
            MetamodelImpl metaModel =
                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
            EntityType entity = metaModel.entity(m.getEntityClazz());

            String keyFieldName = CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties,
                ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m));
            for (int i = 1; i < results.length; i++) {
                if (results[i] != null) {
                    if (results[i].indexOf(".") > 0) {
                        String fieldName = results[i].substring(0, results[i].indexOf("."));
                        String embeddedFieldName =
                            results[i].substring(results[i].indexOf(".") + 1, results[i].length());
                        AbstractAttribute attribute = (AbstractAttribute) entity.getAttribute(fieldName);
                        EmbeddableType embeddable = metamodel.embeddable(attribute.getBindableJavaType());
                        Attribute embeddableAttribute = embeddable.getAttribute(embeddedFieldName);
                        columns.add(((AbstractAttribute) embeddableAttribute).getJPAColumnName());
                    } else {
                        Attribute attribute = entity.getAttribute(results[i]);
                        if (attribute == null) {
                            throw new QueryHandlerException("Column type is null for : " + results);
                        } else if (m.getIdAttribute().equals(attribute) && compoundKey != null) {
                            Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
                            for (Field field : fields) {
                                addCompositeIdToColumns(metamodel, compoundKey, columns, field);
                            }
                        } else if (m.getIdAttribute().equals(attribute) && compoundKey == null) {
                            columns.add(keyFieldName);
                        } else {
                            columns.add(((AbstractAttribute) attribute).getJPAColumnName());
                        }
                    }
                }
            }
            return columns;
        }

        if (log.isInfoEnabled()) {
            log.info("No record found, returning null.");
        }
        return null;
    }
977497
private void rebuildNodeIndex(final String entityType) {

		final NodeFactory nodeFactory       = new NodeFactory(SecurityContext.getSuperUserInstance());
		final DatabaseService graphDb       = (DatabaseService) arguments.get("graphDb");
		Iterator<AbstractNode> nodeIterator = null;

		nodeIterator = Iterables.map(nodeFactory, graphDb.getNodesByTypeProperty(entityType)).iterator();

		if (entityType == null) {

			info("Node type not set or no entity class found. Starting (re-)indexing all nodes");

		} else {

			info("Starting (re-)indexing all nodes of type {}", entityType);
		}

		long count = bulkGraphOperation(securityContext, nodeIterator, 1000, "RebuildNodeIndex", new BulkGraphOperation<AbstractNode>() {

			@Override
			public boolean handleGraphObject(SecurityContext securityContext, AbstractNode node) {

				node.addToIndex();

				return true;
			}

			@Override
			public void handleThrowable(SecurityContext securityContext, Throwable t, AbstractNode node) {
				logger.warn("Unable to index node {}: {}", new Object[]{node, t.getMessage()});
			}

			@Override
			public void handleTransactionFailure(SecurityContext securityContext, Throwable t) {
				logger.warn("Unable to index node: {}", t.getMessage());
			}
		});

		info("Done with (re-)indexing {} nodes", count);
	}
317355
public static UserCustomColumn createRelatedIdColumn(int index) {
		return UserCustomColumn.createColumn(index, COLUMN_RELATED_ID,
				GeoPackageDataType.INTEGER, true, null);
	}
375081
public List<IndexField> getIndexMappingFields(String index,final String indexType) throws ElasticSearchException{
		try{
			final List<IndexField> fields = new ArrayList<IndexField>();
			getIndexMapping(index,false,new ResponseHandler<Void>(){

				@Override
				public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();

					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						/**
						 * Map<indexName,Mapping<Type,Properties<fieldName<"fileds",Map<subFieldName,IndexField>>,Type>>>
						 */
						if(!client.isUpper7()) {
							Map<String, Object> map = SimpleStringUtil.json2ObjectWithType(entity.getContent(), new JsonTypeReference<Map<String, Object>>() {
							});
							Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
							while (entries.hasNext()) {
								Map.Entry<String, Object> entry = entries.next();//去最新的映射版本，区别于每天的索引表版本
								Map<String, Map<String, Object>> mapping = (Map<String, Map<String, Object>>) entry.getValue();
								Map<String, Map<String, Object>> typeProperties = (Map<String, Map<String, Object>>) mapping.get("mappings").get(indexType);
								Map<String, Object> properties = (Map<String, Object>) typeProperties.get("properties");
								Iterator<Map.Entry<String, Object>> fileds = properties.entrySet().iterator();
								while (fileds.hasNext()) {
									Map.Entry<String, Object> field = fileds.next();
									IndexField indexField = BuildTool.buildIndexField(field, fields, null);
								}
								break;

							}
						}
						else{
							Map<String, Object> map = SimpleStringUtil.json2ObjectWithType(entity.getContent(), new JsonTypeReference<Map<String, Object>>() {
							});
							Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
							while (entries.hasNext()) {
								Map.Entry<String, Object> entry = entries.next();//去最新的映射版本，区别于每天的索引表版本
								Map<String, Map<String, Object>> index = (Map<String, Map<String, Object>>) entry.getValue();
								Map<String,Object> mapping = index.get("mappings");
								Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
								Iterator<Map.Entry<String, Object>> fileds = properties.entrySet().iterator();
								while (fileds.hasNext()) {
									Map.Entry<String, Object> field = fileds.next();
									IndexField indexField = BuildTool.buildIndexField(field, fields, null);
								}
								break;

							}
						}
						/**
						 * Map<indexName,Properties<fieldName<"fileds",Map<subFieldName,IndexField>>,Type>>
						 */
						return null;

					} else {
						HttpEntity entity = response.getEntity();
						if (entity != null )
							throw new ElasticSearchException(new StringBuilder().append("Unexpected response : " ).append( EntityUtils.toString(entity)).toString(),status);
						else
							throw new ElasticSearchException("Unexpected response status: " + status,status);
					}
				}
			});
			return fields;
		}
		catch(ElasticSearchException e){
			return (List<IndexField>)ResultUtil.hand404HttpRuntimeException(e,Object.class,ResultUtil.OPERTYPE_getIndice);
		}

	}
371411
public static Map<String, MappingColumn> getMappingColumnMap(final Class<?> entityType, final SqlKind kind) {
		return Arrays.stream(MappingUtils.getMappingColumns(entityType, kind))
				.collect(Collectors.toMap(MappingColumn::getCamelName, c -> c));
	}
69048
@TimerJ
    public TableMetadataBuilder addIndex(IndexMetadata indexMetadata) {
        indexes.put(indexMetadata.getName(), indexMetadata);
        return this;
    }
973282
public <T> List<T>  sql(Class<T> beanType,  String entity) throws ElasticSearchException {
		SQLRestResponse result = this.client.executeRequest("/_xpack/sql",entity,   new SQLRestResponseHandler());
		return ResultUtil.buildSQLResult(result,beanType);
	}
384842
public static Triple<String, String, String> buldIndexes(final SQLiteEntity entity,
			ArrayList<Pair<List<String>, Boolean>> indexList, boolean unique, int counter) {
		Triple<String, String, String> result = new Triple<>();
		result.value0 = "";
		result.value1 = "";
		result.value2 = "";

		if (indexList.size() == 0)
			return result;

		String uniqueString;

		if (unique) {
			uniqueString = "UNIQUE ";
		} else {
			uniqueString = "";
		}

		List<String> listCreateIndex = new ArrayList<>();
		List<String> listDropIndex = new ArrayList<>();
		List<String> listUniqueConstraint = new ArrayList<>();

		for (Pair<List<String>, Boolean> index : indexList) {
			final List<String> listUniqueFields = new ArrayList<>();

			String createIndex = String.format(" CREATE %sINDEX idx_%s_%s on %s (%s)", uniqueString,
					entity.getTableName(), counter++, entity.getTableName(), StringUtils.join(index.value0, ", "));
			String dropIndex = String.format(" DROP INDEX IF EXISTS idx_%s_%s", entity.getTableName(), counter);

			final One<Integer> fieldCounter = new One<Integer>(0);
			createIndex = JQLChecker.getInstance().replace(new JQLContext() {

				@Override
				public String getContextDescription() {
					return "While table definition generation for entity " + entity.getName();
				}

				@Override
				public String getName() {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public String getParentName() {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public Finder<SQLProperty> findEntityByName(String entityName) {
					// TODO Auto-generated method stub
					return null;
				}
			}, createIndex, new JQLReplacerListenerImpl(null) {

				@Override
				public String onColumnName(String columnName) {
					fieldCounter.value0++;
					SQLProperty property = entity.findPropertyByName(columnName);

					AssertKripton.assertTrue(property != null, "class '%s' in @%s(indexes) use unknown property '%s'",
							entity.getName(), BindSqlType.class.getSimpleName(), columnName);

					listUniqueFields.add(property.columnName);

					return property.columnName;
				}

				@Override
				public String onColumnFullyQualifiedName(String tableName, String columnName) {
					AssertKripton.fail("Inconsistent state");
					return null;
				}
			});

			AssertKripton.assertTrue(fieldCounter.value0 > 0,
					"class '%s' have @%s(indexes) with no well formed indexes", entity.getName(),
					BindSqlType.class.getSimpleName());

			if (unique) {
				// add unique constraint
				listUniqueConstraint.add(String.format(", UNIQUE (%s)", StringUtils.join(listUniqueFields, ", ")));
			}

			listCreateIndex.add(createIndex);
			listDropIndex.add(dropIndex);
		}

		result.value0 = StringUtils.join(listCreateIndex, ";");
		result.value1 = StringUtils.join(listDropIndex, ";");
		result.value2 = StringUtils.join(listUniqueConstraint, "");

		return result;
	}
731638
@SuppressWarnings("unchecked")
	@Override
	public <E> int delete(final Class<? extends E> entityType, final Object... keys) {
		@SuppressWarnings("rawtypes")
		EntityHandler handler = this.getEntityHandler();
		if (!handler.getEntityType().isAssignableFrom(entityType)) {
			throw new IllegalArgumentException("Entity type not supported");
		}

		try {
			TableMetadata metadata = handler.getMetadata(this.transactionManager, entityType);
			TableMetadata.Column keyColumn = null;
			List<? extends TableMetadata.Column> keyColumns = metadata.getKeyColumns();
			if (keyColumns.size() == 1) {
				keyColumn = keyColumns.get(0);
			} else if (keyColumns.isEmpty()) {
				keyColumn = metadata.getColumns().get(0);
			} else {
				throw new IllegalArgumentException("Entity has multiple keys");
			}
			return delete(entityType).in(keyColumn.getCamelColumnName(), keys).count();
		} catch (SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.DELETE, e);
		}
	}