index
int64 0
0
| repo_id
stringlengths 26
205
| file_path
stringlengths 51
246
| content
stringlengths 8
433k
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris connector classes.
*/
package com.netflix.metacat.connector.polaris;
| 0 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/common/PolarisConnectorConsts.java | package com.netflix.metacat.connector.polaris.common;
/**
* Polaris connector consts.
*/
public final class PolarisConnectorConsts {
/**
* Max number of client-side retries for CRDB txns.
*/
public static final int MAX_CRDB_TXN_RETRIES = 5;
/**
* Default Ctor.
*/
private PolarisConnectorConsts() {
}
}
| 1 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/common/TransactionRetryAspect.java | package com.netflix.metacat.connector.polaris.common;
import com.google.common.base.Throwables;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import com.netflix.metacat.common.server.monitoring.Metrics;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.retry.RetryException;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.sql.SQLException;
/**
* Aspect for client-side transaction retries.
*/
@Aspect
@Slf4j
public class TransactionRetryAspect implements Ordered {
private static final String SQLSTATE_RETRY_TRANSACTION = "40001";
private final RetryTemplate retryTemplate;
private final ConnectorContext connectorContext;
/**
* Constructor.
*
* @param retryTemplate retry template.
* @param connectorContext the connector context.
*/
public TransactionRetryAspect(final RetryTemplate retryTemplate,
final ConnectorContext connectorContext) {
this.retryTemplate = retryTemplate;
this.connectorContext = connectorContext;
}
/**
* Pointcut for transactional methods in Polaris persistence classes.
*
* @param pjp joint point
* @return data results
* @throws Exception data exception
*/
@Around(value = "@annotation(org.springframework.transaction.annotation.Transactional)"
+ "&& within(com.netflix.metacat.connector.polaris.store..*)")
public Object retry(final ProceedingJoinPoint pjp) throws Exception {
return retryOnError(pjp);
}
private Object retryOnError(final ProceedingJoinPoint pjp) throws Exception {
return retryTemplate.<Object, Exception>execute(context -> {
try {
return pjp.proceed();
} catch (Throwable t) {
if (!TransactionSynchronizationManager.isActualTransactionActive() && isRetryError(t)) {
log.warn("Transaction failed with retry error: {}", t.getMessage());
connectorContext.getRegistry().counter(
Metrics.CounterTransactionRetryFailure.getMetricName()).increment();
throw new RetryException("TransactionRetryError", t);
}
throw new RuntimeException(t);
}
});
}
private boolean isRetryError(final Throwable t) {
for (Throwable ex : Throwables.getCausalChain(t)) {
if (ex instanceof SQLException && SQLSTATE_RETRY_TRANSACTION.equals(((SQLException) ex).getSQLState())) {
return true;
}
}
return false;
}
@Override
public int getOrder() {
return 99;
}
}
| 2 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/common/PolarisUtils.java | package com.netflix.metacat.connector.polaris.common;
import com.netflix.metacat.common.server.connectors.ConnectorRequestContext;
import org.apache.commons.lang3.StringUtils;
/**
* Polaris connector utils.
*/
public final class PolarisUtils {
/**
* Default metacat user.
*/
public static final String DEFAULT_METACAT_USER = "metacat_user";
/**
* Default Ctor.
*/
private PolarisUtils() {
}
/**
* Get the user name from the request context or
* a default one if missing.
* @param context The request context.
* @return the user name.
*/
public static String getUserOrDefault(final ConnectorRequestContext context) {
final String userName = context.getUserName();
return StringUtils.isNotBlank(userName) ? userName : DEFAULT_METACAT_USER;
}
}
| 3 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/common/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris connector common classes.
*/
package com.netflix.metacat.connector.polaris.common;
| 4 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/configs/PolarisPersistenceConfig.java | package com.netflix.metacat.connector.polaris.configs;
import com.netflix.metacat.connector.polaris.store.PolarisStoreConnector;
import com.netflix.metacat.connector.polaris.store.PolarisStoreService;
import com.netflix.metacat.connector.polaris.store.repos.PolarisDatabaseRepository;
import com.netflix.metacat.connector.polaris.store.repos.PolarisTableRepository;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* The Polaris Store Persistence config.
*
*/
@Configuration
@EntityScan("com.netflix.metacat.connector.polaris.store.entities")
@EnableJpaRepositories("com.netflix.metacat.connector.polaris.store.repos")
@EnableJpaAuditing
@EnableTransactionManagement(proxyTargetClass = true)
@ImportAutoConfiguration({DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class})
public class PolarisPersistenceConfig {
/**
* Primary datasource. Since connectors can have data sources configured, polaris store JPA needs to be
* explicitly configured.
*
* @param dataSourceProperties datasource properties
* @return Datasource
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(final DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
/**
* Datasource properties.
*
* @return DataSourceProperties
*/
@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
/**
* Get an implementation of {@link PolarisStoreConnector}.
*
* @param repo - PolarisDatabaseRepository
* @param tblRepo - PolarisTableRepository
* @return PolarisStoreConnector
*/
@Bean
public PolarisStoreService polarisStoreService(
final PolarisDatabaseRepository repo, final PolarisTableRepository tblRepo) {
return new PolarisStoreConnector(repo, tblRepo);
}
}
| 5 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/configs/PolarisConnectorConfig.java | package com.netflix.metacat.connector.polaris.configs;
import com.google.common.collect.ImmutableMap;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import com.netflix.metacat.common.server.util.ThreadServiceManager;
import com.netflix.metacat.connector.hive.converters.HiveConnectorInfoConverter;
import com.netflix.metacat.connector.hive.iceberg.IcebergTableCriteria;
import com.netflix.metacat.connector.hive.iceberg.IcebergTableCriteriaImpl;
import com.netflix.metacat.connector.hive.iceberg.IcebergTableHandler;
import com.netflix.metacat.connector.hive.iceberg.IcebergTableOpWrapper;
import com.netflix.metacat.connector.hive.iceberg.IcebergTableOpsProxy;
import com.netflix.metacat.connector.polaris.PolarisConnectorDatabaseService;
import com.netflix.metacat.connector.polaris.PolarisConnectorPartitionService;
import com.netflix.metacat.connector.polaris.PolarisConnectorTableService;
import com.netflix.metacat.connector.polaris.common.PolarisConnectorConsts;
import com.netflix.metacat.connector.polaris.common.TransactionRetryAspect;
import com.netflix.metacat.connector.polaris.mappers.PolarisTableMapper;
import com.netflix.metacat.connector.polaris.store.PolarisStoreService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.retry.RetryException;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
/**
* Config for polaris connector.
*/
public class PolarisConnectorConfig {
/**
* Creates a new instance of a polaris connector partition service.
*
* @param icebergTableHandler iceberg table handler
* @param connectorContext connector context
* @param polarisTableService polaris table service
* @return PolarisConnectorPartitionService
*/
@Bean
public PolarisConnectorPartitionService polarisConnectorPartitionService(
final IcebergTableHandler icebergTableHandler,
final ConnectorContext connectorContext,
final PolarisConnectorTableService polarisTableService) {
return new PolarisConnectorPartitionService(connectorContext, icebergTableHandler, polarisTableService);
}
/**
* Create polaris connector database service.
*
* @param polarisStoreService polaris store service
* @param connectorContext connector context
* @return PolarisConnectorDatabaseService
*/
@Bean
@ConditionalOnMissingBean(PolarisConnectorDatabaseService.class)
public PolarisConnectorDatabaseService polarisDatabaseService(
final PolarisStoreService polarisStoreService,
final ConnectorContext connectorContext
) {
return new PolarisConnectorDatabaseService(polarisStoreService, connectorContext);
}
/**
* Create polaris connector table service.
*
* @param polarisStoreService polaris connector
* @param connectorConverter connector converter
* @param connectorDatabaseService polaris database service
* @param icebergTableHandler iceberg table handler
* @param polarisTableMapper polaris table mapper
* @param connectorContext connector context
* @return PolarisConnectorTableService
*/
@Bean
@ConditionalOnMissingBean(PolarisConnectorTableService.class)
public PolarisConnectorTableService polarisTableService(
final PolarisStoreService polarisStoreService,
final HiveConnectorInfoConverter connectorConverter,
final PolarisConnectorDatabaseService connectorDatabaseService,
final IcebergTableHandler icebergTableHandler,
final PolarisTableMapper polarisTableMapper,
final ConnectorContext connectorContext
) {
return new PolarisConnectorTableService(
polarisStoreService,
connectorContext.getCatalogName(),
connectorDatabaseService,
connectorConverter,
icebergTableHandler,
polarisTableMapper,
connectorContext
);
}
/**
* Create PolarisTableMapper.
* @param connectorContext server context
* @return PolarisTableMapper.
*/
@Bean
public PolarisTableMapper polarisTableMapper(final ConnectorContext connectorContext) {
return new PolarisTableMapper(connectorContext.getCatalogName());
}
/**
* Create iceberg table handler.
* @param connectorContext server context
* @param icebergTableCriteria iceberg table criteria
* @param icebergTableOpWrapper iceberg table operation
* @param icebergTableOpsProxy IcebergTableOps proxy
* @return IcebergTableHandler
*/
@Bean
public IcebergTableHandler icebergTableHandler(final ConnectorContext connectorContext,
final IcebergTableCriteria icebergTableCriteria,
final IcebergTableOpWrapper icebergTableOpWrapper,
final IcebergTableOpsProxy icebergTableOpsProxy) {
return new IcebergTableHandler(
connectorContext,
icebergTableCriteria,
icebergTableOpWrapper,
icebergTableOpsProxy);
}
/**
* Create iceberg table criteria.
* @param connectorContext server context
* @return IcebergTableCriteria
*/
@Bean
public IcebergTableCriteria icebergTableCriteria(final ConnectorContext connectorContext) {
return new IcebergTableCriteriaImpl(connectorContext);
}
/**
* Create iceberg table operation wrapper.
* @param connectorContext server context
* @param threadServiceManager executor service
* @return IcebergTableOpWrapper
*/
@Bean
public IcebergTableOpWrapper icebergTableOpWrapper(final ConnectorContext connectorContext,
final ThreadServiceManager threadServiceManager) {
return new IcebergTableOpWrapper(connectorContext, threadServiceManager);
}
/**
* Create thread service manager.
* @param connectorContext connector config
* @return ThreadServiceManager
*/
@Bean
public ThreadServiceManager threadServiceManager(final ConnectorContext connectorContext) {
return new ThreadServiceManager(connectorContext.getRegistry(), connectorContext.getConfig());
}
/**
* Create IcebergTableOps proxy.
* @return IcebergTableOpsProxy
*/
@Bean
public IcebergTableOpsProxy icebergTableOps() {
return new IcebergTableOpsProxy();
}
/**
* Retry template to use for transaction retries.
*
* @return The retry template bean.
*/
@Bean
public RetryTemplate transactionRetryTemplate() {
final RetryTemplate result = new RetryTemplate();
result.setRetryPolicy(new SimpleRetryPolicy(
PolarisConnectorConsts.MAX_CRDB_TXN_RETRIES,
new ImmutableMap.Builder<Class<? extends Throwable>, Boolean>()
.put(RetryException.class, true)
.build()));
result.setBackOffPolicy(new ExponentialBackOffPolicy());
return result;
}
/**
* Aspect advice for transaction retries.
*
* @param retryTemplate the transaction retry template.
* @param connectorContext the connector context.
* @return TransactionRetryAspect
*/
@Bean
public TransactionRetryAspect transactionRetryAspect(
@Qualifier("transactionRetryTemplate") final RetryTemplate retryTemplate,
final ConnectorContext connectorContext) {
return new TransactionRetryAspect(retryTemplate, connectorContext);
}
}
| 6 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/configs/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris config classes.
*/
package com.netflix.metacat.connector.polaris.configs;
| 7 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/mappers/InfoToEntityMapper.java | package com.netflix.metacat.connector.polaris.mappers;
/**
* Info to Entity mapper.
*
* @param <I> The info type to map from.
* @param <E> The entity type to map to.
*/
public interface InfoToEntityMapper<I, E> {
/**
* Maps an info object to an entity object.
*
* @param info The info object to map from.
* @return The result entity object.
*/
E toEntity(I info);
}
| 8 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/mappers/EntityToInfoMapper.java | package com.netflix.metacat.connector.polaris.mappers;
/**
* Entity to Info Mapper.
*
* @param <E> The entity type to map from.
* @param <I> The info type to map to.
*/
public interface EntityToInfoMapper<E, I> {
/**
* Maps an Entity to the Info object.
*
* @param entity The entity to map from.
* @return The result info object.
*/
I toInfo(E entity);
}
| 9 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/mappers/PolarisDatabaseMapper.java | package com.netflix.metacat.connector.polaris.mappers;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.connectors.model.DatabaseInfo;
import com.netflix.metacat.connector.polaris.store.entities.PolarisDatabaseEntity;
/**
* Database object mapper implementations.
*/
public class PolarisDatabaseMapper implements
EntityToInfoMapper<PolarisDatabaseEntity, DatabaseInfo>,
InfoToEntityMapper<DatabaseInfo, PolarisDatabaseEntity> {
// TODO: this can be reworked if PolarisDatabaseEntity starts tracking catalog name
private final String catalogName;
/**
* Constructor.
* @param catalogName the catalog name
*/
public PolarisDatabaseMapper(final String catalogName) {
this.catalogName = catalogName;
}
/**
* {@inheritDoc}.
*/
@Override
public DatabaseInfo toInfo(final PolarisDatabaseEntity entity) {
final DatabaseInfo databaseInfo = DatabaseInfo.builder()
.name(QualifiedName.ofDatabase(catalogName, entity.getDbName()))
.uri(entity.getLocation())
.build();
return databaseInfo;
}
/**
* {@inheritDoc}.
*/
@Override
public PolarisDatabaseEntity toEntity(final DatabaseInfo info) {
final PolarisDatabaseEntity databaseEntity = PolarisDatabaseEntity.builder()
.dbName(info.getName().getDatabaseName())
.location(info.getUri())
.build();
return databaseEntity;
}
}
| 10 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/mappers/PolarisTableMapper.java | package com.netflix.metacat.connector.polaris.mappers;
import com.google.common.collect.ImmutableMap;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.connectors.exception.InvalidMetaException;
import com.netflix.metacat.common.server.connectors.model.AuditInfo;
import com.netflix.metacat.common.server.connectors.model.StorageInfo;
import com.netflix.metacat.common.server.connectors.model.TableInfo;
import com.netflix.metacat.connector.hive.sql.DirectSqlTable;
import com.netflix.metacat.connector.polaris.store.entities.PolarisTableEntity;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import java.sql.Date;
import java.util.Map;
/**
* Table object mapper implementations.
*/
public class PolarisTableMapper implements
EntityToInfoMapper<PolarisTableEntity, TableInfo>,
InfoToEntityMapper<TableInfo, PolarisTableEntity> {
private static final String PARAMETER_SPARK_SQL_PROVIDER = "spark.sql.sources.provider";
private static final String PARAMETER_EXTERNAL = "EXTERNAL";
private static final String PARAMETER_METADATA_PREFIX = "/metadata/";
private final String catalogName;
/**
* Constructor.
* @param catalogName the catalog name
*/
public PolarisTableMapper(final String catalogName) {
this.catalogName = catalogName;
}
/**
* {@inheritDoc}.
*/
@Override
public TableInfo toInfo(final PolarisTableEntity entity) {
final int uriIndex = entity.getMetadataLocation().indexOf(PARAMETER_METADATA_PREFIX);
final TableInfo tableInfo = TableInfo.builder()
.name(QualifiedName.ofTable(catalogName, entity.getDbName(), entity.getTblName()))
.metadata(ImmutableMap.of(
DirectSqlTable.PARAM_METADATA_LOCATION, entity.getMetadataLocation(),
PARAMETER_EXTERNAL, "TRUE", PARAMETER_SPARK_SQL_PROVIDER, "iceberg",
DirectSqlTable.PARAM_TABLE_TYPE, DirectSqlTable.ICEBERG_TABLE_TYPE))
.serde(StorageInfo.builder().inputFormat("org.apache.hadoop.mapred.FileInputFormat")
.outputFormat("org.apache.hadoop.mapred.FileOutputFormat")
.serializationLib("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe")
.uri(uriIndex > 0 ? entity.getMetadataLocation().substring(0, uriIndex) : "")
.build())
.auditInfo(AuditInfo.builder()
.createdBy(entity.getAudit().getCreatedBy())
.createdDate(Date.from(entity.getAudit().getCreatedDate()))
.lastModifiedBy(entity.getAudit().getLastModifiedBy())
.lastModifiedDate(Date.from(entity.getAudit().getLastModifiedDate()))
.build())
.build();
return tableInfo;
}
/**
* {@inheritDoc}.
*/
@Override
public PolarisTableEntity toEntity(final TableInfo info) {
final Map<String, String> metadata = info.getMetadata();
if (MapUtils.isEmpty(metadata)) {
final String message = String.format("No parameters defined for iceberg table %s", info.getName());
throw new InvalidMetaException(info.getName(), message, null);
}
final String location = metadata.get(DirectSqlTable.PARAM_METADATA_LOCATION);
if (StringUtils.isEmpty(location)) {
final String message = String.format("No metadata location defined for iceberg table %s", info.getName());
throw new InvalidMetaException(info.getName(), message, null);
}
final PolarisTableEntity tableEntity = PolarisTableEntity.builder()
.dbName(info.getName().getDatabaseName())
.tblName(info.getName().getTableName())
.metadataLocation(location)
.build();
return tableEntity;
}
}
| 11 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/mappers/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris mapper classes.
*/
package com.netflix.metacat.connector.polaris.mappers;
| 12 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/PolarisStoreService.java | package com.netflix.metacat.connector.polaris.store;
import com.netflix.metacat.connector.polaris.store.entities.PolarisDatabaseEntity;
import com.netflix.metacat.connector.polaris.store.entities.PolarisTableEntity;
import java.util.List;
import java.util.Optional;
/**
* Interface methods for Polaris Store CRUD access.
*/
public interface PolarisStoreService {
/**
* Creates a database entry.
* @param databaseName database name
* @param location the database location.
* @param createdBy user creating this database.
* @return Polaris Database entity.
*/
PolarisDatabaseEntity createDatabase(String databaseName, String location, String createdBy);
/**
* Fetches database entry.
* @param databaseName database name
* @return Polaris Database entity
*/
Optional<PolarisDatabaseEntity> getDatabase(String databaseName);
/**
* Deletes the database entry.
* @param dbName database name.
*/
void deleteDatabase(String dbName);
/**
* Fetches all database entities.
* @return Polaris Database entities
*/
List<PolarisDatabaseEntity> getAllDatabases();
/**
* Checks if database with the name exists.
* @param databaseName database name to look up.
* @return true, if database exists. false, otherwise.
*/
boolean databaseExists(String databaseName);
/**
* Updates existing database entity.
* @param databaseEntity databaseEntity to save.
* @return the saved database entity.
*/
PolarisDatabaseEntity saveDatabase(PolarisDatabaseEntity databaseEntity);
/**
* Creates a table entry.
* @param dbName database name
* @param tableName table name
* @param metadataLocation metadata location
* @param createdBy user creating this table.
* @return Polaris Table entity.
*/
PolarisTableEntity createTable(String dbName, String tableName, String metadataLocation, String createdBy);
/**
* Fetches table entry.
* @param dbName database name
* @param tableName table name
* @return Polaris Table entity
*/
Optional<PolarisTableEntity> getTable(String dbName, String tableName);
/**
* Fetch table entities for given database.
* @param databaseName database name
* @param tableNamePrefix table name prefix. can be empty.
* @return table entities in the database.
*/
List<PolarisTableEntity> getTableEntities(final String databaseName, final String tableNamePrefix);
/**
* Updates existing or creates new table entry.
* @param tableEntity tableEntity to save.
* @return The saved entity.
*/
PolarisTableEntity saveTable(PolarisTableEntity tableEntity);
/**
* Deletes the table entry.
* @param dbName database name.
* @param tableName table name.
*/
void deleteTable(String dbName, String tableName);
/**
* Checks if table with the name exists.
* @param databaseName database name of the table to be looked up.
* @param tableName table name to look up.
* @return true, if table exists. false, otherwise.
*/
boolean tableExists(String databaseName, String tableName);
/**
* Gets tables in the database and tableName prefix.
* @param databaseName database name
* @param tableNamePrefix table name prefix
* @return list of table names in the database with the table name prefix.
*/
List<String> getTables(String databaseName, String tableNamePrefix);
/**
* Do an atomic compare-and-swap to update the table's metadata location.
* @param databaseName database name of the table
* @param tableName table name
* @param expectedLocation expected current metadata-location of the table
* @param newLocation new metadata location of the table
* @param lastModifiedBy user updating the location.
* @return true, if update was successful. false, otherwise.
*/
boolean updateTableMetadataLocation(
String databaseName, String tableName,
String expectedLocation, String newLocation,
String lastModifiedBy);
}
| 13 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/PolarisStoreConnector.java | package com.netflix.metacat.connector.polaris.store;
import com.netflix.metacat.connector.polaris.store.entities.AuditEntity;
import com.netflix.metacat.connector.polaris.store.entities.PolarisDatabaseEntity;
import com.netflix.metacat.connector.polaris.store.entities.PolarisTableEntity;
import com.netflix.metacat.connector.polaris.store.repos.PolarisDatabaseRepository;
import com.netflix.metacat.connector.polaris.store.repos.PolarisTableRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* This class exposes APIs for CRUD operations.
*/
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PolarisStoreConnector implements PolarisStoreService {
private final PolarisDatabaseRepository dbRepo;
private final PolarisTableRepository tblRepo;
/**
* Creates entry for new database.
* @param databaseName database name
* @return entity
*/
@Override
public PolarisDatabaseEntity createDatabase(final String databaseName,
final String location,
final String createdBy) {
final PolarisDatabaseEntity e = new PolarisDatabaseEntity(databaseName, location, createdBy);
return dbRepo.save(e);
}
/**
* Fetches database entry.
*
* @param databaseName database name
* @return Polaris Database entity
*/
@Override
public Optional<PolarisDatabaseEntity> getDatabase(final String databaseName) {
return dbRepo.findByDbName(databaseName);
}
/**
* Deletes the database entry.
*
* @param dbName database name.
*/
@Override
public void deleteDatabase(final String dbName) {
dbRepo.deleteByName(dbName);
}
/**
* Fetches all database entities.
*
* @return Polaris Database entities
*/
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<PolarisDatabaseEntity> getAllDatabases() {
final int pageFetchSize = 1000;
final List<PolarisDatabaseEntity> retval = new ArrayList<>();
Pageable page = PageRequest.of(0, pageFetchSize);
boolean hasNext;
do {
final Slice<PolarisDatabaseEntity> dbs = dbRepo.getDatabases(page);
retval.addAll(dbs.toList());
hasNext = dbs.hasNext();
if (hasNext) {
page = dbs.nextPageable();
}
} while (hasNext);
return retval;
}
/**
* Checks if database with the name exists.
*
* @param databaseName database name to look up.
* @return true, if database exists. false, otherwise.
*/
@Override
public boolean databaseExists(final String databaseName) {
return dbRepo.existsByDbName(databaseName);
}
/**
* Updates existing database entity, or creates a new one if not present.
*
* @param databaseEntity databaseEntity to save.
* @return the saved database entity.
*/
@Override
public PolarisDatabaseEntity saveDatabase(final PolarisDatabaseEntity databaseEntity) {
return dbRepo.save(databaseEntity);
}
boolean databaseExistsById(final String dbId) {
return dbRepo.existsById(dbId);
}
/**
* Creates entry for new table.
* @param dbName database name
* @param tableName table name
* @param metadataLocation metadata location of the table.
* @param createdBy user creating this table.
* @return entity corresponding to created table entry
*/
@Override
public PolarisTableEntity createTable(final String dbName,
final String tableName,
final String metadataLocation,
final String createdBy) {
final AuditEntity auditEntity = AuditEntity.builder()
.createdBy(createdBy)
.lastModifiedBy(createdBy)
.build();
final PolarisTableEntity e = PolarisTableEntity.builder()
.audit(auditEntity)
.dbName(dbName)
.tblName(tableName)
.metadataLocation(metadataLocation)
.build();
return tblRepo.save(e);
}
/**
* Fetches table entry.
*
* @param tableName table name
* @return Polaris Table entity
*/
@Override
public Optional<PolarisTableEntity> getTable(final String dbName, final String tableName) {
return tblRepo.findByDbNameAndTblName(dbName, tableName);
}
/**
* Fetch table entities for given database.
* @param databaseName database name
* @param tableNamePrefix table name prefix. can be empty.
* @return table entities in the database.
*/
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<PolarisTableEntity> getTableEntities(final String databaseName, final String tableNamePrefix) {
final int pageFetchSize = 1000;
final List<PolarisTableEntity> retval = new ArrayList<>();
final String tblPrefix = tableNamePrefix == null ? "" : tableNamePrefix;
Pageable page = PageRequest.of(0, pageFetchSize, Sort.by("tblName").ascending());
Slice<PolarisTableEntity> tbls;
boolean hasNext;
do {
tbls = tblRepo.findAllTablesByDbNameAndTablePrefix(databaseName, tblPrefix, page);
retval.addAll(tbls.toList());
hasNext = tbls.hasNext();
if (hasNext) {
page = tbls.nextPageable();
}
} while (hasNext);
return retval;
}
/**
* Updates existing table entry.
*
* @param tableEntity tableEntity to save.
* @return The saved entity.
*/
@Override
public PolarisTableEntity saveTable(final PolarisTableEntity tableEntity) {
return tblRepo.save(tableEntity);
}
/**
* Deletes entry for table.
* @param dbName database name
* @param tableName table name
*/
@Override
public void deleteTable(final String dbName, final String tableName) {
tblRepo.deleteByName(dbName, tableName);
}
/**
* Checks if table with the name exists.
*
* @param tableName table name to look up.
* @return true, if table exists. false, otherwise.
*/
@Override
public boolean tableExists(final String databaseName, final String tableName) {
return tblRepo.existsByDbNameAndTblName(databaseName, tableName);
}
boolean tableExistsById(final String tblId) {
return tblRepo.existsById(tblId);
}
/**
* Fetch table names for given database.
* @param databaseName database name
* @param tableNamePrefix table name prefix. can be empty.
* @return table names in the database.
*/
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<String> getTables(final String databaseName, final String tableNamePrefix) {
final int pageFetchSize = 1000;
final List<String> retval = new ArrayList<>();
final String tblPrefix = tableNamePrefix == null ? "" : tableNamePrefix;
Pageable page = PageRequest.of(0, pageFetchSize, Sort.by("tblName").ascending());
Slice<String> tblNames = null;
boolean hasNext = true;
do {
tblNames = tblRepo.findAllByDbNameAndTablePrefix(databaseName, tblPrefix, page);
retval.addAll(tblNames.toList());
hasNext = tblNames.hasNext();
if (hasNext) {
page = tblNames.nextPageable();
}
} while (hasNext);
return retval;
}
/**
* Do an atomic compare-and-swap to update the table's metadata location.
*
* @param databaseName database name of the table
* @param tableName table name
* @param expectedLocation expected current metadata-location of the table
* @param newLocation new metadata location of the table
* @param lastModifiedBy user updating the location.
* @return true, if update was successful. false, otherwise.
*/
@Override
public boolean updateTableMetadataLocation(
final String databaseName, final String tableName,
final String expectedLocation, final String newLocation,
final String lastModifiedBy) {
final int updatedRowCount =
tblRepo.updateMetadataLocation(databaseName, tableName,
expectedLocation, newLocation, lastModifiedBy, Instant.now());
return updatedRowCount > 0;
}
}
| 14 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris data classes.
*/
package com.netflix.metacat.connector.polaris.store;
| 15 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/repos/PolarisDatabaseRepository.java | package com.netflix.metacat.connector.polaris.store.repos;
import com.netflix.metacat.connector.polaris.store.entities.PolarisDatabaseEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* JPA repository implementation for storing PolarisDatabaseEntity.
*/
@Repository
public interface PolarisDatabaseRepository extends JpaRepository<PolarisDatabaseEntity, String>,
JpaSpecificationExecutor {
/**
* Fetch database entry.
* @param dbName database name
* @return database entry, if found
*/
Optional<PolarisDatabaseEntity> findByDbName(@Param("dbName") final String dbName);
/**
* Check if database with that name exists.
* @param dbName database name to look up.
* @return true, if database exists. false, otherwise.
*/
boolean existsByDbName(@Param("dbName") final String dbName);
/**
* Delete database entry by name.
* @param dbName database name.
*/
@Modifying
@Query("DELETE FROM PolarisDatabaseEntity e WHERE e.dbName = :dbName")
void deleteByName(@Param("dbName") final String dbName);
/**
* Fetch databases.
* @param page pageable.
* @return database entities.
*/
@Query("SELECT e FROM PolarisDatabaseEntity e")
Slice<PolarisDatabaseEntity> getDatabases(Pageable page);
}
| 16 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/repos/PolarisTableRepository.java | package com.netflix.metacat.connector.polaris.store.repos;
import com.netflix.metacat.connector.polaris.store.entities.PolarisTableEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Optional;
/**
* JPA repository implementation for storing PolarisTableEntity.
*/
@Repository
public interface PolarisTableRepository extends JpaRepository<PolarisTableEntity, String>,
JpaSpecificationExecutor {
/**
* Delete table entry by name.
* @param dbName database name.
* @param tblName table name.
*/
@Modifying
@Query("DELETE FROM PolarisTableEntity e WHERE e.dbName = :dbName AND e.tblName = :tblName")
@Transactional
void deleteByName(
@Param("dbName") final String dbName,
@Param("tblName") final String tblName);
/**
* Fetch table names in database.
* @param dbName database name
* @param tableNamePrefix table name prefix. can be empty.
* @param page pageable.
* @return table names that belong to the database.
*/
@Query("SELECT e.tblName FROM PolarisTableEntity e WHERE e.dbName = :dbName AND e.tblName LIKE :tableNamePrefix%")
Slice<String> findAllByDbNameAndTablePrefix(
@Param("dbName") final String dbName,
@Param("tableNamePrefix") final String tableNamePrefix,
Pageable page);
/**
* Fetch table entry.
* @param dbName database name
* @param tblName table name
* @return optional table entry
*/
Optional<PolarisTableEntity> findByDbNameAndTblName(
@Param("dbName") final String dbName,
@Param("tblName") final String tblName);
/**
* Checks if table with the database name and table name exists.
* @param dbName database name of the table to be looked up.
* @param tblName table name to be looked up.
* @return true, if table exists. false, otherwise.
*/
boolean existsByDbNameAndTblName(
@Param("dbName") final String dbName,
@Param("tblName") final String tblName);
/**
* Fetch table entities in database.
* @param dbName database name
* @param tableNamePrefix table name prefix. can be empty.
* @param page pageable.
* @return table entities that belong to the database.
*/
@Query("SELECT e FROM PolarisTableEntity e WHERE e.dbName = :dbName AND e.tblName LIKE :tableNamePrefix%")
Slice<PolarisTableEntity> findAllTablesByDbNameAndTablePrefix(
@Param("dbName") final String dbName,
@Param("tableNamePrefix") final String tableNamePrefix,
Pageable page);
/**
* Do an atomic compare-and-swap on the metadata location of the table.
* @param dbName database name of the table
* @param tableName table name
* @param expectedLocation expected metadata location before the update is done.
* @param newLocation new metadata location of the table.
* @param lastModifiedBy user updating the location.
* @param lastModifiedDate timestamp for when the location was updated.
* @return number of rows that are updated.
*/
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query("UPDATE PolarisTableEntity t SET t.metadataLocation = :newLocation, "
+ "t.audit.lastModifiedBy = :lastModifiedBy, t.audit.lastModifiedDate = :lastModifiedDate, "
+ "t.previousMetadataLocation = t.metadataLocation, t.version = t.version + 1 "
+ "WHERE t.metadataLocation = :expectedLocation AND t.dbName = :dbName AND t.tblName = :tableName")
@Transactional
int updateMetadataLocation(
@Param("dbName") final String dbName,
@Param("tableName") final String tableName,
@Param("expectedLocation") final String expectedLocation,
@Param("newLocation") final String newLocation,
@Param("lastModifiedBy") final String lastModifiedBy,
@Param("lastModifiedDate") final Instant lastModifiedDate);
}
| 17 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/repos/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris repo classes.
*/
package com.netflix.metacat.connector.polaris.store.repos;
| 18 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/entities/PolarisTableEntity.java | package com.netflix.metacat.connector.polaris.store.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
/**
* Entity class for Table object.
*/
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
@EqualsAndHashCode
@Entity
@ToString(callSuper = true)
@Table(name = "TBLS")
@EntityListeners(AuditingEntityListener.class)
public class PolarisTableEntity {
@Version
private Long version;
@Basic
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "id", nullable = false, unique = true, updatable = false)
private String tblId;
@Basic
@Column(name = "db_name", nullable = false, updatable = false)
private String dbName;
@Basic
@Setter
@Column(name = "tbl_name", nullable = false)
private String tblName;
@Basic
@Setter
@Column(name = "previous_metadata_location", nullable = true, updatable = true)
private String previousMetadataLocation;
@Basic
@Setter
@Column(name = "metadata_location", nullable = true, updatable = true)
private String metadataLocation;
@Embedded
private AuditEntity audit;
/**
* Constructor for Polaris Table Entity.
*
* @param dbName database name
* @param tblName table name
* @param createdBy user that created this entity.
*/
public PolarisTableEntity(final String dbName,
final String tblName,
final String createdBy) {
this.dbName = dbName;
this.tblName = tblName;
this.audit = AuditEntity
.builder()
.createdBy(createdBy)
.lastModifiedBy(createdBy)
.build();
}
}
| 19 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/entities/PolarisDatabaseEntity.java | package com.netflix.metacat.connector.polaris.store.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
/**
* Entity class for Database object.
*/
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
@EqualsAndHashCode
@Entity
@ToString(callSuper = true)
@Table(name = "DBS")
@EntityListeners(AuditingEntityListener.class)
public class PolarisDatabaseEntity {
@Version
private Long version;
@Basic
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "id", nullable = false, unique = true, updatable = false)
private String dbId;
@Basic
@Column(name = "name", nullable = false, unique = true, updatable = false)
private String dbName;
@Basic
@Column(name = "location", updatable = false)
private String location;
@Embedded
private AuditEntity audit;
/**
* Constructor for Polaris Database Entity.
*
* @param dbName database name
* @param location database location.
* @param createdBy user that created this entity.
*/
public PolarisDatabaseEntity(final String dbName,
final String location,
final String createdBy) {
this.dbName = dbName;
this.location = location;
this.audit = AuditEntity
.builder()
.createdBy(createdBy)
.lastModifiedBy(createdBy)
.build();
}
}
| 20 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/entities/AuditEntity.java | package com.netflix.metacat.connector.polaris.store.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.time.Instant;
/**
* Embeddable audit entity.
*
* @author rveeramacheneni
*/
@Embeddable
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString(of = {
"createdBy",
"lastModifiedBy",
"createdDate",
"lastModifiedDate"
})
public class AuditEntity {
@Basic
@Column(name = "created_by")
private String createdBy;
@Basic
@Column(name = "last_updated_by")
private String lastModifiedBy;
@Basic
@Column(name = "created_date", updatable = false, nullable = false)
@CreatedDate
private Instant createdDate;
@Basic
@Column(name = "last_updated_date", nullable = false)
@LastModifiedDate
private Instant lastModifiedDate;
}
| 21 |
0 | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store | Create_ds/metacat/metacat-connector-polaris/src/main/java/com/netflix/metacat/connector/polaris/store/entities/package-info.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Polaris entity classes.
*/
package com.netflix.metacat.connector.polaris.store.entities;
| 22 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeExceptionMapper.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.connectors.exception.ConnectorException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseNotFoundException;
import com.netflix.metacat.common.server.connectors.exception.TableAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.TableNotFoundException;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import java.sql.SQLException;
/**
* Exception mapper for Snowflake SQLExceptions.
*
* @author amajumdar
* @see SQLException
* @see ConnectorException
* @since 1.2.0
*/
public class SnowflakeExceptionMapper implements JdbcExceptionMapper {
/**
* {@inheritDoc}
*/
@Override
public ConnectorException toConnectorException(
final SQLException se,
final QualifiedName name
) {
final int errorCode = se.getErrorCode();
switch (errorCode) {
case 2042: //database already exists
return new DatabaseAlreadyExistsException(name, se);
case 2002: //table already exists
return new TableAlreadyExistsException(name, se);
case 2043: //database does not exist
return new DatabaseNotFoundException(name, se);
case 2003: //table doesn't exist
return new TableNotFoundException(name, se);
default:
return new ConnectorException(se.getMessage(), se);
}
}
}
| 23 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeConnectorModule.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.netflix.metacat.common.server.connectors.ConnectorDatabaseService;
import com.netflix.metacat.common.server.connectors.ConnectorPartitionService;
import com.netflix.metacat.common.server.connectors.ConnectorTableService;
import com.netflix.metacat.common.server.connectors.ConnectorUtils;
import com.netflix.metacat.common.server.util.DataSourceManager;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorDatabaseService;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorPartitionService;
import javax.sql.DataSource;
import java.util.Map;
/**
* Guice module for the Snowflake Connector.
*
* @author amajumdar
* @since 1.2.0
*/
public class SnowflakeConnectorModule extends AbstractModule {
private final String catalogShardName;
private final Map<String, String> configuration;
/**
* Constructor.
*
* @param catalogShardName unique catalog shard name
* @param configuration connector configuration
*
*/
public SnowflakeConnectorModule(
final String catalogShardName,
final Map<String, String> configuration
) {
this.catalogShardName = catalogShardName;
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
@Override
protected void configure() {
this.bind(DataSource.class).toInstance(DataSourceManager.get()
.load(this.catalogShardName, this.configuration).get(this.catalogShardName));
this.bind(JdbcTypeConverter.class).to(SnowflakeTypeConverter.class).in(Scopes.SINGLETON);
this.bind(JdbcExceptionMapper.class).to(SnowflakeExceptionMapper.class).in(Scopes.SINGLETON);
this.bind(ConnectorDatabaseService.class)
.to(ConnectorUtils.getDatabaseServiceClass(this.configuration, JdbcConnectorDatabaseService.class))
.in(Scopes.SINGLETON);
this.bind(ConnectorTableService.class)
.to(ConnectorUtils.getTableServiceClass(this.configuration, SnowflakeConnectorTableService.class))
.in(Scopes.SINGLETON);
this.bind(ConnectorPartitionService.class)
.to(ConnectorUtils.getPartitionServiceClass(this.configuration, JdbcConnectorPartitionService.class))
.in(Scopes.SINGLETON);
}
}
| 24 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeTypeConverter.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.netflix.metacat.common.type.BaseType;
import com.netflix.metacat.common.type.CharType;
import com.netflix.metacat.common.type.DecimalType;
import com.netflix.metacat.common.type.Type;
import com.netflix.metacat.common.type.VarcharType;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import lombok.extern.slf4j.Slf4j;
/**
* Type converter for Snowflake.
*
* @author amajumdar
* @since 1.2.0
*/
@Slf4j
public class SnowflakeTypeConverter extends JdbcTypeConverter {
static final int DEFAULT_CHARACTER_LENGTH = 256;
private static final String DEFAULT_CHARACTER_LENGTH_STRING = Integer.toString(DEFAULT_CHARACTER_LENGTH);
/**
* {@inheritDoc}
*
* @see <a href="https://docs.snowflake.net/manuals/sql-reference/data-types.html">Snowflake Types</a>
*/
@Override
public Type toMetacatType(final String type) {
final String lowerType = type.toLowerCase();
// Split up the possible type: TYPE[(size, magnitude)] EXTRA
final String[] splitType = this.splitType(lowerType);
switch (splitType[0]) {
case "smallint":
case "tinyint":
case "byteint":
return BaseType.SMALLINT;
case "int":
case "integer":
return BaseType.INT;
case "bigint":
return BaseType.BIGINT;
case "number":
case "decimal":
case "numeric":
return this.toMetacatDecimalType(splitType);
case "real":
case "float4":
return BaseType.FLOAT;
case "double":
case "double precision":
case "float8":
case "float":
return BaseType.DOUBLE;
case "varchar":
fixDataSizeIfIncorrect(splitType);
return this.toMetacatVarcharType(splitType);
case "text":
case "string":
// text is basically alias for VARCHAR(256)
splitType[1] = DEFAULT_CHARACTER_LENGTH_STRING;
return this.toMetacatVarcharType(splitType);
case "character":
case "char":
fixDataSizeIfIncorrect(splitType);
return this.toMetacatCharType(splitType);
case "binary":
case "varbinary":
fixDataSizeIfIncorrect(splitType);
return this.toMetacatVarbinaryType(splitType);
case "timestamp":
case "datetime":
case "timestamp_ntz":
case "timestampntz":
case "timestamp without time zone":
return this.toMetacatTimestampType(splitType);
case "timestamp_tz":
case "timestamptz":
case "timestampltz":
case "timestamp_ltz":
case "timestamp with local time zone":
case "timestamp with time zone":
return BaseType.TIMESTAMP_WITH_TIME_ZONE;
case "date":
return BaseType.DATE;
case "boolean":
return BaseType.BOOLEAN;
default:
log.info("Unhandled or unknown Snowflake type {}", splitType[0]);
return BaseType.UNKNOWN;
}
}
private void fixDataSizeIfIncorrect(final String[] splitType) {
//
// Adding a hack to ignore errors for data type with negative size.
// TODO: Remove this hack when we have a solution for the above.
//
if (splitType[1] == null || Integer.parseInt(splitType[1]) <= 0) {
splitType[1] = DEFAULT_CHARACTER_LENGTH_STRING;
}
}
/**
* {@inheritDoc}
*/
@Override
public String fromMetacatType(final Type type) {
switch (type.getTypeSignature().getBase()) {
case ARRAY:
throw new UnsupportedOperationException("Snowflake doesn't support array types");
case BIGINT:
return "NUMBER(38)";
case BOOLEAN:
return "BOOLEAN";
case CHAR:
if (!(type instanceof CharType)) {
throw new IllegalArgumentException("Expected CHAR type but was " + type.getClass().getName());
}
final CharType charType = (CharType) type;
return "CHAR(" + charType.getLength() + ")";
case DATE:
return "DATE";
case DECIMAL:
if (!(type instanceof DecimalType)) {
throw new IllegalArgumentException("Expected decimal type but was " + type.getClass().getName());
}
final DecimalType decimalType = (DecimalType) type;
return "DECIMAL(" + decimalType.getPrecision() + ", " + decimalType.getScale() + ")";
case DOUBLE:
case FLOAT:
return "DOUBLE PRECISION";
case INT:
return "INT";
case INTERVAL_DAY_TO_SECOND:
throw new UnsupportedOperationException("Snowflake doesn't support interval types");
case INTERVAL_YEAR_TO_MONTH:
throw new UnsupportedOperationException("Snowflake doesn't support interval types");
case JSON:
throw new UnsupportedOperationException("Snowflake doesn't support JSON types");
case MAP:
throw new UnsupportedOperationException("Snowflake doesn't support MAP types");
case ROW:
throw new UnsupportedOperationException("Snowflake doesn't support ROW types");
case SMALLINT:
return "SMALLINT";
case STRING:
return "STRING";
case TIME:
case TIME_WITH_TIME_ZONE:
return "TIME";
case TIMESTAMP:
return "TIMESTAMP";
case TIMESTAMP_WITH_TIME_ZONE:
return "TIMESTAMPTZ";
case TINYINT:
return "SMALLINT";
case UNKNOWN:
throw new IllegalArgumentException("Can't map an unknown type");
case VARBINARY:
return "VARBINARY";
case VARCHAR:
if (!(type instanceof VarcharType)) {
throw new IllegalArgumentException("Expected varchar type but was " + type.getClass().getName());
}
final VarcharType varcharType = (VarcharType) type;
return "VARCHAR(" + varcharType.getLength() + ")";
default:
throw new IllegalArgumentException("Unknown type " + type.getTypeSignature().getBase());
}
}
}
| 25 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeConnectorPlugin.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.netflix.metacat.common.server.connectors.ConnectorFactory;
import com.netflix.metacat.common.server.connectors.ConnectorPlugin;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import lombok.NonNull;
import javax.annotation.Nonnull;
/**
* Snowflake Connector Plugin.
*
* @author amajumdar
* @since 1.2.0
*/
public class SnowflakeConnectorPlugin implements ConnectorPlugin {
private static final String CONNECTOR_TYPE = "snowflake";
private static final SnowflakeTypeConverter TYPE_CONVERTER = new SnowflakeTypeConverter();
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return CONNECTOR_TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public ConnectorFactory create(@Nonnull @NonNull final ConnectorContext connectorContext) {
return new SnowflakeConnectorFactory(connectorContext.getCatalogName(),
connectorContext.getCatalogShardName(), connectorContext.getConfiguration());
}
/**
* {@inheritDoc}
*/
@Override
public ConnectorTypeConverter getTypeConverter() {
return TYPE_CONVERTER;
}
}
| 26 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeConnectorTableService.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.Pageable;
import com.netflix.metacat.common.dto.Sort;
import com.netflix.metacat.common.server.connectors.ConnectorRequestContext;
import com.netflix.metacat.common.server.connectors.model.AuditInfo;
import com.netflix.metacat.common.server.connectors.model.TableInfo;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Snowflake table service implementation.
*
* @author amajumdar
* @since 1.2.0
*/
@Slf4j
public class SnowflakeConnectorTableService extends JdbcConnectorTableService {
private static final String COL_CREATED = "CREATED";
private static final String COL_LAST_ALTERED = "LAST_ALTERED";
private static final String SQL_GET_AUDIT_INFO
= "select created, last_altered from information_schema.tables"
+ " where table_schema=? and table_name=?";
private static final String JDBC_UNDERSCORE = "_";
private static final String JDBC_ESCAPE_UNDERSCORE = "\\_";
/**
* Constructor.
*
* @param dataSource the datasource to use to connect to the database
* @param typeConverter The type converter to use from the SQL type to Metacat canonical type
* @param exceptionMapper The exception mapper to use
*/
@Inject
public SnowflakeConnectorTableService(
final DataSource dataSource,
final JdbcTypeConverter typeConverter,
final JdbcExceptionMapper exceptionMapper
) {
super(dataSource, typeConverter, exceptionMapper);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
super.delete(context, getSnowflakeName(name));
}
/**
* Returns the snowflake represented name which is always uppercase.
*
* @param name qualified name
* @return qualified name
*/
private QualifiedName getSnowflakeName(final QualifiedName name) {
return name.cloneWithUpperCase();
}
/**
* Returns a normalized string that escapes JDBC special characters like "_".
*
* @param input object name.
* @return the normalized string.
*/
private static String getJdbcNormalizedSnowflakeName(final String input) {
if (!StringUtils.isBlank(input) && input.contains(JDBC_UNDERSCORE)) {
return StringUtils.replace(input, JDBC_UNDERSCORE, JDBC_ESCAPE_UNDERSCORE);
}
return input;
}
/**
* {@inheritDoc}
*/
@Override
public TableInfo get(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
return super.get(context, getSnowflakeName(name));
}
/**
* {@inheritDoc}
*/
@Override
public List<TableInfo> list(@Nonnull final ConnectorRequestContext context,
@Nonnull final QualifiedName name,
@Nullable final QualifiedName prefix,
@Nullable final Sort sort,
@Nullable final Pageable pageable) {
return super.list(context, getSnowflakeName(name), prefix, sort, pageable);
}
/**
* {@inheritDoc}
*/
@Override
public List<QualifiedName> listNames(@Nonnull final ConnectorRequestContext context,
@Nonnull final QualifiedName name,
@Nullable final QualifiedName prefix,
@Nullable final Sort sort,
@Nullable final Pageable pageable) {
return super.listNames(context, name.cloneWithUpperCase(), prefix, sort, pageable);
}
/**
* {@inheritDoc}
*/
@Override
public void rename(@Nonnull final ConnectorRequestContext context,
@Nonnull final QualifiedName oldName,
@Nonnull final QualifiedName newName) {
super.rename(context, getSnowflakeName(oldName), getSnowflakeName(newName));
}
@Override
protected Connection getConnection(@Nonnull @NonNull final String schema) throws SQLException {
final Connection connection = this.dataSource.getConnection();
connection.setSchema(connection.getCatalog());
return connection;
}
/**
* {@inheritDoc}
*/
@Override
public boolean exists(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
boolean result = false;
final QualifiedName sName = getSnowflakeName(name);
try (Connection connection = this.dataSource.getConnection()) {
final ResultSet rs = getTables(connection, sName, sName, false);
if (rs.next()) {
result = true;
}
} catch (final SQLException se) {
throw this.exceptionMapper.toConnectorException(se, name);
}
return result;
}
@Override
protected ResultSet getColumns(
@Nonnull @NonNull final Connection connection,
@Nonnull @NonNull final QualifiedName name
) throws SQLException {
try {
return connection.getMetaData().getColumns(
connection.getCatalog(),
getJdbcNormalizedSnowflakeName(name.getDatabaseName()),
getJdbcNormalizedSnowflakeName(name.getTableName()),
JdbcConnectorUtils.MULTI_CHARACTER_SEARCH
);
} catch (SQLException e) {
throw this.exceptionMapper.toConnectorException(e, name);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void setTableInfoDetails(final Connection connection, final TableInfo tableInfo) {
final QualifiedName tableName = getSnowflakeName(tableInfo.getName());
try (
PreparedStatement statement = connection.prepareStatement(SQL_GET_AUDIT_INFO)
) {
statement.setString(1, tableName.getDatabaseName());
statement.setString(2, tableName.getTableName());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final AuditInfo auditInfo =
AuditInfo.builder().createdDate(resultSet.getDate(COL_CREATED))
.lastModifiedDate(resultSet.getDate(COL_LAST_ALTERED)).build();
tableInfo.setAudit(auditInfo);
}
}
} catch (final Exception ignored) {
log.info("Ignoring. Error getting the audit info for table {}", tableName);
}
}
/**
* {@inheritDoc}
*/
@Override
protected ResultSet getTables(
@Nonnull @NonNull final Connection connection,
@Nonnull @NonNull final QualifiedName name,
@Nullable final QualifiedName prefix
) throws SQLException {
return getTables(connection, name, prefix, true);
}
private ResultSet getTables(
@Nonnull @NonNull final Connection connection,
@Nonnull @NonNull final QualifiedName name,
@Nullable final QualifiedName prefix,
final boolean multiCharacterSearch
) throws SQLException {
final String schema = getJdbcNormalizedSnowflakeName(name.getDatabaseName());
final DatabaseMetaData metaData = connection.getMetaData();
return prefix == null || StringUtils.isEmpty(prefix.getTableName())
? metaData.getTables(connection.getCatalog(), schema, null, TABLE_TYPES)
: metaData
.getTables(
connection.getCatalog(),
schema,
multiCharacterSearch ? getJdbcNormalizedSnowflakeName(prefix.getTableName())
+ JdbcConnectorUtils.MULTI_CHARACTER_SEARCH
: getJdbcNormalizedSnowflakeName(prefix.getTableName()),
TABLE_TYPES
);
}
}
| 27 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/package-info.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes for the Snowflake Connector implementation.
*
* @author amajumdar
* @since 1.2.0
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.connector.snowflake;
import javax.annotation.ParametersAreNonnullByDefault;
| 28 |
0 | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-snowflake/src/main/java/com/netflix/metacat/connector/snowflake/SnowflakeConnectorFactory.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.snowflake;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.server.connectors.DefaultConnectorFactory;
import java.util.Map;
/**
* Connector Factory for Snowflake.
*
* @author amajumdar
* @since 1.2.0
*/
class SnowflakeConnectorFactory extends DefaultConnectorFactory {
/**
* Constructor.
*
* @param name catalog name
* @param catalogShardName catalog shard name
* @param configuration catalog configuration
*/
SnowflakeConnectorFactory(
final String name,
final String catalogShardName,
final Map<String, String> configuration
) {
super(name, catalogShardName,
Lists.newArrayList(new SnowflakeConnectorModule(catalogShardName, configuration)));
}
}
| 29 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/MySqlServiceUtil.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.metadata.mysql;
import com.google.common.collect.Sets;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.DataSourceManager;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.FileSystems;
import java.util.Properties;
import java.util.Set;
/**
* MySqlServiceUtil.
*
* @author zhenl
* @since 1.1.0
*/
public final class MySqlServiceUtil {
private MySqlServiceUtil() {
}
/**
* Returns the list of string having the input ids.
*
* @param jdbcTemplate jdbc template
* @param sql query sql
* @param item identifier
* @return list of results
*/
public static Set<String> getValues(final JdbcTemplate jdbcTemplate,
final String sql,
final Object item) {
try {
return jdbcTemplate.query(sql, rs -> {
final Set<String> result = Sets.newHashSet();
while (rs.next()) {
result.add(rs.getString("value"));
}
return result;
}, item);
} catch (EmptyResultDataAccessException e) {
return Sets.newHashSet();
}
}
/**
* load mysql data source.
*
* @param dataSourceManager data source manager to use
* @param configLocation usermetadata config location
* @throws Exception exception to throw
*/
public static void loadMySqlDataSource(final DataSourceManager dataSourceManager,
final String configLocation) throws Exception {
URL url = Thread.currentThread().getContextClassLoader().getResource(configLocation);
if (url == null) {
url = FileSystems.getDefault().getPath(configLocation).toUri().toURL();
}
final Properties connectionProperties = new Properties();
try (InputStream is = url.openStream()) {
connectionProperties.load(is);
} catch (Exception e) {
throw new Exception(String.format("Unable to read from user metadata config file %s", configLocation), e);
}
dataSourceManager.load(UserMetadataService.NAME_DATASOURCE, connectionProperties);
}
}
| 30 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/MySqlLookupService.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.metadata.mysql;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.netflix.metacat.common.server.model.Lookup;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.LookupService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataServiceException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.annotation.Transactional;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Set;
import java.util.stream.Collectors;
/**
* User metadata service impl using Mysql.
*/
@Slf4j
@SuppressFBWarnings
@Transactional("metadataTxManager")
public class MySqlLookupService implements LookupService {
private static final String SQL_GET_LOOKUP =
"select id, name, type, created_by createdBy, last_updated_by lastUpdatedBy, date_created dateCreated,"
+ " last_updated lastUpdated from lookup where name=?";
private static final String SQL_INSERT_LOOKUP =
"insert into lookup( name, version, type, created_by, last_updated_by, date_created, last_updated)"
+ " values (?,0,?,?,?,now(),now())";
private static final String SQL_INSERT_LOOKUP_VALUES =
"insert into lookup_values( lookup_id, values_string) values (?,?)";
private static final String SQL_DELETE_LOOKUP_VALUES =
"delete from lookup_values where lookup_id=? and values_string in (%s)";
private static final String SQL_GET_LOOKUP_VALUES =
"select values_string value from lookup_values where lookup_id=?";
private static final String SQL_GET_LOOKUP_VALUES_BY_NAME =
"select lv.values_string value from lookup l, lookup_values lv where l.id=lv.lookup_id and l.name=?";
private static final String STRING_TYPE = "string";
private final Config config;
private JdbcTemplate jdbcTemplate;
/**
* Constructor.
*
* @param config config
* @param jdbcTemplate jdbc template
*/
public MySqlLookupService(final Config config, final JdbcTemplate jdbcTemplate) {
this.config = config;
this.jdbcTemplate = jdbcTemplate;
}
/**
* Returns the lookup for the given <code>name</code>.
*
* @param name lookup name
* @return lookup
*/
@Override
@Transactional(readOnly = true)
public Lookup get(final String name) {
try {
return jdbcTemplate.queryForObject(
SQL_GET_LOOKUP,
new Object[]{name}, new int[]{Types.VARCHAR},
(rs, rowNum) -> {
final Lookup lookup = new Lookup();
lookup.setId(rs.getLong("id"));
lookup.setName(rs.getString("name"));
lookup.setType(rs.getString("type"));
lookup.setCreatedBy(rs.getString("createdBy"));
lookup.setLastUpdated(rs.getDate("lastUpdated"));
lookup.setLastUpdatedBy(rs.getString("lastUpdatedBy"));
lookup.setDateCreated(rs.getDate("dateCreated"));
lookup.setValues(getValues(rs.getLong("id")));
return lookup;
});
} catch (EmptyResultDataAccessException e) {
return null;
} catch (Exception e) {
final String message = String.format("Failed to get the lookup for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Returns the value of the lookup name.
*
* @param name lookup name
* @return scalar lookup value
*/
@Override
@Transactional(readOnly = true)
public String getValue(final String name) {
String result = null;
final Set<String> values = getValues(name);
if (values != null && values.size() > 0) {
result = values.iterator().next();
}
return result;
}
/**
* Returns the list of values of the lookup name.
*
* @param lookupId lookup id
* @return list of lookup values
*/
@Override
@Transactional(readOnly = true)
public Set<String> getValues(final Long lookupId) {
try {
return MySqlServiceUtil.getValues(jdbcTemplate, SQL_GET_LOOKUP_VALUES, lookupId);
} catch (EmptyResultDataAccessException e) {
return Sets.newHashSet();
} catch (Exception e) {
final String message = String.format("Failed to get the lookup values for id %s", lookupId);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Returns the list of values of the lookup name.
*
* @param name lookup name
* @return list of lookup values
*/
@Override
@Transactional(readOnly = true)
public Set<String> getValues(final String name) {
try {
return MySqlServiceUtil.getValues(jdbcTemplate, SQL_GET_LOOKUP_VALUES_BY_NAME, name);
} catch (EmptyResultDataAccessException e) {
return Sets.newHashSet();
} catch (Exception e) {
final String message = String.format("Failed to get the lookup values for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Saves the lookup value.
*
* @param name lookup name
* @param values multiple values
* @return returns the lookup with the given name.
*/
@Override
public Lookup setValues(final String name, final Set<String> values) {
try {
final Lookup lookup = findOrCreateLookupByName(name);
final Set<String> inserts;
Set<String> deletes = Sets.newHashSet();
final Set<String> lookupValues = lookup.getValues();
if (lookupValues == null || lookupValues.isEmpty()) {
inserts = values;
} else {
inserts = Sets.difference(values, lookupValues).immutableCopy();
deletes = Sets.difference(lookupValues, values).immutableCopy();
}
lookup.setValues(values);
if (!inserts.isEmpty()) {
insertLookupValues(lookup.getId(), inserts);
}
if (!deletes.isEmpty()) {
deleteLookupValues(lookup.getId(), deletes);
}
return lookup;
} catch (Exception e) {
final String message = String.format("Failed to set the lookup values for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
private void insertLookupValues(final Long id, final Set<String> inserts) {
jdbcTemplate.batchUpdate(SQL_INSERT_LOOKUP_VALUES, inserts.stream().map(insert -> new Object[]{id, insert})
.collect(Collectors.toList()), new int[]{Types.BIGINT, Types.VARCHAR});
}
private void deleteLookupValues(final Long id, final Set<String> deletes) {
jdbcTemplate.update(
String.format(SQL_DELETE_LOOKUP_VALUES, "'" + Joiner.on("','").skipNulls().join(deletes) + "'"),
new SqlParameterValue(Types.BIGINT, id));
}
/**
* findOrCreateLookupByName.
*
* @param name name to find or create
* @return Look up object
* @throws SQLException sql exception
*/
private Lookup findOrCreateLookupByName(final String name) throws SQLException {
Lookup lookup = get(name);
if (lookup == null) {
final KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_LOOKUP,
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setString(2, STRING_TYPE);
ps.setString(3, config.getLookupServiceUserAdmin());
ps.setString(4, config.getLookupServiceUserAdmin());
return ps;
}, holder);
final Long lookupId = holder.getKey().longValue();
lookup = new Lookup();
lookup.setName(name);
lookup.setId(lookupId);
}
return lookup;
}
/**
* Saves the lookup value.
*
* @param name lookup name
* @param values multiple values
* @return returns the lookup with the given name.
*/
@Override
public Lookup addValues(final String name, final Set<String> values) {
try {
final Lookup lookup = findOrCreateLookupByName(name);
final Set<String> inserts;
final Set<String> lookupValues = lookup.getValues();
if (lookupValues == null || lookupValues.isEmpty()) {
inserts = values;
lookup.setValues(values);
} else {
inserts = Sets.difference(values, lookupValues);
}
if (!inserts.isEmpty()) {
insertLookupValues(lookup.getId(), inserts);
}
return lookup;
} catch (Exception e) {
final String message = String.format("Failed to set the lookup values for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Saves the lookup value.
*
* @param name lookup name
* @param value lookup value
* @return returns the lookup with the given name.
*/
@Override
public Lookup setValue(final String name, final String value) {
return setValues(name, Sets.newHashSet(value));
}
}
| 31 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/MySqlTagService.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.metadata.mysql;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.exception.MetacatBadRequestException;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.server.model.Lookup;
import com.netflix.metacat.common.server.model.TagItem;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.LookupService;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataServiceException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Tag service implementation.
*
* @author amajumdar
* @author zhenl
*/
@Slf4j
@SuppressFBWarnings
@Transactional("metadataTxManager")
public class MySqlTagService implements TagService {
/**
* Lookup name for tag.
*/
private static final String LOOKUP_NAME_TAG = "tag";
private static final String NAME_TAGS = "tags";
private static final String QUERY_LIST =
"select distinct i.name from tag_item i, tag_item_tags t where i.id=t.tag_item_id"
+ " and (1=? or t.tags_string in (%s) ) and (1=? or i.name like ?) and (1=? or i.name rlike ?)";
private static final String QUERY_SEARCH =
"select distinct i.name from tag_item i, tag_item_tags t where i.id=t.tag_item_id"
+ " and (1=? or t.tags_string %s ) and (1=? or i.name like ?)";
private static final String SQL_GET_TAG_ITEM =
"select id, name, created_by createdBy, last_updated_by lastUpdatedBy, date_created dateCreated,"
+ " last_updated lastUpdated from tag_item where name=?";
private static final String SQL_INSERT_TAG_ITEM =
"insert into tag_item( name, version, created_by, last_updated_by, date_created, last_updated)"
+ " values (?,0,?,?,now(),now())";
private static final String SQL_UPDATE_TAG_ITEM =
"update tag_item set name=?, last_updated=now() where name=?";
private static final String SQL_INSERT_TAG_ITEM_TAGS =
"insert into tag_item_tags( tag_item_id, tags_string) values (?,?)";
private static final String SQL_DELETE_TAG_ITEM =
"delete from tag_item where name=?";
private static final String SQL_DELETE_TAG_ITEM_TAGS_BY_NAME =
"delete from tag_item_tags where tag_item_id=(select id from tag_item where name=?)";
private static final String SQL_DELETE_TAG_ITEM_TAGS_BY_NAME_TAGS =
"delete from tag_item_tags where tag_item_id=(select id from tag_item where name=?) and tags_string in (%s)";
private static final String SQL_DELETE_TAG_ITEM_TAGS =
"delete from tag_item_tags where tag_item_id=(?) and tags_string in (%s)";
private static final String SQL_GET_TAG_ITEM_TAGS =
"select tags_string value from tag_item_tags where tag_item_id=?";
private static final String EMPTY_CLAUSE = "''";
// private static final String SQL_GET_LOOKUP_VALUES_BY_NAME =
// "select lv.tags_string value from tag_item l, tag_item_tags lv where l.id=lv.tag_item_id and l.name=?";
private static final int MAX_TAGS_LIST_COUNT = 16;
private final Config config;
private final LookupService lookupService;
private final MetacatJson metacatJson;
private final UserMetadataService userMetadataService;
private JdbcTemplate jdbcTemplate;
/**
* Constructor.
*
* @param config config
* @param jdbcTemplate JDBC template
* @param lookupService lookup service
* @param metacatJson json util
* @param userMetadataService user metadata service
*/
public MySqlTagService(
final Config config,
final JdbcTemplate jdbcTemplate,
final LookupService lookupService,
final MetacatJson metacatJson,
final UserMetadataService userMetadataService
) {
this.config = Preconditions.checkNotNull(config, "config is required");
this.jdbcTemplate = jdbcTemplate;
this.lookupService = Preconditions.checkNotNull(lookupService, "lookupService is required");
this.metacatJson = Preconditions.checkNotNull(metacatJson, "metacatJson is required");
this.userMetadataService = Preconditions.checkNotNull(userMetadataService, "userMetadataService is required");
}
private Lookup addTags(final Set<String> tags) {
try {
return lookupService.addValues(LOOKUP_NAME_TAG, tags);
} catch (Exception e) {
final String message = String.format("Failed adding the tags %s", tags);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Get the tag item.
*
* @param name name
* @return tag item
*/
public TagItem get(final QualifiedName name) {
return get(name.toString());
}
/**
* Returns the TagItem for the given <code>name</code>.
*
* @param name tag name
* @return TagItem
*/
@Transactional(readOnly = true)
public TagItem get(final String name) {
try {
return jdbcTemplate.queryForObject(
SQL_GET_TAG_ITEM,
new Object[]{name}, new int[]{Types.VARCHAR},
(rs, rowNum) -> {
final TagItem tagItem = new TagItem();
tagItem.setId(rs.getLong("id"));
tagItem.setName(rs.getString("name"));
tagItem.setCreatedBy(rs.getString("createdBy"));
tagItem.setLastUpdated(rs.getDate("lastUpdated"));
tagItem.setLastUpdatedBy(rs.getString("lastUpdatedBy"));
tagItem.setDateCreated(rs.getDate("dateCreated"));
tagItem.setValues(getValues(rs.getLong("id")));
return tagItem;
});
} catch (EmptyResultDataAccessException e) {
return null;
} catch (Exception e) {
final String message = String.format("Failed to get the tag for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Returns the list of tags of the tag item id.
*
* @param tagItemId tag item id
* @return list of tags
*/
private Set<String> getValues(final Long tagItemId) {
try {
return MySqlServiceUtil.getValues(jdbcTemplate, SQL_GET_TAG_ITEM_TAGS, tagItemId);
} catch (EmptyResultDataAccessException e) {
return Sets.newHashSet();
} catch (Exception e) {
final String message = String.format("Failed to get the tags for id %s", tagItemId);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* findOrCreateTagItemByName.
*
* @param name name to find or create
* @return Tag Item
* @throws SQLException sql exception
*/
private TagItem findOrCreateTagItemByName(final String name) throws SQLException {
TagItem result = get(name);
if (result == null) {
final KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
final PreparedStatement ps = connection.prepareStatement(SQL_INSERT_TAG_ITEM,
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
ps.setString(2, config.getTagServiceUserAdmin());
ps.setString(3, config.getTagServiceUserAdmin());
return ps;
}, holder);
final Long id = holder.getKey().longValue();
result = new TagItem();
result.setName(name);
result.setId(id);
}
return result;
}
@Override
public void renameTableTags(final QualifiedName name, final String newTableName) {
try {
final QualifiedName newName = QualifiedName.ofTable(name.getCatalogName(), name.getDatabaseName(),
newTableName);
if (get(newName) != null) {
delete(newName, false /*don't delete existing definition metadata with the new name*/);
}
jdbcTemplate.update(SQL_UPDATE_TAG_ITEM, new String[]{newName.toString(), name.toString()},
new int[]{Types.VARCHAR, Types.VARCHAR});
} catch (Exception e) {
final String message = String.format("Failed to rename item name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void delete(final QualifiedName name, final boolean updateUserMetadata) {
try {
jdbcTemplate
.update(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME, new SqlParameterValue(Types.VARCHAR, name.toString()));
jdbcTemplate.update(SQL_DELETE_TAG_ITEM, new SqlParameterValue(Types.VARCHAR, name.toString()));
if (updateUserMetadata) {
// Set the tags in user metadata
final Map<String, Set<String>> data = Maps.newHashMap();
data.put(NAME_TAGS, Sets.newHashSet());
userMetadataService
.saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)),
true);
}
} catch (Exception e) {
final String message = String.format("Failed to delete all tags for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* remove.
*
* @param name qualifiedName
* @param tags tags
* @param updateUserMetadata flag to update user metadata
*/
public void remove(final QualifiedName name, final Set<String> tags, final boolean updateUserMetadata) {
try {
final TagItem tagItem = get(name);
if (tagItem == null || tagItem.getValues().isEmpty()) {
log.info(String.format("No tags or tagItems found for table %s", name));
return;
}
final List<SqlParameterValue> params = Lists.newArrayList();
params.add(new SqlParameterValue(Types.VARCHAR, name.toString()));
jdbcTemplate.update(String.format(SQL_DELETE_TAG_ITEM_TAGS_BY_NAME_TAGS,
buildParametrizedInClause(tags, params, params.size())),
params.toArray());
if (updateUserMetadata) {
tagItem.getValues().removeAll(tags);
final Map<String, Set<String>> data = Maps.newHashMap();
data.put(NAME_TAGS, tagItem.getValues());
userMetadataService
.saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)),
true);
}
} catch (Exception e) {
final String message = String.format("Failed to remove tags for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* Returns the list of tags.
*
* @return list of tag names
*/
@Override
@Transactional(readOnly = true)
public Set<String> getTags() {
return lookupService.getValues(LOOKUP_NAME_TAG);
}
/**
* Returns the list of <code>QualifiedName</code> of items that are tagged by the
* given <code>includeTags</code> and do not contain the given <code>excludeTags</code>.
*
* @param includeTags include items that contain tags
* @param excludeTags include items that do not contain tags
* @param sourceName catalog/source name
* @param databaseName database name
* @param tableName table name
* @param type metacat data category
* @return list of qualified names of the items
*/
@Override
@Transactional(readOnly = true)
public List<QualifiedName> list(
@Nullable final Set<String> includeTags,
@Nullable final Set<String> excludeTags,
@Nullable final String sourceName,
@Nullable final String databaseName,
@Nullable final String tableName,
@Nullable final QualifiedName.Type type
) {
Set<String> includedNames = Sets.newHashSet();
final Set<String> excludedNames = Sets.newHashSet();
final String wildCardName =
QualifiedName.qualifiedNameToWildCardQueryString(sourceName, databaseName, tableName);
final Set<String> localIncludes = includeTags != null ? includeTags : Sets.newHashSet();
validateRequestTagCount(localIncludes);
try {
includedNames.addAll(queryTaggedItems(wildCardName, type, localIncludes));
if (excludeTags != null && !excludeTags.isEmpty()) {
excludedNames.addAll(queryTaggedItems(wildCardName, type, excludeTags));
}
} catch (Exception e) {
final String message = String.format("Failed getting the list of qualified names for tags %s", includeTags);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
if (excludeTags != null && !excludeTags.isEmpty()) {
includedNames = Sets.difference(includedNames, excludedNames);
}
return includedNames.stream().map(s -> QualifiedName.fromString(s, false)).collect(Collectors.toList());
}
/**
* Returns the list of <code>QualifiedName</code> of items that have tags containing the given tag text.
*
* @param tag partial text of a tag
* @param sourceName source/catalog name
* @param databaseName database name
* @param tableName table name
* @return list of qualified names of the items
*/
@Override
@Transactional(readOnly = true)
public List<QualifiedName> search(
@Nullable final String tag,
@Nullable final String sourceName,
@Nullable final String databaseName,
@Nullable final String tableName
) {
final Set<String> result = Sets.newHashSet();
try {
final String wildCardName =
QualifiedName.qualifiedNameToWildCardQueryString(sourceName, databaseName, tableName);
//Includes
final String query = String.format(QUERY_SEARCH, "like ?");
final Object[] params = {tag == null ? 1 : 0, tag + "%", wildCardName == null ? 1 : 0, wildCardName};
result.addAll(jdbcTemplate.query(query, params,
new int[]{Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.VARCHAR},
(rs, rowNum) -> rs.getString("name")));
} catch (Exception e) {
final String message = String.format("Failed getting the list of qualified names for tag %s", tag);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
return result.stream().map(QualifiedName::fromString).collect(Collectors.toList());
}
/**
* Tags the given table with the given <code>tags</code>.
*
* @param name resource name
* @param tags list of tags
* @return return the complete list of tags associated with the table
*/
@Override
public Set<String> setTags(final QualifiedName name, final Set<String> tags,
final boolean updateUserMetadata) {
addTags(tags);
try {
final TagItem tagItem = findOrCreateTagItemByName(name.toString());
final Set<String> inserts;
Set<String> deletes = Sets.newHashSet();
Set<String> values = tagItem.getValues();
if (values == null || values.isEmpty()) {
inserts = tags;
} else {
inserts = Sets.difference(tags, values).immutableCopy();
deletes = Sets.difference(values, tags).immutableCopy();
}
values = tags;
if (!inserts.isEmpty()) {
insertTagItemTags(tagItem.getId(), inserts);
}
if (!deletes.isEmpty()) {
removeTagItemTags(tagItem.getId(), deletes);
}
if (updateUserMetadata) {
// Set the tags in user metadata
final Map<String, Set<String>> data = Maps.newHashMap();
data.put(NAME_TAGS, values);
userMetadataService
.saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)),
true);
}
} catch (Exception e) {
final String message = String.format("Failed to remove tags for name %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
return tags;
}
private void removeTagItemTags(final Long id, final Set<String> tags) {
final List<SqlParameterValue> params = Lists.newArrayList();
params.add(new SqlParameterValue(Types.BIGINT, id));
jdbcTemplate
.update(String.format(SQL_DELETE_TAG_ITEM_TAGS, buildParametrizedInClause(
tags,
params,
params.size()
)), params.toArray());
}
private void insertTagItemTags(final Long id, final Set<String> tags) {
jdbcTemplate.batchUpdate(SQL_INSERT_TAG_ITEM_TAGS, tags.stream().map(tag -> new Object[]{id, tag})
.collect(Collectors.toList()), new int[]{Types.BIGINT, Types.VARCHAR});
}
/**
* Removes the tags from the given resource.
*
* @param name qualified name
* @param deleteAll if true, will delete all tags associated with the given table
* @param tags list of tags to be removed for the given table
*/
@Override
public void removeTags(final QualifiedName name, final Boolean deleteAll,
final Set<String> tags, final boolean updateUserMetadata) {
if (deleteAll != null && deleteAll) {
delete(name, updateUserMetadata);
} else {
remove(name, tags, updateUserMetadata);
}
}
private List<String> queryTaggedItems(final String name,
final QualifiedName.Type type,
final Set<String> tags) {
final List<SqlParameterValue> sqlParams = Lists.newArrayList();
sqlParams.add(new SqlParameterValue(Types.INTEGER, tags.size() == 0 ? 1 : 0));
final String query = String.format(QUERY_LIST,
buildParametrizedInClause(tags, sqlParams, sqlParams.size()));
sqlParams.addAll(Stream.of(
new SqlParameterValue(Types.INTEGER, name == null ? 1 : 0),
new SqlParameterValue(Types.VARCHAR, name),
new SqlParameterValue(Types.INTEGER, type == null ? 1 : 0),
new SqlParameterValue(Types.VARCHAR, type == null ? ".*" : type.getRegexValue())
).collect(Collectors.toList()));
return jdbcTemplate.query(query,
sqlParams.toArray(),
(rs, rowNum) -> rs.getString("name"));
}
private static String buildParametrizedInClause(final Set<String> tags,
final List<SqlParameterValue> params,
final int index) {
final String tagList = tags.stream().filter(StringUtils::isNotBlank)
.map(v -> "?").collect(Collectors.joining(", "));
params.addAll(index, tags.stream().filter(StringUtils::isNotBlank)
.map(p -> new SqlParameterValue(Types.VARCHAR, p))
.collect(Collectors.toList()));
return StringUtils.isBlank(tagList) ? EMPTY_CLAUSE : tagList;
}
private static void validateRequestTagCount(final Set<String> tags) {
final int totalTags = tags.size();
if (totalTags > MAX_TAGS_LIST_COUNT) {
throw new MetacatBadRequestException(String.format("Too many tags in request. Count %s", totalTags));
}
}
}
| 32 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/MySqlUserMetadataConfig.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.metadata.mysql;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.properties.MetacatProperties;
import com.netflix.metacat.common.server.usermetadata.MetadataInterceptor;
import com.netflix.metacat.common.server.usermetadata.LookupService;
import com.netflix.metacat.common.server.usermetadata.MetadataInterceptorImpl;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.DataSourceManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* MySql UserMetadata Config.
*
* @author zhenl
* @since 1.1.0
*/
@Configuration
@ConditionalOnProperty(value = "metacat.mysqlmetadataservice.enabled", havingValue = "true")
public class MySqlUserMetadataConfig {
/**
* business Metadata Manager.
* @return business Metadata Manager
*/
@Bean
@ConditionalOnMissingBean(MetadataInterceptor.class)
public MetadataInterceptor businessMetadataManager(
) {
return new MetadataInterceptorImpl();
}
/**
* User Metadata service.
*
* @param jdbcTemplate JDBC template
* @param config System config to use
* @param metacatJson Json Utilities to use
* @param metadataInterceptor business metadata manager
* @return User metadata service based on MySql
*/
@Bean
public UserMetadataService userMetadataService(
@Qualifier("metadataJdbcTemplate") final JdbcTemplate jdbcTemplate,
final Config config,
final MetacatJson metacatJson,
final MetadataInterceptor metadataInterceptor
) {
return new MysqlUserMetadataService(jdbcTemplate, metacatJson, config, metadataInterceptor);
}
/**
* Lookup service.
*
* @param jdbcTemplate JDBC template
* @param config System configuration to use
* @return Lookup service backed by MySQL
*/
@Bean
public LookupService lookupService(
@Qualifier("metadataJdbcTemplate") final JdbcTemplate jdbcTemplate,
final Config config) {
return new MySqlLookupService(config, jdbcTemplate);
}
/**
* The tag service to use.
*
* @param jdbcTemplate JDBC template
* @param config System config to use
* @param metacatJson Json Utilities to use
* @param lookupService Look up service implementation to use
* @param userMetadataService User metadata service implementation to use
* @return The tag service implementation backed by MySQL
*/
@Bean
public TagService tagService(
@Qualifier("metadataJdbcTemplate") final JdbcTemplate jdbcTemplate,
final Config config,
final MetacatJson metacatJson,
final LookupService lookupService,
final UserMetadataService userMetadataService
) {
return new MySqlTagService(config, jdbcTemplate, lookupService, metacatJson, userMetadataService);
}
/**
* mySql DataSource.
*
* @param dataSourceManager data source manager
* @param metacatProperties metacat properties
* @return data source
* @throws Exception exception
*/
@Bean
public DataSource metadataDataSource(final DataSourceManager dataSourceManager,
final MetacatProperties metacatProperties) throws Exception {
MySqlServiceUtil.loadMySqlDataSource(dataSourceManager,
metacatProperties.getUsermetadata().getConfig().getLocation());
return dataSourceManager.get(UserMetadataService.NAME_DATASOURCE);
}
/**
* mySql metadata Transaction Manager.
*
* @param mySqlDataSource metadata data source
* @return metadata transaction manager
*/
@Bean
public DataSourceTransactionManager metadataTxManager(
@Qualifier("metadataDataSource") final DataSource mySqlDataSource) {
return new DataSourceTransactionManager(mySqlDataSource);
}
/**
* mySql metadata JDBC template.
*
* @param mySqlDataSource metadata data source
* @param config System config to use
* @return metadata JDBC template
*/
@Bean
public JdbcTemplate metadataJdbcTemplate(
@Qualifier("metadataDataSource") final DataSource mySqlDataSource,
final Config config) {
final JdbcTemplate result = new JdbcTemplate(mySqlDataSource);
result.setQueryTimeout(config.getMetadataQueryTimeout());
return result;
}
}
| 33 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/MysqlUserMetadataService.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.metadata.mysql;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.DefinitionMetadataDto;
import com.netflix.metacat.common.dto.HasDataMetadata;
import com.netflix.metacat.common.dto.HasDefinitionMetadata;
import com.netflix.metacat.common.dto.HasMetadata;
import com.netflix.metacat.common.exception.MetacatBadRequestException;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.json.MetacatJsonException;
import com.netflix.metacat.common.server.connectors.exception.InvalidMetadataException;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.BaseUserMetadataService;
import com.netflix.metacat.common.server.usermetadata.GetMetadataInterceptorParameters;
import com.netflix.metacat.common.server.usermetadata.MetadataInterceptor;
import com.netflix.metacat.common.server.usermetadata.UserMetadataServiceException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* User metadata service.
* <p>
* Definition metadata (business metadata about the logical schema definition) is stored in two tables. Definition
* metadata about the partitions are stored in 'partition_definition_metadata' table. Definition metadata about the
* catalogs, databases and tables are stored in 'definition_metadata' table.
* <p>
* Data metadata (metadata about the data stored in the location referred by the schema). This information is stored in
* 'data_metadata' table.
*/
@Slf4j
@SuppressFBWarnings
@Transactional("metadataTxManager")
public class MysqlUserMetadataService extends BaseUserMetadataService {
private static final String NAME_OWNER = "owner";
private static final String NAME_USERID = "userId";
private static final List<String> DEFINITION_METADATA_SORT_BY_COLUMNS = Arrays.asList(
"id", "date_created", "created_by", "last_updated_by", "name", "last_updated");
private static final List<String> VALID_SORT_ORDER = Arrays.asList("ASC", "DESC");
private final MetacatJson metacatJson;
private final Config config;
private JdbcTemplate jdbcTemplate;
private final MetadataInterceptor metadataInterceptor;
/**
* Constructor.
*
* @param jdbcTemplate jdbc template
* @param metacatJson json utility
* @param config config
* @param metadataInterceptor metadata interceptor
*/
public MysqlUserMetadataService(
final JdbcTemplate jdbcTemplate,
final MetacatJson metacatJson,
final Config config,
final MetadataInterceptor metadataInterceptor
) {
this.metacatJson = metacatJson;
this.config = config;
this.jdbcTemplate = jdbcTemplate;
this.metadataInterceptor = metadataInterceptor;
}
@Override
public void saveMetadata(final String userId, final HasMetadata holder, final boolean merge) {
super.saveMetadata(userId, holder, merge);
}
@Override
public void populateMetadata(final HasMetadata holder, final ObjectNode definitionMetadata,
final ObjectNode dataMetadata) {
super.populateMetadata(holder, definitionMetadata, dataMetadata);
}
@Nonnull
@Override
@Transactional(readOnly = true)
public Optional<ObjectNode> getDefinitionMetadataWithInterceptor(
@Nonnull final QualifiedName name,
final GetMetadataInterceptorParameters getMetadataInterceptorParameters) {
//not applying interceptor
final Optional<ObjectNode> retData = getDefinitionMetadata(name);
retData.ifPresent(objectNode ->
this.metadataInterceptor.onRead(this, name, objectNode, getMetadataInterceptorParameters));
return retData;
}
@Override
public void softDeleteDataMetadata(
final String user,
@Nonnull final List<String> uris
) {
try {
final List<List<String>> subLists = Lists.partition(uris, config.getUserMetadataMaxInClauseItems());
for (List<String> subUris : subLists) {
_softDeleteDataMetadata(user, subUris);
}
} catch (Exception e) {
final String message = String.format("Failed deleting the data metadata for %s", uris);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void deleteDataMetadata(
@Nonnull final List<String> uris
) {
deleteDataMetadatasWithBatch(uris, true);
}
@Override
public void deleteDataMetadataDeletes(
@Nonnull final List<String> uris
) {
deleteDataMetadatasWithBatch(uris, false);
}
private void deleteDataMetadatasWithBatch(final List<String> uris, final boolean removeDataMetadata) {
try {
final List<List<String>> subLists = Lists.partition(uris, config.getUserMetadataMaxInClauseItems());
for (List<String> subUris : subLists) {
_deleteDataMetadata(subUris, removeDataMetadata);
}
} catch (Exception e) {
final String message = String.format("Failed deleting the data metadata for %s", uris);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void deleteDefinitionMetadata(
@Nonnull final List<QualifiedName> names
) {
try {
final List<List<QualifiedName>> subLists =
Lists.partition(names, config.getUserMetadataMaxInClauseItems());
for (List<QualifiedName> subNames : subLists) {
_deleteDefinitionMetadata(subNames);
}
} catch (Exception e) {
final String message = String.format("Failed deleting the definition metadata for %s", names);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void deleteStaleDefinitionMetadata(
@NonNull final String qualifiedNamePattern,
@NonNull final Date lastUpdated) {
if (qualifiedNamePattern == null || lastUpdated == null) {
return;
}
try {
jdbcTemplate.update(SQL.DELETE_DEFINITION_METADATA_STALE, new Object[]{qualifiedNamePattern, lastUpdated},
new int[]{Types.VARCHAR, Types.TIMESTAMP});
} catch (Exception e) {
final String message = String.format("Failed to delete stale definition metadata for pattern %s",
qualifiedNamePattern);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void deleteMetadata(final String userId, final List<HasMetadata> holders) {
try {
final List<List<HasMetadata>> subLists =
Lists.partition(holders, config.getUserMetadataMaxInClauseItems());
for (List<HasMetadata> hasMetadatas : subLists) {
final List<QualifiedName> names = hasMetadatas.stream()
.filter(m -> m instanceof HasDefinitionMetadata)
.map(m -> ((HasDefinitionMetadata) m).getDefinitionName())
.collect(Collectors.toList());
if (!names.isEmpty()) {
_deleteDefinitionMetadata(names);
}
if (config.canSoftDeleteDataMetadata()) {
final List<String> uris = hasMetadatas.stream()
.filter(m -> m instanceof HasDataMetadata && ((HasDataMetadata) m).isDataExternal())
.map(m -> ((HasDataMetadata) m).getDataUri()).collect(Collectors.toList());
if (!uris.isEmpty()) {
_softDeleteDataMetadata(userId, uris);
}
}
}
} catch (Exception e) {
log.error("Failed deleting metadatas", e);
throw new UserMetadataServiceException("Failed deleting metadatas", e);
}
}
/**
* delete Definition Metadatas.
*
* @param names names to delete
*/
@SuppressWarnings("checkstyle:methodname")
private void _deleteDefinitionMetadata(
@Nullable final List<QualifiedName> names
) {
if (names != null && !names.isEmpty()) {
final SqlParameterValue[] aNames = names.stream().filter(name -> !name.isPartitionDefinition())
.map(n -> new SqlParameterValue(Types.VARCHAR, n))
.toArray(SqlParameterValue[]::new);
final SqlParameterValue[] aPartitionNames = names.stream().filter(QualifiedName::isPartitionDefinition)
.map(n -> new SqlParameterValue(Types.VARCHAR, n))
.toArray(SqlParameterValue[]::new);
if (aNames.length > 0) {
final List<String> paramVariables = Arrays.stream(aNames).map(s -> "?").collect(Collectors.toList());
jdbcTemplate.update(
String.format(SQL.DELETE_DEFINITION_METADATA, Joiner.on(",").skipNulls().join(paramVariables)),
(Object[]) aNames);
}
if (aPartitionNames.length > 0) {
final List<String> paramVariables =
Arrays.stream(aPartitionNames).map(s -> "?").collect(Collectors.toList());
jdbcTemplate.update(
String.format(SQL.DELETE_PARTITION_DEFINITION_METADATA,
Joiner.on(",").skipNulls().join(paramVariables)), (Object[]) aPartitionNames);
}
}
}
/**
* soft Delete Data Metadatas.
*
* @param userId user id
* @param uris uri list
*/
@SuppressWarnings("checkstyle:methodname")
private void _softDeleteDataMetadata(final String userId,
@Nullable final List<String> uris) {
if (uris != null && !uris.isEmpty()) {
final List<String> paramVariables = uris.stream().map(s -> "?").collect(Collectors.toList());
final String[] aUris = uris.toArray(new String[0]);
final String paramString = Joiner.on(",").skipNulls().join(paramVariables);
final List<Long> ids = jdbcTemplate
.query(String.format(SQL.GET_DATA_METADATA_IDS, paramString), aUris, (rs, rowNum) -> rs.getLong("id"));
if (!ids.isEmpty()) {
final List<String> idParamVariables = ids.stream().map(s -> "?").collect(Collectors.toList());
final Long[] aIds = ids.toArray(new Long[0]);
final String idParamString = Joiner.on(",").skipNulls().join(idParamVariables);
final List<Long> dupIds = jdbcTemplate
.query(String.format(SQL.GET_DATA_METADATA_DELETE_BY_IDS, idParamString), aIds,
(rs, rowNum) -> rs.getLong("id"));
if (!dupIds.isEmpty()) {
ids.removeAll(dupIds);
}
final List<Object[]> deleteDataMetadatas = Lists.newArrayList();
ids.forEach(id -> deleteDataMetadatas.add(new Object[]{id, userId}));
final int[] colTypes = {Types.BIGINT, Types.VARCHAR};
jdbcTemplate.batchUpdate(SQL.SOFT_DELETE_DATA_METADATA, deleteDataMetadatas, colTypes);
}
}
}
/**
* delete Data Metadatas.
*
* @param uris uri list
* @param removeDataMetadata flag to remove data meta data
*/
@SuppressWarnings("checkstyle:methodname")
private void _deleteDataMetadata(
@Nullable final List<String> uris,
final boolean removeDataMetadata
) {
if (uris != null && !uris.isEmpty()) {
final List<String> paramVariables = uris.stream().map(s -> "?").collect(Collectors.toList());
final String[] aUris = uris.toArray(new String[0]);
final String paramString = Joiner.on(",").skipNulls().join(paramVariables);
final List<Long> ids = jdbcTemplate
.query(String.format(SQL.GET_DATA_METADATA_IDS, paramString), aUris, (rs, rowNum) -> rs.getLong("id"));
if (!ids.isEmpty()) {
final List<String> idParamVariables = ids.stream().map(s -> "?").collect(Collectors.toList());
final SqlParameterValue[] aIds = ids.stream().map(id -> new SqlParameterValue(Types.BIGINT, id))
.toArray(SqlParameterValue[]::new);
final String idParamString = Joiner.on(",").skipNulls().join(idParamVariables);
jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA_DELETE, idParamString), (Object[]) aIds);
if (removeDataMetadata) {
jdbcTemplate.update(String.format(SQL.DELETE_DATA_METADATA, idParamString), (Object[]) aIds);
}
}
}
}
@Nonnull
@Override
@Transactional(readOnly = true)
public Optional<ObjectNode> getDataMetadata(
@Nonnull final String uri) {
return getJsonForKey(SQL.GET_DATA_METADATA, uri);
}
@Nonnull
@Override
@Transactional(readOnly = true)
public Map<String, ObjectNode> getDataMetadataMap(
@Nonnull final List<String> uris) {
final Map<String, ObjectNode> result = Maps.newHashMap();
if (!uris.isEmpty()) {
final List<List<String>> parts = Lists.partition(uris, config.getUserMetadataMaxInClauseItems());
parts.forEach(keys -> result.putAll(_getMetadataMap(keys, SQL.GET_DATA_METADATAS)));
}
return result;
}
@Nonnull
@Override
@Transactional(readOnly = true)
public Optional<ObjectNode> getDefinitionMetadata(
@Nonnull final QualifiedName name) {
final Optional<ObjectNode> retData = getJsonForKey(
name.isPartitionDefinition() ? SQL.GET_PARTITION_DEFINITION_METADATA : SQL.GET_DEFINITION_METADATA,
name.toString());
return retData;
}
@Override
@Transactional(readOnly = true)
public List<QualifiedName> getDescendantDefinitionNames(@Nonnull final QualifiedName name) {
final List<String> result;
try {
result = jdbcTemplate
.query(SQL.GET_DESCENDANT_DEFINITION_NAMES, new Object[]{name.toString() + "/%"},
new int[]{Types.VARCHAR},
(rs, rowNum) -> rs.getString("name"));
} catch (Exception e) {
final String message = String.format("Failed to get descendant names for %s", name);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
return result.stream().map(QualifiedName::fromString).collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public List<String> getDescendantDataUris(@Nonnull final String uri) {
final List<String> result;
try {
result = jdbcTemplate.query(SQL.GET_DESCENDANT_DATA_URIS, new Object[]{uri + "/%"},
new int[]{Types.VARCHAR},
(rs, rowNum) -> rs.getString("uri"));
} catch (Exception e) {
final String message = String.format("Failed to get descendant uris for %s", uri);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
return result;
}
//TODO: For partition metadata, add interceptor if needed
@Nonnull
@Override
@Transactional(readOnly = true)
public Map<String, ObjectNode> getDefinitionMetadataMap(
@Nonnull final List<QualifiedName> names) {
//
// names can contain partition names and non-partition names. Since definition metadata is stored in two tables,
// metadata needs to be retrieved from both the tables.
//
final List<QualifiedName> oNames = names.stream().filter(name -> !name.isPartitionDefinition()).collect(
Collectors.toList());
final List<QualifiedName> partitionNames = names.stream().filter(QualifiedName::isPartitionDefinition).collect(
Collectors.toList());
final Map<String, ObjectNode> result = Maps.newHashMap();
if (!oNames.isEmpty()) {
result.putAll(_getNonPartitionDefinitionMetadataMap(oNames));
}
if (!partitionNames.isEmpty()) {
result.putAll(_getPartitionDefinitionMetadata(partitionNames));
}
return result;
}
@SuppressWarnings("checkstyle:methodname")
private Map<String, ObjectNode> _getNonPartitionDefinitionMetadataMap(final List<QualifiedName> names) {
final List<List<QualifiedName>> parts = Lists.partition(names, config.getUserMetadataMaxInClauseItems());
return parts.parallelStream()
.map(keys -> _getMetadataMap(keys, SQL.GET_DEFINITION_METADATAS))
.flatMap(it -> it.entrySet().stream())
.collect(Collectors.toConcurrentMap(it -> QualifiedName.fromString(it.getKey()).toString(),
Map.Entry::getValue));
}
@SuppressWarnings("checkstyle:methodname")
private Map<String, ObjectNode> _getPartitionDefinitionMetadata(final List<QualifiedName> names) {
final List<List<QualifiedName>> parts = Lists.partition(names, config.getUserMetadataMaxInClauseItems());
return parts.parallelStream()
.map(keys -> _getMetadataMap(keys, SQL.GET_PARTITION_DEFINITION_METADATAS))
.flatMap(it -> it.entrySet().stream())
.collect(Collectors.toConcurrentMap(it -> QualifiedName.fromString(it.getKey()).toString(),
Map.Entry::getValue));
}
/**
* get Metadata Map.
*
* @param keys list of keys
* @param sql query string
* @return map of the metadata
*/
@SuppressWarnings("checkstyle:methodname")
private Map<String, ObjectNode> _getMetadataMap(@Nullable final List<?> keys, final String sql) {
final Map<String, ObjectNode> result = Maps.newHashMap();
if (keys == null || keys.isEmpty()) {
return result;
}
final List<String> paramVariables = keys.stream().map(s -> "?").collect(Collectors.toList());
final SqlParameterValue[] aKeys = keys.stream().map(o -> new SqlParameterValue(Types.VARCHAR, o.toString()))
.toArray(SqlParameterValue[]::new);
final String query = String.format(sql, Joiner.on(","
+ "").join(paramVariables));
try {
final ResultSetExtractor<Void> handler = resultSet -> {
while (resultSet.next()) {
final String json = resultSet.getString("data");
final String name = resultSet.getString("name");
if (json != null) {
try {
result.put(name, metacatJson.parseJsonObject(json));
} catch (MetacatJsonException e) {
log.error("Invalid json '{}' for name '{}'", json, name);
throw new UserMetadataServiceException(
String.format("Invalid json %s for name %s", json, name), e);
}
}
}
return null;
};
jdbcTemplate.query(query, aKeys, handler);
} catch (Exception e) {
final String message = String.format("Failed to get data for %s", keys);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
return result;
}
/**
* get Json for key.
*
* @param query query string
* @param keyValue parameters
* @return result object node
*/
private Optional<ObjectNode> getJsonForKey(final String query, final String keyValue) {
try {
ResultSetExtractor<Optional<ObjectNode>> handler = rs -> {
final String json;
Optional<ObjectNode> result = Optional.empty();
while (rs.next()) {
final String key = rs.getString(1);
if (keyValue.equalsIgnoreCase(key)) {
json = rs.getString(2);
if (Strings.isNullOrEmpty(json)) {
return Optional.empty();
}
result = Optional.ofNullable(metacatJson.parseJsonObject(json));
break;
}
}
return result;
};
return jdbcTemplate.query(query, new String[]{keyValue}, new int[]{Types.VARCHAR}, handler);
} catch (MetacatJsonException e) {
final String message = String.format("Invalid json %s for name %s", e.getInputJson(), keyValue);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
} catch (Exception e) {
final String message = String.format("Failed to get data for %s", keyValue);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
/**
* executeUpdateForKey.
*
* @param query sql query string
* @param keyValues parameters
* @return number of updated rows
*/
private int executeUpdateForKey(final String query, final String... keyValues) {
try {
final SqlParameterValue[] values =
Arrays.stream(keyValues).map(keyValue -> new SqlParameterValue(Types.VARCHAR, keyValue))
.toArray(SqlParameterValue[]::new);
return jdbcTemplate.update(query, (Object[]) values);
} catch (Exception e) {
final String message = String.format("Failed to save data for %s", Arrays.toString(keyValues));
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
private void throwIfPartitionDefinitionMetadataDisabled() {
if (config.disablePartitionDefinitionMetadata()) {
throw new MetacatBadRequestException("Partition Definition metadata updates are disabled");
}
}
@Override
public void saveDataMetadata(
@Nonnull final String uri,
@Nonnull final String userId,
@Nonnull final Optional<ObjectNode> metadata, final boolean merge) {
final Optional<ObjectNode> existingData = getDataMetadata(uri);
final int count;
if (existingData.isPresent() && metadata.isPresent()) {
final ObjectNode merged = existingData.get();
if (merge) {
metacatJson.mergeIntoPrimary(merged, metadata.get());
}
count = executeUpdateForKey(SQL.UPDATE_DATA_METADATA, merged.toString(), userId, uri);
} else {
count = metadata.map(
jsonNodes -> executeUpdateForKey(SQL.INSERT_DATA_METADATA, jsonNodes.toString(), userId, userId, uri))
.orElse(1);
}
if (count != 1) {
throw new IllegalStateException("Expected one row to be insert or update for " + uri);
}
}
@Override
public void saveDefinitionMetadata(
@Nonnull final QualifiedName name,
@Nonnull final String userId,
@Nonnull final Optional<ObjectNode> metadata, final boolean merge)
throws InvalidMetadataException {
final Optional<ObjectNode> existingData = getDefinitionMetadata(name);
final int count;
if (existingData.isPresent() && metadata.isPresent()) {
ObjectNode merged = existingData.get();
if (merge) {
metacatJson.mergeIntoPrimary(merged, metadata.get());
} else {
merged = metadata.get();
}
//apply interceptor to change the object node
this.metadataInterceptor.onWrite(this, name, merged);
String query;
if (name.isPartitionDefinition()) {
throwIfPartitionDefinitionMetadataDisabled();
query = SQL.UPDATE_PARTITION_DEFINITION_METADATA;
} else {
query = SQL.UPDATE_DEFINITION_METADATA;
}
count = executeUpdateForKey(
query,
merged.toString(),
userId,
name.toString());
} else {
//apply interceptor to change the object node
if (metadata.isPresent()) {
this.metadataInterceptor.onWrite(this, name, metadata.get());
}
String queryToExecute;
if (name.isPartitionDefinition()) {
throwIfPartitionDefinitionMetadataDisabled();
queryToExecute = SQL.INSERT_PARTITION_DEFINITION_METADATA;
} else {
queryToExecute = SQL.INSERT_DEFINITION_METADATA;
}
count = metadata.map(jsonNodes -> executeUpdateForKey(
queryToExecute,
jsonNodes.toString(),
userId,
userId,
name.toString()
)).orElse(1);
}
if (count != 1) {
throw new IllegalStateException("Expected one row to be insert or update for " + name);
}
}
@Override
public int renameDataMetadataKey(
@Nonnull final String oldUri,
@Nonnull final String newUri) {
return executeUpdateForKey(SQL.RENAME_DATA_METADATA, newUri, oldUri);
}
@Override
public int renameDefinitionMetadataKey(
@Nonnull final QualifiedName oldName,
@Nonnull final QualifiedName newName) {
_deleteDefinitionMetadata(Lists.newArrayList(newName));
return executeUpdateForKey(SQL.RENAME_DEFINITION_METADATA, newName.toString(), oldName.toString());
}
@Override
public void saveMetadata(final String user, final List<? extends HasMetadata> metadatas, final boolean merge) {
try {
@SuppressWarnings("unchecked") final List<List<HasMetadata>> subLists = Lists.partition(
(List<HasMetadata>) metadatas,
config.getUserMetadataMaxInClauseItems()
);
for (List<HasMetadata> hasMetadatas : subLists) {
final List<String> uris = Lists.newArrayList();
final List<QualifiedName> names = Lists.newArrayList();
// Get the names and uris
final List<HasDefinitionMetadata> definitionMetadatas = Lists.newArrayList();
final List<HasDataMetadata> dataMetadatas = Lists.newArrayList();
hasMetadatas.forEach(hasMetadata -> {
if (hasMetadata instanceof HasDefinitionMetadata) {
final HasDefinitionMetadata oDef = (HasDefinitionMetadata) hasMetadata;
names.add(oDef.getDefinitionName());
if (oDef.getDefinitionMetadata() != null) {
definitionMetadatas.add(oDef);
}
}
if (hasMetadata instanceof HasDataMetadata) {
final HasDataMetadata oData = (HasDataMetadata) hasMetadata;
if (oData.isDataExternal() && oData.getDataMetadata() != null
&& oData.getDataMetadata().size() > 0) {
uris.add(oData.getDataUri());
dataMetadatas.add(oData);
}
}
});
if (!definitionMetadatas.isEmpty() || !dataMetadatas.isEmpty()) {
// Get the existing metadata based on the names and uris
final Map<String, ObjectNode> definitionMap = getDefinitionMetadataMap(names);
final Map<String, ObjectNode> dataMap = getDataMetadataMap(uris);
// Curate the list of existing and new metadatas
final List<Object[]> insertDefinitionMetadatas = Lists.newArrayList();
final List<Object[]> updateDefinitionMetadatas = Lists.newArrayList();
final List<Object[]> insertPartitionDefinitionMetadatas = Lists.newArrayList();
final List<Object[]> updatePartitionDefinitionMetadatas = Lists.newArrayList();
final List<Object[]> insertDataMetadatas = Lists.newArrayList();
final List<Object[]> updateDataMetadatas = Lists.newArrayList();
definitionMetadatas.forEach(oDef -> {
final QualifiedName qualifiedName = oDef.getDefinitionName();
if (qualifiedName != null && oDef.getDefinitionMetadata() != null
&& oDef.getDefinitionMetadata().size() != 0) {
final String name = qualifiedName.toString();
final ObjectNode oNode = definitionMap.get(name);
if (oNode == null) {
final Object[] o = new Object[]{
metacatJson.toJsonString(oDef.getDefinitionMetadata()), user, user, name, };
if (qualifiedName.isPartitionDefinition()) {
insertPartitionDefinitionMetadatas.add(o);
} else {
insertDefinitionMetadatas.add(o);
}
} else {
metacatJson.mergeIntoPrimary(oNode, oDef.getDefinitionMetadata());
final Object[] o = new Object[]{metacatJson.toJsonString(oNode), user, name};
if (qualifiedName.isPartitionDefinition()) {
updatePartitionDefinitionMetadatas.add(o);
} else {
updateDefinitionMetadatas.add(o);
}
}
}
});
dataMetadatas.forEach(oData -> {
final String uri = oData.getDataUri();
final ObjectNode oNode = dataMap.get(uri);
if (oData.getDataMetadata() != null && oData.getDataMetadata().size() != 0) {
if (oNode == null) {
insertDataMetadatas.add(
new Object[]{
metacatJson.toJsonString(oData.getDataMetadata()),
user,
user,
uri,
}
);
} else {
metacatJson.mergeIntoPrimary(oNode, oData.getDataMetadata());
updateDataMetadatas
.add(new Object[]{metacatJson.toJsonString(oNode), user, uri});
}
}
});
if (!insertDefinitionMetadatas.isEmpty()) {
jdbcTemplate.batchUpdate(SQL.INSERT_DEFINITION_METADATA, insertDefinitionMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
if (!updateDefinitionMetadatas.isEmpty()) {
jdbcTemplate.batchUpdate(SQL.UPDATE_DEFINITION_METADATA, updateDefinitionMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
if (!insertPartitionDefinitionMetadatas.isEmpty()) {
throwIfPartitionDefinitionMetadataDisabled();
jdbcTemplate.batchUpdate(SQL.INSERT_PARTITION_DEFINITION_METADATA,
insertPartitionDefinitionMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
if (!updatePartitionDefinitionMetadatas.isEmpty()) {
throwIfPartitionDefinitionMetadataDisabled();
jdbcTemplate.batchUpdate(SQL.UPDATE_PARTITION_DEFINITION_METADATA,
updatePartitionDefinitionMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
if (!insertDataMetadatas.isEmpty()) {
jdbcTemplate.batchUpdate(SQL.INSERT_DATA_METADATA, insertDataMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
if (!updateDataMetadatas.isEmpty()) {
jdbcTemplate.batchUpdate(SQL.UPDATE_DATA_METADATA, updateDataMetadatas,
new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR});
}
}
}
} catch (Exception e) {
log.error("Failed to save metadata", e);
throw new UserMetadataServiceException("Failed to save metadata", e);
}
}
@Override
@Transactional(readOnly = true)
public List<DefinitionMetadataDto> searchDefinitionMetadata(
@Nullable final Set<String> propertyNames,
@Nullable final String type,
@Nullable final String name,
@Nullable final HasMetadata holder,
@Nullable final String sortBy,
@Nullable final String sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit
) {
final List<DefinitionMetadataDto> result = Lists.newArrayList();
final SearchMetadataQuery queryObj = new SearchMetadataQuery(SQL.SEARCH_DEFINITION_METADATAS)
.buildSearchMetadataQuery(
propertyNames,
type,
name,
sortBy,
sortOrder,
offset,
limit
);
try {
// Handler for reading the result set
final ResultSetExtractor<Void> handler = rs -> {
while (rs.next()) {
final String definitionName = rs.getString("name");
final String data = rs.getString("data");
final DefinitionMetadataDto definitionMetadataDto = new DefinitionMetadataDto();
definitionMetadataDto.setName(QualifiedName.fromString(definitionName));
definitionMetadataDto.setDefinitionMetadata(metacatJson.parseJsonObject(data));
result.add(definitionMetadataDto);
}
return null;
};
jdbcTemplate.query(queryObj.getSearchQuery().toString(), queryObj.getSearchParamList().toArray(), handler);
} catch (Exception e) {
log.error("Failed to search definition data", e);
throw new UserMetadataServiceException("Failed to search definition data", e);
}
return result;
}
@Override
@Transactional(readOnly = true)
public List<QualifiedName> searchByOwners(final Set<String> owners) {
final List<QualifiedName> result = Lists.newArrayList();
final StringBuilder query = new StringBuilder(SQL.SEARCH_DEFINITION_METADATA_NAMES);
final List<SqlParameterValue> paramList = Lists.newArrayList();
query.append(" where 1=0");
owners.forEach(s -> {
query.append(" or data like ?");
paramList.add(new SqlParameterValue(Types.VARCHAR, "%\"userId\":\"" + s.trim() + "\"%"));
});
final SqlParameterValue[] params = new SqlParameterValue[paramList.size()];
try {
// Handler for reading the result set
final ResultSetExtractor<Void> handler = rs -> {
while (rs.next()) {
final String definitionName = rs.getString("name");
result.add(QualifiedName.fromString(definitionName, false));
}
return null;
};
jdbcTemplate.query(query.toString(), paramList.toArray(params), handler);
} catch (Exception e) {
log.error("Failed to search by owners", e);
throw new UserMetadataServiceException("Failed to search by owners", e);
}
return result;
}
@Override
@Transactional(readOnly = true)
public List<String> getDeletedDataMetadataUris(final Date deletedPriorTo, final Integer offset,
final Integer limit) {
try {
return jdbcTemplate.query(String.format(SQL.GET_DELETED_DATA_METADATA_URI, offset, limit),
new Object[]{deletedPriorTo}, new int[]{Types.TIMESTAMP}, (rs, rowNum) -> rs.getString("uri"));
} catch (Exception e) {
final String message =
String.format("Failed to get deleted data metadata uris deleted prior to %s", deletedPriorTo);
log.error(message, e);
throw new UserMetadataServiceException(message, e);
}
}
@Override
public void populateOwnerIfMissing(final HasDefinitionMetadata holder, final String owner) {
ObjectNode definitionMetadata = holder.getDefinitionMetadata();
if (definitionMetadata == null) {
definitionMetadata = metacatJson.emptyObjectNode();
holder.setDefinitionMetadata(definitionMetadata);
}
final ObjectNode ownerNode = definitionMetadata.with(NAME_OWNER);
final JsonNode userId = ownerNode.get(NAME_USERID);
if (userId == null || Strings.isNullOrEmpty(userId.textValue())) {
ownerNode.put(NAME_USERID, owner);
}
}
/**
* Inner help class for generating the search definition/business metadata.
*/
@Data
class SearchMetadataQuery {
private StringBuilder searchQuery;
private List<SqlParameterValue> searchParamList = Lists.newArrayList();
SearchMetadataQuery(final String querySQL) {
this.searchQuery = new StringBuilder(querySQL);
}
SearchMetadataQuery buildSearchMetadataQuery(@Nullable final Set<String> propertyNames,
@Nullable final String type,
@Nullable final String name,
@Nullable final String sortByStr,
@Nullable final String sortOrderStr,
@Nullable final Integer offset,
@Nullable final Integer limit) {
String sortBy = null;
if (StringUtils.isNotBlank(sortByStr)) {
sortBy = sortByStr.trim().toLowerCase();
if (!DEFINITION_METADATA_SORT_BY_COLUMNS.contains(sortBy)) {
throw new IllegalArgumentException(String.format("Invalid sortBy column %s", sortBy));
}
}
String sortOrder = null;
if (StringUtils.isNotBlank(sortOrderStr)) {
sortOrder = sortOrderStr.trim().toUpperCase();
if (!VALID_SORT_ORDER.contains(sortOrder)) {
throw new IllegalArgumentException("Invalid sort order. Expected ASC or DESC");
}
}
if (type != null) {
String typeRegex = null;
switch (type) {
case "catalog":
typeRegex = "^[^/]*$";
break;
case "database":
typeRegex = "^[^/]*/[^/]*$";
break;
case "table":
typeRegex = "^[^/]*/[^/]*/[^/]*$";
break;
case "partition":
typeRegex = "^[^/]*/[^/]*/[^/]*/.*$";
break;
default:
}
if (typeRegex != null) {
this.searchQuery.append(" and name rlike ?");
this.searchParamList.add(new SqlParameterValue(Types.VARCHAR, typeRegex));
}
}
if (propertyNames != null && !propertyNames.isEmpty()) {
propertyNames.forEach(propertyName -> {
this.searchQuery.append(" and data like ?");
searchParamList.add(new SqlParameterValue(Types.VARCHAR, "%\"" + propertyName + "\":%"));
});
}
if (!Strings.isNullOrEmpty(name)) {
this.searchQuery.append(" and name like ?");
this.searchParamList.add(new SqlParameterValue(Types.VARCHAR, name));
}
if (!Strings.isNullOrEmpty(sortBy)) {
this.searchQuery.append(" order by ").append(sortBy);
if (!Strings.isNullOrEmpty(sortOrder)) {
this.searchQuery.append(" ").append(sortOrder);
}
}
if (limit != null) {
this.searchQuery.append(" limit ");
if (offset != null) {
this.searchQuery.append(offset).append(",");
}
this.searchQuery.append(limit);
}
return this;
}
}
protected static class SQL {
static final String SOFT_DELETE_DATA_METADATA =
"insert into data_metadata_delete(id, created_by,date_created) values (?,?, now())";
static final String GET_DATA_METADATA_IDS =
"select id from data_metadata where uri in (%s)";
static final String GET_DATA_METADATA_DELETE_BY_IDS =
"select id from data_metadata_delete where id in (%s)";
static final String DELETE_DATA_METADATA_DELETE =
"delete from data_metadata_delete where id in (%s)";
static final String DELETE_DATA_METADATA =
"delete from data_metadata where id in (%s)";
static final String DELETE_DEFINITION_METADATA =
"delete from definition_metadata where name in (%s)";
static final String DELETE_DEFINITION_METADATA_STALE =
"delete from definition_metadata where name like ? and last_updated < ?";
static final String DELETE_PARTITION_DEFINITION_METADATA =
"delete from partition_definition_metadata where name in (%s)";
static final String GET_DATA_METADATA =
"select uri name, data from data_metadata where uri=?";
static final String GET_DELETED_DATA_METADATA_URI =
"select uri from data_metadata_delete dmd join data_metadata dm on dmd.id=dm.id"
+ " where dmd.date_created < ? limit %d,%d";
static final String GET_DESCENDANT_DATA_URIS =
"select uri from data_metadata where uri like ?";
static final String GET_DESCENDANT_DEFINITION_NAMES =
"select name from partition_definition_metadata where name like ?";
static final String GET_DATA_METADATAS =
"select uri name,data from data_metadata where uri in (%s)";
static final String GET_DEFINITION_METADATA =
"select name, data from definition_metadata where name=?";
static final String GET_PARTITION_DEFINITION_METADATA =
"select name, data from partition_definition_metadata where name=?";
static final String GET_DEFINITION_METADATAS =
"select name,data from definition_metadata where name in (%s)";
static final String GET_PARTITION_DEFINITION_METADATAS =
"select name,data from partition_definition_metadata where name in (%s)";
static final String SEARCH_DEFINITION_METADATAS =
"select name,data from definition_metadata where 1=1";
static final String SEARCH_DEFINITION_METADATA_NAMES =
"select name from definition_metadata";
static final String INSERT_DATA_METADATA = "insert into data_metadata "
+ "(data, created_by, last_updated_by, date_created, last_updated, version, uri) values "
+ "(?, ?, ?, now(), now(), 0, ?)";
static final String INSERT_DEFINITION_METADATA = "insert into definition_metadata "
+ "(data, created_by, last_updated_by, date_created, last_updated, version, name) values "
+ "(?, ?, ?, now(), now(), 0, ?)";
static final String INSERT_PARTITION_DEFINITION_METADATA = "insert into partition_definition_metadata "
+ "(data, created_by, last_updated_by, date_created, last_updated, version, name) values "
+ "(?, ?, ?, now(), now(), 0, ?)";
static final String RENAME_DATA_METADATA = "update data_metadata set uri=? where uri=?";
static final String RENAME_DEFINITION_METADATA = "update definition_metadata set name=? where name=?";
static final String UPDATE_DATA_METADATA =
"update data_metadata set data=?, last_updated=now(), last_updated_by=? where uri=?";
static final String UPDATE_DEFINITION_METADATA =
"update definition_metadata set data=?, last_updated=now(), last_updated_by=? where name=?";
static final String UPDATE_PARTITION_DEFINITION_METADATA =
"update partition_definition_metadata set data=?, last_updated=now(), last_updated_by=? where name=?";
}
}
| 34 |
0 | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata | Create_ds/metacat/metacat-metadata-mysql/src/main/java/com/netflix/metacat/metadata/mysql/package-info.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package includes user metadata service classes.
*
* @author amajumdar
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.metadata.mysql;
import javax.annotation.ParametersAreNonnullByDefault;
| 35 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftConnectorFactory.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.server.connectors.DefaultConnectorFactory;
import java.util.Map;
/**
* Connector Factory for Redshift.
*
* @author tgianos
* @since 1.0.0
*/
class RedshiftConnectorFactory extends DefaultConnectorFactory {
/**
* Constructor.
*
* @param name catalog name
* @param catalogShardName catalog shard name
* @param configuration catalog configuration
*/
RedshiftConnectorFactory(
final String name,
final String catalogShardName,
final Map<String, String> configuration
) {
super(name, catalogShardName, Lists.newArrayList(new RedshiftConnectorModule(catalogShardName, configuration)));
}
}
| 36 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftConnectorPlugin.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.netflix.metacat.common.server.connectors.ConnectorFactory;
import com.netflix.metacat.common.server.connectors.ConnectorPlugin;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import lombok.NonNull;
import javax.annotation.Nonnull;
/**
* Redshift Connector Plugin.
*
* @author tgianos
* @since 1.0.0
*/
public class RedshiftConnectorPlugin implements ConnectorPlugin {
private static final String CONNECTOR_TYPE = "redshift";
private static final RedshiftTypeConverter TYPE_CONVERTER = new RedshiftTypeConverter();
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return CONNECTOR_TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public ConnectorFactory create(@Nonnull @NonNull final ConnectorContext connectorContext) {
return new RedshiftConnectorFactory(connectorContext.getCatalogName(),
connectorContext.getCatalogShardName(), connectorContext.getConfiguration());
}
/**
* {@inheritDoc}
*/
@Override
public ConnectorTypeConverter getTypeConverter() {
return TYPE_CONVERTER;
}
}
| 37 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftTypeConverter.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.netflix.metacat.common.type.BaseType;
import com.netflix.metacat.common.type.CharType;
import com.netflix.metacat.common.type.DecimalType;
import com.netflix.metacat.common.type.Type;
import com.netflix.metacat.common.type.VarcharType;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import lombok.extern.slf4j.Slf4j;
/**
* Type converter for Redshift.
*
* @author tgianos
* @since 1.0.0
*/
@Slf4j
public class RedshiftTypeConverter extends JdbcTypeConverter {
static final int DEFAULT_CHARACTER_LENGTH = 256;
private static final String DEFAULT_CHARACTER_LENGTH_STRING = Integer.toString(DEFAULT_CHARACTER_LENGTH);
/**
* {@inheritDoc}
*
* @see <a href="http://docs.aws.amazon.com/redshift/latest/dg/c_Supported_data_types.html">Redshift Types</a>
* @see <a href="http://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-datatypes.html">
* Unsupported PostgreSQL Types
* </a>
*/
@Override
public Type toMetacatType(final String type) {
// See: https://www.postgresql.org/docs/current/static/datatype.html
final String lowerType = type.toLowerCase();
// Split up the possible type: TYPE[(size, magnitude)] EXTRA
final String[] splitType = this.splitType(lowerType);
switch (splitType[0]) {
case "smallint":
case "int2":
return BaseType.SMALLINT;
case "int":
case "integer":
case "int4":
return BaseType.INT;
case "int8":
case "bigint":
case "oid":
return BaseType.BIGINT;
case "decimal":
case "numeric":
return this.toMetacatDecimalType(splitType);
case "real":
case "float4":
return BaseType.FLOAT;
case "double precision":
case "float8":
case "float":
return BaseType.DOUBLE;
case "character varying":
case "varchar":
case "nvarchar":
fixDataSizeIfIncorrect(splitType);
return this.toMetacatVarcharType(splitType);
case "text":
case "name":
// text is basically alias for VARCHAR(256)
splitType[1] = DEFAULT_CHARACTER_LENGTH_STRING;
return this.toMetacatVarcharType(splitType);
case "character":
case "char":
case "nchar":
fixDataSizeIfIncorrect(splitType);
return this.toMetacatCharType(splitType);
case "bpchar":
// bpchar defaults to fixed length of 256 characters
splitType[1] = DEFAULT_CHARACTER_LENGTH_STRING;
return this.toMetacatCharType(splitType);
case "timestamp":
return this.toMetacatTimestampType(splitType);
case "timestampz":
return BaseType.TIMESTAMP_WITH_TIME_ZONE;
case "date":
return BaseType.DATE;
case "boolean":
case "bool":
return BaseType.BOOLEAN;
default:
// see: http://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-datatypes.html
log.info("Unhandled or unknown Redshift type {}", splitType[0]);
return BaseType.UNKNOWN;
}
}
private void fixDataSizeIfIncorrect(final String[] splitType) {
//
// Adding a hack to ignore errors for data type with negative size.
// TODO: Remove this hack when we have a solution for the above.
//
if (splitType[1] == null || Integer.parseInt(splitType[1]) <= 0) {
splitType[1] = DEFAULT_CHARACTER_LENGTH_STRING;
}
}
/**
* {@inheritDoc}
*/
@Override
public String fromMetacatType(final Type type) {
switch (type.getTypeSignature().getBase()) {
case ARRAY:
throw new UnsupportedOperationException("Redshift doesn't support array types");
case BIGINT:
return "BIGINT";
case BOOLEAN:
return "BOOLEAN";
case CHAR:
if (!(type instanceof CharType)) {
throw new IllegalArgumentException("Expected CHAR type but was " + type.getClass().getName());
}
final CharType charType = (CharType) type;
return "CHAR(" + charType.getLength() + ")";
case DATE:
return "DATE";
case DECIMAL:
if (!(type instanceof DecimalType)) {
throw new IllegalArgumentException("Expected decimal type but was " + type.getClass().getName());
}
final DecimalType decimalType = (DecimalType) type;
return "DECIMAL(" + decimalType.getPrecision() + ", " + decimalType.getScale() + ")";
case DOUBLE:
case FLOAT:
return "DOUBLE PRECISION";
case INT:
return "INT";
case INTERVAL_DAY_TO_SECOND:
throw new UnsupportedOperationException("Redshift doesn't support interval types");
case INTERVAL_YEAR_TO_MONTH:
throw new UnsupportedOperationException("Redshift doesn't support interval types");
case JSON:
throw new UnsupportedOperationException("Redshift doesn't support JSON types");
case MAP:
throw new UnsupportedOperationException("Redshift doesn't support MAP types");
case ROW:
throw new UnsupportedOperationException("Redshift doesn't support ROW types");
case SMALLINT:
return "SMALLINT";
case STRING:
throw new UnsupportedOperationException("Redshift doesn't support STRING types");
case TIME:
case TIME_WITH_TIME_ZONE:
throw new UnsupportedOperationException("Redshift doesn't support TIME types");
case TIMESTAMP:
return "TIMESTAMP";
case TIMESTAMP_WITH_TIME_ZONE:
return "TIMESTAMPZ";
case TINYINT:
// NOTE: There is no tiny int type in Redshift so using slightly larger SMALLINT
return "SMALLINT";
case UNKNOWN:
throw new IllegalArgumentException("Can't map an unknown type");
case VARBINARY:
throw new UnsupportedOperationException("Redshift doesn't support VARBINARY types");
case VARCHAR:
if (!(type instanceof VarcharType)) {
throw new IllegalArgumentException("Expected varchar type but was " + type.getClass().getName());
}
final VarcharType varcharType = (VarcharType) type;
// NOTE: PostgreSQL lets you store up to 1GB in a varchar field which is about the same as TEXT
return "VARCHAR(" + varcharType.getLength() + ")";
default:
throw new IllegalArgumentException("Unknown type " + type.getTypeSignature().getBase());
}
}
}
| 38 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftExceptionMapper.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.connectors.exception.ConnectorException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseNotFoundException;
import com.netflix.metacat.common.server.connectors.exception.TableAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.TableNotFoundException;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import java.sql.SQLException;
/**
* Exception mapper for Redshift SQLExceptions.
*
* @author tgianos
* @author zhenl
* @see SQLException
* @see ConnectorException
* @see <a href="https://www.postgresql.org/docs/current/static/errcodes-appendix.html">PostgreSQL Ref</a>
* @since 1.0.0
*/
public class RedshiftExceptionMapper implements JdbcExceptionMapper {
/**
* {@inheritDoc}
*/
@Override
public ConnectorException toConnectorException(
final SQLException se,
final QualifiedName name
) {
// TODO: For now as can't find documentation stating contrary this is a copy of PostgreSQL implementation.
// Source code looks pretty unclear too at cursory glance
final String sqlState = se.getSQLState();
if (sqlState == null) {
throw new ConnectorException(se.getMessage(), se);
}
switch (sqlState) {
case "42P04": //database already exists
return new DatabaseAlreadyExistsException(name, se);
case "42P07": //table already exists
return new TableAlreadyExistsException(name, se);
case "3D000":
case "3F000": //database does not exist
return new DatabaseNotFoundException(name, se);
case "42P01": //table doesn't exist
return new TableNotFoundException(name, se);
default:
return new ConnectorException(se.getMessage(), se);
}
}
}
| 39 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftConnectorTableService.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.google.inject.Inject;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService;
import javax.sql.DataSource;
/**
* Redshift table service implementation.
*
* @author tgianos
* @since 1.0.8
*/
public class RedshiftConnectorTableService extends JdbcConnectorTableService {
/**
* Constructor.
*
* @param dataSource the datasource to use to connect to the database
* @param typeConverter The type converter to use from the SQL type to Metacat canonical type
* @param exceptionMapper The exception mapper to use
*/
@Inject
public RedshiftConnectorTableService(
final DataSource dataSource,
final JdbcTypeConverter typeConverter,
final JdbcExceptionMapper exceptionMapper
) {
super(dataSource, typeConverter, exceptionMapper);
}
/**
* {@inheritDoc}
*/
@Override
protected String getRenameTableSql(
final QualifiedName oldName,
final String finalOldTableName,
final String finalNewTableName
) {
return "ALTER TABLE "
+ oldName.getDatabaseName()
+ "."
+ finalOldTableName
+ " RENAME TO "
+ finalNewTableName;
}
/**
* {@inheritDoc}
*/
@Override
protected String getDropTableSql(final QualifiedName name, final String finalTableName) {
return "DROP TABLE " + name.getCatalogName() + "." + name.getDatabaseName() + "." + finalTableName;
}
}
| 40 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes for the Redshift Connector implementation.
*
* @author tgianos
* @since 1.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.connector.redshift;
import javax.annotation.ParametersAreNonnullByDefault;
| 41 |
0 | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-redshift/src/main/java/com/netflix/metacat/connector/redshift/RedshiftConnectorModule.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.redshift;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.netflix.metacat.common.server.connectors.ConnectorDatabaseService;
import com.netflix.metacat.common.server.connectors.ConnectorPartitionService;
import com.netflix.metacat.common.server.connectors.ConnectorTableService;
import com.netflix.metacat.common.server.connectors.ConnectorUtils;
import com.netflix.metacat.common.server.util.DataSourceManager;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import com.netflix.metacat.connector.jdbc.JdbcTypeConverter;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorDatabaseService;
import com.netflix.metacat.connector.jdbc.services.JdbcConnectorPartitionService;
import javax.sql.DataSource;
import java.util.Map;
/**
* Guice module for the Redshift Connector.
*
* @author tgianos
* @since 1.0.0
*/
public class RedshiftConnectorModule extends AbstractModule {
private final String catalogShardName;
private final Map<String, String> configuration;
/**
* Constructor.
*
* @param catalogShardName catalog shard name
* @param configuration connector configuration
*/
RedshiftConnectorModule(
final String catalogShardName,
final Map<String, String> configuration
) {
this.catalogShardName = catalogShardName;
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
@Override
protected void configure() {
this.bind(DataSource.class).toInstance(DataSourceManager.get()
.load(this.catalogShardName, this.configuration).get(this.catalogShardName));
this.bind(JdbcTypeConverter.class).to(RedshiftTypeConverter.class).in(Scopes.SINGLETON);
this.bind(JdbcExceptionMapper.class).to(RedshiftExceptionMapper.class).in(Scopes.SINGLETON);
this.bind(ConnectorDatabaseService.class)
.to(ConnectorUtils.getDatabaseServiceClass(this.configuration, JdbcConnectorDatabaseService.class))
.in(Scopes.SINGLETON);
this.bind(ConnectorTableService.class)
.to(ConnectorUtils.getTableServiceClass(this.configuration, RedshiftConnectorTableService.class))
.in(Scopes.SINGLETON);
this.bind(ConnectorPartitionService.class)
.to(ConnectorUtils.getPartitionServiceClass(this.configuration, JdbcConnectorPartitionService.class))
.in(Scopes.SINGLETON);
}
}
| 42 |
0 | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig/PigConnectorPlugin.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.pig;
import com.netflix.metacat.common.server.connectors.ConnectorFactory;
import com.netflix.metacat.common.server.connectors.ConnectorPlugin;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import com.netflix.metacat.connector.pig.converters.PigTypeConverter;
import lombok.NonNull;
import javax.annotation.Nonnull;
/**
* S3 plugin.
*/
public class PigConnectorPlugin implements ConnectorPlugin {
/**
* Type of the connector.
*/
public static final String CONNECTOR_TYPE = "pig";
private static final PigTypeConverter PIG_TYPE_CONVERTER = new PigTypeConverter();
@Override
public String getType() {
return CONNECTOR_TYPE;
}
@Override
public ConnectorFactory create(@Nonnull @NonNull final ConnectorContext connectorContext) {
return null;
}
@Override
public ConnectorTypeConverter getTypeConverter() {
return PIG_TYPE_CONVERTER;
}
}
| 43 |
0 | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Pig connector classes.
*/
package com.netflix.metacat.connector.pig;
| 44 |
0 | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig/converters/PigTypeMapping.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.pig.converters;
import com.google.common.collect.ImmutableMap;
import com.netflix.metacat.common.type.BaseType;
import com.netflix.metacat.common.type.Type;
import com.netflix.metacat.common.type.VarbinaryType;
import lombok.Getter;
import org.apache.pig.data.DataType;
import java.util.Map;
/**
* Pig type mapping.
*/
public class PigTypeMapping {
@Getter
private static final Map<Type, Byte> CANONICAL_TO_PIG = new ImmutableMap.Builder<Type, Byte>()
.put(VarbinaryType.VARBINARY, Byte.valueOf(DataType.BYTEARRAY))
.put(BaseType.BOOLEAN, Byte.valueOf(DataType.BOOLEAN))
.put(BaseType.INT, Byte.valueOf(DataType.INTEGER))
.put(BaseType.SMALLINT, Byte.valueOf(DataType.INTEGER))
.put(BaseType.TINYINT, Byte.valueOf(DataType.INTEGER))
.put(BaseType.BIGINT, Byte.valueOf(DataType.LONG))
.put(BaseType.FLOAT, Byte.valueOf(DataType.FLOAT))
.put(BaseType.DOUBLE, Byte.valueOf(DataType.DOUBLE))
.put(BaseType.TIMESTAMP, Byte.valueOf(DataType.DATETIME))
.put(BaseType.TIMESTAMP_WITH_TIME_ZONE, Byte.valueOf(DataType.DATETIME))
.put(BaseType.DATE, Byte.valueOf(DataType.DATETIME))
.put(BaseType.TIME, Byte.valueOf(DataType.DATETIME))
.put(BaseType.STRING, Byte.valueOf(DataType.CHARARRAY))
.put(BaseType.UNKNOWN, Byte.valueOf(DataType.UNKNOWN))
.build();
@Getter
private static final Map<Byte, Type> PIG_TO_CANONICAL = new ImmutableMap.Builder<Byte, Type>()
.put(Byte.valueOf(DataType.BOOLEAN), BaseType.BOOLEAN)
.put(Byte.valueOf(DataType.UNKNOWN), BaseType.UNKNOWN)
.put(Byte.valueOf(DataType.BYTE), VarbinaryType.VARBINARY)
.put(Byte.valueOf(DataType.BYTEARRAY), VarbinaryType.VARBINARY)
.put(Byte.valueOf(DataType.INTEGER), BaseType.INT)
.put(Byte.valueOf(DataType.LONG), BaseType.BIGINT)
.put(Byte.valueOf(DataType.BIGINTEGER), BaseType.BIGINT)
.put(Byte.valueOf(DataType.FLOAT), BaseType.FLOAT)
.put(Byte.valueOf(DataType.DOUBLE), BaseType.DOUBLE)
.put(Byte.valueOf(DataType.BIGDECIMAL), BaseType.DOUBLE)
.put(Byte.valueOf(DataType.DATETIME), BaseType.TIMESTAMP)
.put(Byte.valueOf(DataType.CHARARRAY), BaseType.STRING)
.put(Byte.valueOf(DataType.BIGCHARARRAY), BaseType.STRING)
.build();
}
| 45 |
0 | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig/converters/PigTypeConverter.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.connector.pig.converters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.type.ArrayType;
import com.netflix.metacat.common.type.BaseType;
import com.netflix.metacat.common.type.CharType;
import com.netflix.metacat.common.type.DecimalType;
import com.netflix.metacat.common.type.MapType;
import com.netflix.metacat.common.type.RowType;
import com.netflix.metacat.common.type.Type;
import com.netflix.metacat.common.type.TypeUtils;
import com.netflix.metacat.common.type.VarcharType;
import lombok.NonNull;
import org.apache.pig.backend.executionengine.ExecutionEngine;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.LocalExecType;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.newplan.logical.Util;
import org.apache.pig.newplan.logical.relational.LogicalSchema;
import org.apache.pig.parser.QueryParserDriver;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
/**
* Class to convert pig to canonical type and vice versa.
*/
public class PigTypeConverter implements ConnectorTypeConverter {
private static final String NAME_ARRAY_ELEMENT = "array_element";
private static final PigContext PIG_CONTEXT = new PigContext(new LocalExecType() {
private static final long serialVersionUID = -54152102366768171L;
@Override
public ExecutionEngine getExecutionEngine(final PigContext pigContext) {
return null;
}
}, new Properties());
/**
* {@inheritDoc}.
*/
@Override
public Type toMetacatType(@Nonnull @NonNull final String pigType) {
try {
final LogicalSchema schema = new QueryParserDriver(PIG_CONTEXT,
"util", new HashMap<>()).parseSchema(pigType);
final LogicalSchema.LogicalFieldSchema field = schema.getField(0);
return toCanonicalType(field);
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Invalid type signature: '%s'", pigType));
}
}
/**
* {@inheritDoc}.
*/
@Override
public String fromMetacatType(@Nonnull @NonNull final Type type) {
final Schema schema = new Schema(Util.translateFieldSchema(fromCanonicalTypeToPigSchema(null, type)));
final StringBuilder result = new StringBuilder();
try {
Schema.stringifySchema(result, schema, DataType.GENERIC_WRITABLECOMPARABLE, Integer.MIN_VALUE);
} catch (FrontendException e) {
throw new IllegalArgumentException(String.format("Invalid for Pig converter: '%s'", type.getDisplayName()));
}
return result.toString();
}
private LogicalSchema.LogicalFieldSchema fromCanonicalTypeToPigSchema(final String alias,
final Type canonicalType) {
if (PigTypeMapping.getCANONICAL_TO_PIG().containsKey(canonicalType)) {
return new LogicalSchema.LogicalFieldSchema(alias,
null, PigTypeMapping.getCANONICAL_TO_PIG().get(canonicalType));
} else if (canonicalType instanceof DecimalType) {
return new LogicalSchema.LogicalFieldSchema(alias, null, DataType.DOUBLE);
} else if (canonicalType instanceof VarcharType || canonicalType instanceof CharType) {
return new LogicalSchema.LogicalFieldSchema(alias, null, DataType.CHARARRAY);
} else if (canonicalType instanceof MapType) {
final MapType mapType = (MapType) canonicalType;
LogicalSchema schema = null;
if (((MapType) canonicalType).getValueType() != null
&& !BaseType.UNKNOWN.equals(mapType.getValueType())) {
schema = new LogicalSchema();
schema.addField(fromCanonicalTypeToPigSchema(null, mapType.getValueType()));
}
return new LogicalSchema.LogicalFieldSchema(alias, schema, DataType.MAP);
} else if (canonicalType instanceof ArrayType) {
final ArrayType arrayType = (ArrayType) canonicalType;
final LogicalSchema schema = new LogicalSchema();
Type elementType = arrayType.getElementType();
if (elementType != null) {
if (!(elementType instanceof RowType)) {
elementType = RowType.createRowType(
Lists.newArrayList(elementType),
ImmutableList.of(NAME_ARRAY_ELEMENT)
);
}
schema.addField(fromCanonicalTypeToPigSchema(null, elementType));
}
return new LogicalSchema.LogicalFieldSchema(alias, schema, DataType.BAG);
} else if (canonicalType instanceof RowType) {
final LogicalSchema schema = new LogicalSchema();
for (RowType.RowField rowField : ((RowType) canonicalType).getFields()) {
schema.addField(fromCanonicalTypeToPigSchema(
rowField.getName() != null ? rowField.getName() : alias,
rowField.getType()));
}
return new LogicalSchema.LogicalFieldSchema(alias, schema, DataType.TUPLE);
}
throw new IllegalArgumentException(String.format("Invalid for Pig converter: '%s'",
canonicalType.getDisplayName()));
}
private Type toCanonicalType(final LogicalSchema.LogicalFieldSchema field) {
if (PigTypeMapping.getPIG_TO_CANONICAL().containsKey(field.type)) {
return PigTypeMapping.getPIG_TO_CANONICAL().get(field.type);
}
switch (field.type) {
case DataType.MAP:
return toCanonicalMapType(field);
case DataType.BAG:
return toCanonicalArrayType(field);
case DataType.TUPLE:
return toCanonicalRowType(field);
default:
}
throw new IllegalArgumentException(String.format("Invalid for Pig converter: '%s'", field.toString()));
}
private Type toCanonicalRowType(final LogicalSchema.LogicalFieldSchema field) {
final List<Type> fieldTypes = Lists.newArrayList();
final List<String> fieldNames = Lists.newArrayList();
for (LogicalSchema.LogicalFieldSchema logicalFieldSchema : field.schema.getFields()) {
fieldTypes.add(toCanonicalType(logicalFieldSchema));
fieldNames.add(logicalFieldSchema.alias);
}
return RowType.createRowType(fieldTypes, fieldNames);
}
private Type toCanonicalArrayType(final LogicalSchema.LogicalFieldSchema field) {
final LogicalSchema.LogicalFieldSchema subField = field.schema.getField(0);
final Type elementType;
if (subField.type == DataType.TUPLE
&& !TypeUtils.isNullOrEmpty(subField.schema.getFields())
&& NAME_ARRAY_ELEMENT.equals(subField.schema.getFields().get(0).alias)) {
elementType = toCanonicalType(subField.schema.getFields().get(0));
} else {
elementType = toCanonicalType(subField);
}
return new ArrayType(elementType);
}
private Type toCanonicalMapType(final LogicalSchema.LogicalFieldSchema field) {
final Type key = BaseType.STRING;
Type value = BaseType.UNKNOWN;
if (null != field.schema && !TypeUtils.isNullOrEmpty(field.schema.getFields())) {
value = toCanonicalType(field.schema.getFields().get(0));
}
return new MapType(key, value);
}
}
| 46 |
0 | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig | Create_ds/metacat/metacat-connector-pig/src/main/java/com/netflix/metacat/connector/pig/converters/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Created by zhenl on 1/13/17.
*/
package com.netflix.metacat.connector.pig.converters;
| 47 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/MetacatApplication.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
/**
* Spring Boot Metacat application entry point.
*
* @author tgianos
* @since 1.1.0
*/
@SpringBootApplication
@ComponentScan(excludeFilters = @Filter(type = FilterType.ASPECTJ, pattern = "com.netflix.metacat.connector..*"))
public class MetacatApplication {
/**
* Constructor.
*/
protected MetacatApplication() {
}
/**
* Main.
*
* @param args Program arguments
*/
public static void main(final String[] args) {
SpringApplication.run(MetacatApplication.class, args);
}
}
| 48 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Top level package for boot application files.
*
* @author tgianos
* @since 1.1.0
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat;
import javax.annotation.ParametersAreNonnullByDefault;
| 49 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/manager/CatalogManager.java | package com.netflix.metacat.main.manager;
import org.springframework.context.ApplicationContext;
/**
* Interface that defines how catalogs should be loaded.
*/
public interface CatalogManager {
/**
* Flag indicating whether all catalogs have been loaded.
*
* @return True if they've been loaded.
*/
boolean areCatalogsLoaded();
/**
* Load the catalogs for this applicationContext.
*
* @param applicationContext The application context.
* @throws Exception exception if we failed to load a catalog.
*/
void loadCatalogs(ApplicationContext applicationContext) throws Exception;
}
| 50 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/manager/PluginManager.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.manager;
import com.google.common.collect.ImmutableList;
import com.netflix.metacat.common.server.connectors.ConnectorPlugin;
import com.netflix.metacat.common.server.converter.TypeConverterFactory;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Plugin Manager. This loads the connector plugins using the ServiceLoader.
* Connector plugins need to be loaded before loading the catalogs.
*/
@Slf4j
public class PluginManager {
private final ConnectorManager connectorManager;
private final TypeConverterFactory typeConverterFactory;
private final AtomicBoolean pluginsLoaded = new AtomicBoolean();
private final AtomicBoolean pluginsLoading = new AtomicBoolean();
/**
* Constructor.
*
* @param connectorManager manager
* @param typeConverterFactory provider for type converters
*/
public PluginManager(
final ConnectorManager connectorManager,
final TypeConverterFactory typeConverterFactory
) {
this.connectorManager = connectorManager;
this.typeConverterFactory = typeConverterFactory;
}
/**
* Returns true if plugins are loaded.
*
* @return true if plugins are loaded.
*/
public boolean arePluginsLoaded() {
return pluginsLoaded.get();
}
/**
* Loads the plugins.
*
* @throws Exception error
*/
public void loadPlugins() throws Exception {
if (!this.pluginsLoading.compareAndSet(false, true)) {
return;
}
final ServiceLoader<ConnectorPlugin> serviceLoader =
ServiceLoader.load(ConnectorPlugin.class, this.getClass().getClassLoader());
final List<ConnectorPlugin> connectorPlugins = ImmutableList.copyOf(serviceLoader);
if (connectorPlugins.isEmpty()) {
log.warn("No service providers of type {}", ConnectorPlugin.class.getName());
}
for (ConnectorPlugin connectorPlugin : connectorPlugins) {
log.info("Installing {}", connectorPlugin.getClass().getName());
this.installPlugin(connectorPlugin);
log.info("-- Finished loading plugin {} --", connectorPlugin.getClass().getName());
}
this.pluginsLoaded.set(true);
}
/**
* Installs the plugins.
*
* @param connectorPlugin service plugin
*/
private void installPlugin(final ConnectorPlugin connectorPlugin) {
this.connectorManager.addPlugin(connectorPlugin);
this.typeConverterFactory.register(connectorPlugin.getType(), connectorPlugin.getTypeConverter());
}
}
| 51 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/manager/DefaultCatalogManager.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.manager;
import com.google.common.base.Preconditions;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.spi.MetacatCatalogConfig;
import com.netflix.metacat.common.server.util.MetacatUtils;
import com.netflix.spectator.api.Registry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Catalog manager. This loads the catalogs defined as .properties files under the location defined by config property
* <code>metacat.plugin.config.location</code>.
* Usually there is a one-to-one mapping between a catalog and a data store. We could also have data stores
* (mostly sharded) addressed by a single catalog name.
* If a data store is sharded and needs to be represented by a single catalog name, then we will have multiple catalog
* property files, each referencing to its physical data store and having the same <code>catalog.name</code>.
* In this case, <code>catalog.name</code> and <code>metacat.schema.whitelist</code> will be used to point to the right
* data store. A catalog with no <code>metacat.schema.whitelist</code> setting will be the default catalog representing
* all databases for the <code>catalog.name</code>.
*/
@Slf4j
public class DefaultCatalogManager implements CatalogManager {
private final ConnectorManager connectorManager;
private final File catalogConfigurationDir;
private final AtomicBoolean catalogsLoading = new AtomicBoolean();
private final AtomicBoolean catalogsLoaded = new AtomicBoolean();
private final Registry registry;
private final Config config;
/**
* Constructor.
*
* @param connectorManager manager
* @param config config
* @param registry registry of spectator
*/
public DefaultCatalogManager(
final ConnectorManager connectorManager,
final Config config,
final Registry registry
) {
this.connectorManager = connectorManager;
this.config = config;
this.catalogConfigurationDir = new File(config.getPluginConfigLocation());
this.registry = registry;
}
/**
* Returns true if all catalogs are loaded.
*
* @return true if all catalogs are loaded
*/
@Override
public boolean areCatalogsLoaded() {
return this.catalogsLoaded.get();
}
/**
* Loads catalogs.
*
* @param applicationContext spring application context
* @throws Exception error
*/
@Override
public void loadCatalogs(final ApplicationContext applicationContext) throws Exception {
if (!this.catalogsLoading.compareAndSet(false, true)) {
return;
}
for (final File file : MetacatUtils.listFiles(this.catalogConfigurationDir)) {
if (file.isFile() && file.getName().endsWith(".properties")) {
this.loadCatalog(file, applicationContext);
}
}
this.catalogsLoaded.set(true);
}
protected void loadCatalog(final File file, final ApplicationContext applicationContext) throws Exception {
log.info("-- Loading catalog {} --", file);
final Map<String, String> properties = new HashMap<>(MetacatUtils.loadProperties(file));
final String connectorType = properties.remove(MetacatCatalogConfig.Keys.CONNECTOR_NAME);
Preconditions.checkState(
connectorType != null,
"Catalog configuration %s does not contain connector.name",
file.getAbsoluteFile()
);
// Pass in the server application context to the connector context.
final ConnectorContext connectorContext = MetacatUtils.buildConnectorContext(file,
connectorType, config, registry, applicationContext, properties);
this.connectorManager.createConnection(connectorContext);
log.info("-- Added catalog {} shard {} using connector {} --",
connectorContext.getCatalogName(), connectorContext.getCatalogShardName(), connectorType);
}
}
| 52 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/manager/ConnectorManager.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.manager;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.connectors.ConnectorCatalogService;
import com.netflix.metacat.common.server.connectors.ConnectorContext;
import com.netflix.metacat.common.server.connectors.ConnectorDatabaseService;
import com.netflix.metacat.common.server.connectors.ConnectorFactory;
import com.netflix.metacat.common.server.connectors.ConnectorFactoryDecorator;
import com.netflix.metacat.common.server.connectors.ConnectorInfoConverter;
import com.netflix.metacat.common.server.connectors.ConnectorPartitionService;
import com.netflix.metacat.common.server.connectors.ConnectorPlugin;
import com.netflix.metacat.common.server.connectors.ConnectorRequestContext;
import com.netflix.metacat.common.server.connectors.ConnectorTableService;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.server.connectors.exception.CatalogNotFoundException;
import com.netflix.metacat.common.server.connectors.model.CatalogInfo;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.spi.MetacatCatalogConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import javax.annotation.Nonnull;
import javax.annotation.PreDestroy;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Connector manager.
*/
@Slf4j
@RequiredArgsConstructor
public class ConnectorManager {
private static final String EMPTY_STRING = "";
// Map of connector plugins registered.
private final ConcurrentMap<String, ConnectorPlugin> plugins = new ConcurrentHashMap<>();
/**
* Table of catalog name, database name to catalog data stores. Usually there is a one-to-one mapping between the
* catalog name and the data store. In this case the table will have the databse name as null. If there are multiple
* catalogs addressed by the same <code>catalog.name</code> pointing to shards of a data store, then there will be
* multiple entries in this table. An entry will be identified using the catalog name and the database name.
*/
private final Table<String, String, CatalogHolder> catalogs = HashBasedTable.create();
private final Set<MetacatCatalogConfig> catalogConfigs = Sets.newHashSet();
private final Set<ConnectorDatabaseService> databaseServices = Sets.newHashSet();
private final Set<ConnectorTableService> tableServices = Sets.newHashSet();
private final Set<ConnectorPartitionService> partitionServices = Sets.newHashSet();
private final AtomicBoolean stopped = new AtomicBoolean();
private final Config config;
/**
* Stop.
*/
@PreDestroy
public void stop() {
if (stopped.getAndSet(true)) {
return;
}
catalogs.values().forEach(catalogHolder -> {
try {
catalogHolder.getConnectorFactory().stop();
} catch (Throwable t) {
log.error("Error shutting down connector: {}", catalogHolder.getConnectorFactory().getCatalogName(), t);
}
});
}
/**
* add Plugin.
*
* @param connectorPlugin connector plugin
*/
public void addPlugin(final ConnectorPlugin connectorPlugin) {
plugins.put(connectorPlugin.getType(), connectorPlugin);
}
/**
* Creates a connection for the given catalog.
*
* @param connectorContext metacat connector properties
*/
public synchronized void createConnection(final ConnectorContext connectorContext) {
Preconditions.checkState(!stopped.get(), "ConnectorManager is stopped");
final String connectorType = connectorContext.getConnectorType();
final String catalogName = connectorContext.getCatalogName();
final String catalogShardName = connectorContext.getCatalogShardName();
final ConnectorPlugin connectorPlugin = plugins.get(connectorType);
if (connectorPlugin != null) {
final MetacatCatalogConfig catalogConfig =
MetacatCatalogConfig.createFromMapAndRemoveProperties(connectorType, catalogName,
connectorContext.getConfiguration());
final List<String> databaseNames = catalogConfig.getSchemaWhitelist();
if (databaseNames.isEmpty()) {
Preconditions.checkState(!catalogs.contains(catalogName, EMPTY_STRING),
"A catalog with name %s already exists", catalogName);
} else {
databaseNames.forEach(databaseName -> {
Preconditions.checkState(!catalogs.contains(catalogName, databaseName),
"A catalog with name %s for database %s already exists", catalogName, databaseName);
});
}
catalogConfigs.add(catalogConfig);
final ConnectorFactory connectorFactory = new ConnectorFactoryDecorator(connectorPlugin, connectorContext);
try {
databaseServices.add(connectorFactory.getDatabaseService());
} catch (UnsupportedOperationException e) {
log.debug("Catalog {}:{} doesn't support getDatabaseService. Ignoring.", catalogName, catalogShardName);
}
try {
tableServices.add(connectorFactory.getTableService());
} catch (UnsupportedOperationException e) {
log.debug("Catalog {}:{} doesn't support getTableService. Ignoring.", catalogName, catalogShardName);
}
try {
partitionServices.add(connectorFactory.getPartitionService());
} catch (UnsupportedOperationException e) {
log.debug("Catalog {}:{} doesn't support getPartitionService. Ignoring.",
catalogName, catalogShardName);
}
final CatalogHolder catalogHolder = new CatalogHolder(catalogConfig, connectorFactory);
if (databaseNames.isEmpty()) {
catalogs.put(catalogName, EMPTY_STRING, catalogHolder);
} else {
databaseNames.forEach(databaseName -> {
catalogs.put(catalogName, databaseName, catalogHolder);
});
}
} else {
log.warn("No plugin for connector with type {}", connectorType);
}
}
/**
* Returns a set of catalog holders.
*
* @param catalogName catalog name
* @return catalog holders
*/
@Nonnull
private Set<CatalogHolder> getCatalogHolders(final String catalogName) {
final Map<String, CatalogHolder> result = getCatalogHoldersByDatabaseName(catalogName);
if (result.isEmpty()) {
throw new CatalogNotFoundException(catalogName);
} else {
return Sets.newHashSet(result.values());
}
}
private Map<String, CatalogHolder> getCatalogHoldersByDatabaseName(final String catalogName) {
Map<String, CatalogHolder> result = catalogs.row(catalogName);
if (result.isEmpty()) {
final String proxyCatalogName = getConnectorNameFromCatalogName(catalogName);
if (!Strings.isNullOrEmpty(proxyCatalogName)) {
result = catalogs.row(proxyCatalogName);
}
}
return result;
}
/**
* This method should be called only for a proxy catalog. A proxy catalog is a connector catalog that acts as a
* proxy to another service that contains the actual list of catalogs. The convention of the naming is such that
* the connector name is prefixed to the catalog names. Ex: For a catalog configuration with name as 'cde', the
* catalogs under it will be prefixed by 'cde_'.
*
* @param catalogName catalog name
* @return connector name
*/
private String getConnectorNameFromCatalogName(final String catalogName) {
String result = null;
final Iterator<String> splits = Splitter.on("_").limit(2).split(catalogName).iterator();
if (splits.hasNext()) {
result = splits.next();
}
return result;
}
/**
* Returns the catalog holder.
*
* @param name name
* @return catalog holder
*/
@Nonnull
private CatalogHolder getCatalogHolder(final QualifiedName name) {
final String catalogName = name.getCatalogName();
final String databaseName = name.isDatabaseDefinition() ? name.getDatabaseName() : EMPTY_STRING;
final Map<String, CatalogHolder> catalogHolders = getCatalogHoldersByDatabaseName(catalogName);
final CatalogHolder result = catalogHolders.containsKey(databaseName)
? catalogHolders.get(databaseName) : catalogHolders.get(EMPTY_STRING);
if (result == null) {
throw new CatalogNotFoundException(catalogName);
}
return result;
}
/**
* Returns the catalog config based on the qualified name that may or may not have the database name.
* If database name is not present, then the default catalog is returned if there are multiple catalogs with
* the same catalog name.
*
* @param name name
* @return catalog config
*/
@Nonnull
public MetacatCatalogConfig getCatalogConfig(final QualifiedName name) {
return getCatalogHolder(name).getCatalogConfig();
}
/**
* Returns the catalog configs based on the catalog name. In the case where there are multiple catalogs with the
* same catalog name, this method will return multiple catalog configs.
*
* @param name name
* @return set of catalog configs
*/
@Nonnull
public Set<MetacatCatalogConfig> getCatalogConfigs(final String name) {
return getCatalogHolders(name).stream().map(CatalogHolder::getCatalogConfig).collect(Collectors.toSet());
}
/**
* Returns all catalog configs. In the case where a catalog is a proxy connector, the list of catalogs represented
* by the connector will not be included.
* @return set of catalog configs
*/
@Nonnull
public Set<MetacatCatalogConfig> getCatalogConfigs() {
return catalogConfigs;
}
/**
* Returns all catalogs. The list will also include the list of catalogs represented by a proxy connector.
* @return set of catalogs
*/
@Nonnull
public Set<CatalogInfo> getCatalogs() {
return catalogs.column(EMPTY_STRING).values().stream().flatMap(c -> {
final Stream.Builder<CatalogInfo> builder = Stream.builder();
final MetacatCatalogConfig catalogConfig = c.getCatalogConfig();
if (catalogConfig.isProxy()) {
c.getConnectorFactory().getCatalogService()
.list(new ConnectorRequestContext(), QualifiedName.ofCatalog(catalogConfig.getCatalogName()),
null, null, null)
.forEach(builder);
} else {
builder.accept(catalogConfig.toCatalogInfo());
}
return builder.build();
}).collect(Collectors.toSet());
}
/**
* Returns the connector factory for the given <code>name</code>.
*
* @param name qualified name
* @return Returns the connector factory for the given <code>name</code>
*/
private ConnectorFactory getConnectorFactory(final QualifiedName name) {
Preconditions.checkNotNull(name, "Name is null");
return getCatalogHolder(name).getConnectorFactory();
}
/**
* Returns the connector plugin for the given <code>catalogName</code>.
*
* @param connectorType connector type
* @return Returns the plugin for the given <code>catalogName</code>
*/
public ConnectorPlugin getPlugin(final String connectorType) {
Preconditions.checkNotNull(connectorType, "connectorType is null");
final ConnectorPlugin result = plugins.get(connectorType);
Preconditions.checkNotNull(result, "No connector plugin exists for type %s", connectorType);
return result;
}
/**
* Returns all the connector database services.
*
* @return Returns all the connector database services registered in the system.
*/
public Set<ConnectorDatabaseService> getDatabaseServices() {
return databaseServices;
}
/**
* Returns all the connector table services.
*
* @return Returns all the connector table services registered in the system.
*/
public Set<ConnectorTableService> getTableServices() {
return tableServices;
}
/**
* Returns all the connector partition services.
*
* @return Returns all the connector partition services registered in the system.
*/
public Set<ConnectorPartitionService> getPartitionServices() {
return partitionServices;
}
/**
* Returns the connector catalog service for the given <code>name</code>.
*
* @param name qualified name
* @return Returns the connector catalog service for the given <code>name</code>
*/
public ConnectorCatalogService getCatalogService(final QualifiedName name) {
return getConnectorFactory(name).getCatalogService();
}
/**
* Returns the connector database service for the given <code>name</code>.
*
* @param name qualified name
* @return Returns the connector database service for the given <code>name</code>
*/
public ConnectorDatabaseService getDatabaseService(final QualifiedName name) {
return getConnectorFactory(name).getDatabaseService();
}
/**
* Returns the connector table service for the given <code>name</code>.
*
* @param name qualified name
* @return Returns the connector table service for the given <code>name</code>
*/
public ConnectorTableService getTableService(final QualifiedName name) {
return getConnectorFactory(name).getTableService();
}
/**
* Returns the connector partition service for the given <code>name</code>.
*
* @param name qualified name
* @return Returns the connector partition service for the given <code>name</code>
*/
public ConnectorPartitionService getPartitionService(final QualifiedName name) {
return getConnectorFactory(name).getPartitionService();
}
/**
* Returns the connector type converter for the given <code>connectorType</code>.
*
* @param connectorType connector type
* @return Returns the connector type converter for the given <code>connectorType</code>
*/
public ConnectorTypeConverter getTypeConverter(final String connectorType) {
return getPlugin(connectorType).getTypeConverter();
}
/**
* Returns the connector dto converter for the given <code>connectorType</code>.
*
* @param connectorType connector type
* @return Returns the connector dto converter for the given <code>connectorType</code>
*/
public ConnectorInfoConverter getInfoConverter(final String connectorType) {
return getPlugin(connectorType).getInfoConverter();
}
/**
* A Holder class holding the catalog's config and connector factory.
*/
@Data
@AllArgsConstructor
private static class CatalogHolder {
private final MetacatCatalogConfig catalogConfig;
private final ConnectorFactory connectorFactory;
}
}
| 53 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/manager/package-info.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package includes initialization classes.
*
* @author amajumdar
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.main.manager;
import javax.annotation.ParametersAreNonnullByDefault;
| 54 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/PropertiesConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.properties.DefaultConfigImpl;
import com.netflix.metacat.common.server.properties.MetacatProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration for binding Metacat properties.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class PropertiesConfig {
/**
* Static properties bindings.
*
* @return The metacat properties.
*/
@Bean
@ConfigurationProperties("metacat")
public MetacatProperties metacatProperties() {
return new MetacatProperties();
}
/**
* Get the configuration abstraction for use in metacat.
*
* @param metacatProperties The overall metacat properties to use
* @return The configuration object
*/
@Bean
public Config config(final MetacatProperties metacatProperties) {
return new DefaultConfigImpl(metacatProperties);
}
}
| 55 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/SpringFoxConfig.java | package com.netflix.metacat.main.configs;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
import org.springframework.boot.actuate.endpoint.web.EndpointMapping;
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint;
import org.springframework.boot.actuate.endpoint.web.WebEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Needed to get SpringFox working with SBN 2.6+.
*/
@Configuration
public class SpringFoxConfig {
/**
* Needed this bean initialization to have springfox work with SBN 2.6+.
*
* @param webEndpointsSupplier web endpoint supplier
* @param servletEndpointsSupplier servlet endpoint supplier
* @param controllerEndpointsSupplier controller endpoint supplier
* @param endpointMediaTypes media types
* @param corsProperties CORS properties
* @param webEndpointProperties web endpoint properties
* @param environment application environment
* @return WebMvcEndpointHandlerMapping
*/
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(
final WebEndpointsSupplier webEndpointsSupplier,
final ServletEndpointsSupplier servletEndpointsSupplier,
final ControllerEndpointsSupplier controllerEndpointsSupplier,
final EndpointMediaTypes endpointMediaTypes,
final CorsEndpointProperties corsProperties,
final WebEndpointProperties webEndpointProperties,
final Environment environment) {
final List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
final Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
final String basePath = webEndpointProperties.getBasePath();
final EndpointMapping endpointMapping = new EndpointMapping(basePath);
final boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(
webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(final WebEndpointProperties webEndpointProperties,
final Environment environment,
final String basePath) {
return webEndpointProperties.getDiscovery().isEnabled()
&& (StringUtils.hasText(basePath)
|| ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
}
| 56 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/ThriftConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.metacat.common.server.api.v1.MetacatV1;
import com.netflix.metacat.common.server.api.v1.PartitionV1;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.main.services.MetacatThriftService;
import com.netflix.metacat.thrift.CatalogThriftServiceFactory;
import com.netflix.metacat.thrift.CatalogThriftServiceFactoryImpl;
import com.netflix.metacat.thrift.DateConverters;
import com.netflix.metacat.thrift.HiveConverters;
import com.netflix.metacat.thrift.HiveConvertersImpl;
import com.netflix.spectator.api.Registry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring Configuration for the Thrift Module.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class ThriftConfig {
/**
* The hive converters implementation to use.
*
* @return The hive converters
*/
@Bean
public HiveConverters hiveConverters() {
return new HiveConvertersImpl();
}
/**
* The Catalog Thrift Service Factory.
*
* @param config Application config to use
* @param hiveConverters Hive converters to use
* @param metacatV1 The Metacat V1 API implementation to use
* @param partitionV1 The Metacat Partition V1 API to use
* @param registry registry for spectator
* @return The CatalogThriftServiceFactory
*/
@Bean
public CatalogThriftServiceFactory catalogThriftServiceFactory(
final Config config,
final HiveConverters hiveConverters,
final MetacatV1 metacatV1,
final PartitionV1 partitionV1,
final Registry registry
) {
return new CatalogThriftServiceFactoryImpl(
config,
hiveConverters,
metacatV1,
partitionV1,
registry
);
}
/**
* The date converter utility bean.
*
* @param config System configuration
* @return The date converters bean to use
*/
//TODO: Not sure if this is needed doesn't seem to be being used
@Bean
public DateConverters dateConverters(final Config config) {
return new DateConverters(config);
}
/**
* The MetacatThriftService.
*
* @param catalogThriftServiceFactory The factory to use
* @param connectorManager The connector manager to use
* @return The service bean
*/
@Bean
public MetacatThriftService metacatThriftService(
final CatalogThriftServiceFactory catalogThriftServiceFactory,
final ConnectorManager connectorManager
) {
return new MetacatThriftService(catalogThriftServiceFactory, connectorManager);
}
}
| 57 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/MetricsConfig.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration of Metrics.
*
* @author rveeramacheneni
*/
@Configuration
public class MetricsConfig {
/**
* A default registry.
*
* @return The registry to use.
*/
@Bean
@ConditionalOnProperty(value = "metacat.metrics.default-registry.enabled", havingValue = "true")
public Registry spectatorRegistry() {
return new DefaultRegistry();
}
}
| 58 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/ServicesConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.server.api.ratelimiter.DefaultRateLimiter;
import com.netflix.metacat.common.server.api.ratelimiter.RateLimiter;
import com.netflix.metacat.common.server.api.traffic_control.DefaultRequestGateway;
import com.netflix.metacat.common.server.api.traffic_control.RequestGateway;
import com.netflix.metacat.common.server.converter.ConverterUtil;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.AliasService;
import com.netflix.metacat.common.server.usermetadata.AuthorizationService;
import com.netflix.metacat.common.server.usermetadata.DefaultAliasService;
import com.netflix.metacat.common.server.usermetadata.DefaultAuthorizationService;
import com.netflix.metacat.common.server.usermetadata.DefaultLookupService;
import com.netflix.metacat.common.server.usermetadata.DefaultTagService;
import com.netflix.metacat.common.server.usermetadata.DefaultUserMetadataService;
import com.netflix.metacat.common.server.usermetadata.LookupService;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.ThreadServiceManager;
import com.netflix.metacat.main.manager.CatalogManager;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.main.manager.PluginManager;
import com.netflix.metacat.main.services.CatalogService;
import com.netflix.metacat.main.services.CatalogTraversal;
import com.netflix.metacat.main.services.CatalogTraversalServiceHelper;
import com.netflix.metacat.main.services.DatabaseService;
import com.netflix.metacat.main.services.MViewService;
import com.netflix.metacat.main.services.MetacatServiceHelper;
import com.netflix.metacat.main.services.MetacatThriftService;
import com.netflix.metacat.main.services.MetadataService;
import com.netflix.metacat.main.services.OwnerValidationService;
import com.netflix.metacat.main.services.PartitionService;
import com.netflix.metacat.main.services.TableService;
import com.netflix.metacat.main.services.health.MetacatHealthIndicator;
import com.netflix.metacat.main.services.impl.CatalogServiceImpl;
import com.netflix.metacat.main.services.impl.ConnectorTableServiceProxy;
import com.netflix.metacat.main.services.impl.DatabaseServiceImpl;
import com.netflix.metacat.main.services.impl.DefaultOwnerValidationService;
import com.netflix.metacat.main.services.impl.MViewServiceImpl;
import com.netflix.metacat.main.services.impl.PartitionServiceImpl;
import com.netflix.metacat.main.services.impl.TableServiceImpl;
import com.netflix.metacat.main.services.init.MetacatCoreInitService;
import com.netflix.metacat.main.services.init.MetacatThriftInitService;
import com.netflix.spectator.api.Registry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration of Service Tier.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class ServicesConfig {
/**
* No-op User Metadata service.
*
* @return User metadata service based on MySql
*/
@Bean
@ConditionalOnMissingBean(UserMetadataService.class)
public UserMetadataService userMetadataService() {
return new DefaultUserMetadataService();
}
/**
* No-op Tag service.
*
* @return User metadata service based on MySql
*/
@Bean
@ConditionalOnMissingBean(TagService.class)
public TagService tagService() {
return new DefaultTagService();
}
/**
* Authorization service.
*
* @param config metacat config
* @return authorization class based on config
*/
@Bean
@ConditionalOnMissingBean(AuthorizationService.class)
public AuthorizationService authorizationService(
final Config config
) {
return new DefaultAuthorizationService(config);
}
/**
* Owner validation service.
* @param registry the spectator registry
* @return the owner validation service
*/
@Bean
@ConditionalOnMissingBean(OwnerValidationService.class)
public OwnerValidationService ownerValidationService(final Registry registry) {
return new DefaultOwnerValidationService(registry);
}
/**
* Alias service.
*
* @return an instance of the Alias service.
*/
@Bean
@ConditionalOnMissingBean(AliasService.class)
public AliasService aliasService() {
return new DefaultAliasService();
}
/**
* No-op Look up service.
*
* @return User metadata service based on MySql
*/
@Bean
@ConditionalOnMissingBean(LookupService.class)
public LookupService lookupService() {
return new DefaultLookupService();
}
/**
* RateLimiter service.
*
* @return The rate-limiter service bean.
*/
@Bean
@ConditionalOnMissingBean(RateLimiter.class)
public RateLimiter rateLimiter() {
return new DefaultRateLimiter();
}
/**
* The default {@link RequestGateway} bean.
*
* @return the default {@link RequestGateway} bean.
*/
@Bean
@ConditionalOnMissingBean(RequestGateway.class)
public RequestGateway requestGateway() {
return new DefaultRequestGateway();
}
/**
* The catalog service bean.
*
* @param connectorManager Connector manager to use
* @param userMetadataService User metadata service
* @param metacatEventBus Event bus to use
* @param converterUtil Converter utilities
* @return Catalog service implementation
*/
@Bean
public CatalogService catalogService(
final ConnectorManager connectorManager,
final UserMetadataService userMetadataService,
final MetacatEventBus metacatEventBus,
final ConverterUtil converterUtil
) {
return new CatalogServiceImpl(connectorManager, userMetadataService, metacatEventBus, converterUtil);
}
/**
* The database service bean.
*
* @param connectorManager Connector manager to use
* @param userMetadataService User metadata service to use
* @param metacatEventBus Event bus to use
* @param converterUtil Converter utilities
* @param authorizationService authorization Service
* @return Catalog service implementation
*/
@Bean
public DatabaseService databaseService(
final ConnectorManager connectorManager,
final UserMetadataService userMetadataService,
final MetacatEventBus metacatEventBus,
final ConverterUtil converterUtil,
final AuthorizationService authorizationService
) {
return new DatabaseServiceImpl(
connectorManager,
userMetadataService,
metacatEventBus,
converterUtil,
authorizationService
);
}
/**
* The table service bean.
*
* @param connectorManager Connector manager to use
* @param connectorTableServiceProxy connector table service proxy
* @param databaseService database service
* @param tagService tag service
* @param userMetadataService user metadata service
* @param metacatJson metacat json utility
* @param eventBus Internal event bus
* @param registry registry handle
* @param config configurations
* @param converterUtil converter utilities
* @param authorizationService authorization Service
* @param ownerValidationService owner validation service
*
* @return The table service bean
*/
@Bean
public TableService tableService(
final ConnectorManager connectorManager,
final ConnectorTableServiceProxy connectorTableServiceProxy,
final DatabaseService databaseService,
final TagService tagService,
final UserMetadataService userMetadataService,
final MetacatJson metacatJson,
final MetacatEventBus eventBus,
final Registry registry,
final Config config,
final ConverterUtil converterUtil,
final AuthorizationService authorizationService,
final OwnerValidationService ownerValidationService) {
return new TableServiceImpl(
connectorManager,
connectorTableServiceProxy,
databaseService,
tagService,
userMetadataService,
metacatJson,
eventBus,
registry,
config,
converterUtil,
authorizationService,
ownerValidationService
);
}
/**
* The connector table service proxy bean.
*
* @param connectorManager Connector manager to use
* @param converterUtil Converter utilities
* @return The connector table service proxy bean
*/
@Bean
public ConnectorTableServiceProxy connectorTableServiceProxy(
final ConnectorManager connectorManager,
final ConverterUtil converterUtil
) {
return new ConnectorTableServiceProxy(
connectorManager,
converterUtil
);
}
/**
* Partition service bean.
*
* @param catalogService catalog service
* @param connectorManager connector manager
* @param tableService table service
* @param userMetadataService user metadata service
* @param threadServiceManager thread manager
* @param config configurations
* @param eventBus Internal event bus
* @param converterUtil utility to convert to/from Dto to connector resources
* @param registry registry handle
* @return The partition service implementation to use
*/
@Bean
public PartitionService partitionService(
final CatalogService catalogService,
final ConnectorManager connectorManager,
final TableService tableService,
final UserMetadataService userMetadataService,
final ThreadServiceManager threadServiceManager,
final Config config,
final MetacatEventBus eventBus,
final ConverterUtil converterUtil,
final Registry registry
) {
return new PartitionServiceImpl(
catalogService,
connectorManager,
tableService,
userMetadataService,
threadServiceManager,
config,
eventBus,
converterUtil,
registry
);
}
/**
* The MViewService bean.
*
* @param connectorManager connector manager
* @param tableService table service
* @param partitionService partition service
* @param userMetadataService user metadata service
* @param eventBus Internal event bus
* @param converterUtil utility to convert to/from Dto to connector resources
* @return The MViewService implementation to use
*/
@Bean
public MViewService mViewService(
final ConnectorManager connectorManager,
final TableService tableService,
final PartitionService partitionService,
final UserMetadataService userMetadataService,
final MetacatEventBus eventBus,
final ConverterUtil converterUtil
) {
return new MViewServiceImpl(
connectorManager,
tableService,
partitionService,
userMetadataService,
eventBus,
converterUtil
);
}
/**
* The service helper.
*
* @param databaseService database service
* @param tableService table service
* @param partitionService partition service
* @param eventBus event bus
* @param mViewService view service
* @return The service helper instance to use
*/
@Bean
public MetacatServiceHelper metacatServiceHelper(
final DatabaseService databaseService,
final TableService tableService,
final PartitionService partitionService,
final MViewService mViewService,
final MetacatEventBus eventBus
) {
return new MetacatServiceHelper(databaseService, tableService, partitionService, mViewService, eventBus);
}
/**
* Metadata service bean.
*
* @param config System config
* @param tableService The table service to use
* @param partitionService The partition service to use
* @param userMetadataService The user metadata service to use
* @param tagService tag service
* @param helper Metacat service helper
* @param registry registry for spectator
* @return The metadata service bean
*/
@Bean
public MetadataService metadataService(
final Config config,
final TableService tableService,
final PartitionService partitionService,
final UserMetadataService userMetadataService,
final TagService tagService,
final MetacatServiceHelper helper,
final Registry registry
) {
return new MetadataService(config, tableService, partitionService, userMetadataService,
tagService, helper, registry);
}
/**
* The core initialization service that will handle startup and shutdown of the catalog.
* We do not configure the start and stop methods as bean lifecycle methods to Spring since they are
* called via the thrift init service.
*
* @param pluginManager Plugin manager to use
* @param catalogManager Catalog manager to use
* @param connectorManager Connector manager to use
* @param threadServiceManager Thread service manager to use
* @param applicationContext the application context
*
* @return The initialization service bean
*/
@Bean
public MetacatCoreInitService metacatCoreInitService(final PluginManager pluginManager,
final CatalogManager catalogManager,
final ConnectorManager connectorManager,
final ThreadServiceManager threadServiceManager,
final ApplicationContext applicationContext) {
return new MetacatCoreInitService(
pluginManager, catalogManager, connectorManager,
threadServiceManager, applicationContext);
}
/**
* The initialization service that will handle startup and shutdown of Metacat thrift service.
*
* @param metacatCoreInitService the core init service
* @param metacatThriftService Thrift service to use
*
* @return The initialization service bean
*/
@Bean(initMethod = "start", destroyMethod = "stop")
public MetacatThriftInitService metacatThriftInitService(final MetacatCoreInitService metacatCoreInitService,
final MetacatThriftService metacatThriftService) {
return new MetacatThriftInitService(
metacatThriftService,
metacatCoreInitService
);
}
/**
* Metacat health indicator.
*
* @param metacatCoreInitService the code in it service
* @param metacatThriftInitService the thrift init service
*
* @return the health indicator
*/
@Bean
public MetacatHealthIndicator metacatHealthIndicator(final MetacatCoreInitService metacatCoreInitService,
final MetacatThriftInitService metacatThriftInitService) {
return new MetacatHealthIndicator(
metacatCoreInitService, metacatThriftInitService
);
}
/**
* The catalog traversal service helper.
*
* @param catalogService Catalog service
* @param databaseService Database service
* @param tableService Table service
* @return The catalog traversal service helper bean
*/
@Bean
public CatalogTraversalServiceHelper catalogTraversalServiceHelper(
final CatalogService catalogService,
final DatabaseService databaseService,
final TableService tableService
) {
return new CatalogTraversalServiceHelper(
catalogService,
databaseService,
tableService
);
}
/**
* The catalog traversal bean.
*
* @param config System config
* @param catalogTraversalServiceHelper traversal service helper
* @param registry registry of spectator
* @return The catalog traversal bean
*/
@Bean
public CatalogTraversal catalogTraversal(
final Config config,
final CatalogTraversalServiceHelper catalogTraversalServiceHelper,
final Registry registry
) {
return new CatalogTraversal(
config,
catalogTraversalServiceHelper,
registry
);
}
}
| 59 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/CacheConfig.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.configs;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration for cache.
*
* @author amajumdar
* @since 1.2.0
*/
@Configuration
@ConditionalOnProperty(value = "metacat.cache.enabled", havingValue = "true")
@EnableCaching
public class CacheConfig {
}
| 60 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/CommonServerConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.json.MetacatJsonLocator;
import com.netflix.metacat.common.server.connectors.ConnectorTypeConverter;
import com.netflix.metacat.common.server.converter.ConverterUtil;
import com.netflix.metacat.common.server.converter.DozerJsonTypeConverter;
import com.netflix.metacat.common.server.converter.DozerTypeConverter;
import com.netflix.metacat.common.server.converter.TypeConverterFactory;
import com.netflix.metacat.common.server.events.MetacatApplicationEventMulticaster;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.events.MetacatEventListenerFactory;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.properties.MetacatProperties;
import com.netflix.metacat.common.server.util.DataSourceManager;
import com.netflix.metacat.common.server.util.ThreadServiceManager;
import com.netflix.spectator.api.Registry;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListenerFactory;
/**
* Common configuration for Metacat based on classes found in the common server module.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class CommonServerConfig {
private static final String DEFAULT_TYPE_CONVERTER = "defaultTypeConverter";
/**
* An object mapper bean to use if none already exists.
*
* @return JSON object mapper
*/
@Bean
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper objectMapper() {
return new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.ALWAYS);
}
/**
* Metacat JSON Handler.
*
* @return The JSON handler
*/
@Bean
public MetacatJson metacatJson() {
return new MetacatJsonLocator();
}
/**
* The data source manager to use.
*
* @return The data source manager
*/
@Bean
public DataSourceManager dataSourceManager() {
return DataSourceManager.get();
}
/**
* The event bus abstraction to use.
*
* @param applicationEventMulticaster The asynchronous event publisher
* @param registry registry for spectator
* @return The event bus to use.
*/
@Bean
public MetacatEventBus eventBus(
final MetacatApplicationEventMulticaster applicationEventMulticaster,
final Registry registry
) {
return new MetacatEventBus(applicationEventMulticaster, registry);
}
/**
* The application event multicaster to use.
* @param registry registry for spectator
* @param metacatProperties The metacat properties to get number of executor threads from.
* Likely best to do one more than number of CPUs
* @return The application event multicaster to use.
*/
@Bean
public MetacatApplicationEventMulticaster applicationEventMulticaster(final Registry registry,
final MetacatProperties metacatProperties) {
return new MetacatApplicationEventMulticaster(registry, metacatProperties);
}
/**
* Default event listener factory.
* @return The application event multicaster to use.
*/
@Bean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)
public EventListenerFactory eventListenerFactory() {
return new MetacatEventListenerFactory();
}
/**
* The type converter factory to use.
*
* @param defaultTypeConverter default type converter
* @return The type converter factory
*/
@Bean
public TypeConverterFactory typeConverterFactory(@Qualifier(DEFAULT_TYPE_CONVERTER)
final ConnectorTypeConverter defaultTypeConverter) {
return new TypeConverterFactory(defaultTypeConverter);
}
/**
* The default type converter.
*
* @param config The system configuration
* @return default type converter
*/
@Bean(DEFAULT_TYPE_CONVERTER)
public ConnectorTypeConverter defaultTypeConverter(final Config config) {
try {
return (ConnectorTypeConverter) Class.forName(config.getDefaultTypeConverter()).newInstance();
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* The dozer type converter to use.
*
* @param typeConverterFactory The type converter factory to use
* @return type converter
*/
@Bean
public DozerTypeConverter dozerTypeConverter(final TypeConverterFactory typeConverterFactory) {
return new DozerTypeConverter(typeConverterFactory);
}
/**
* The dozer type converter to JSON format.
*
* @param typeConverterFactory The type converter factory to use
* @return type converter
*/
@Bean
public DozerJsonTypeConverter dozerJsonTypeConverter(final TypeConverterFactory typeConverterFactory) {
return new DozerJsonTypeConverter(typeConverterFactory);
}
/**
* Converter utility bean.
*
* @param dozerTypeConverter The Dozer type converter to use.
* @param dozerJsonTypeConverter The dozer type converter to JSON format.
* @return The converter util instance
*/
@Bean
public ConverterUtil converterUtil(final DozerTypeConverter dozerTypeConverter,
final DozerJsonTypeConverter dozerJsonTypeConverter) {
return new ConverterUtil(dozerTypeConverter, dozerJsonTypeConverter);
}
/**
* Get the ThreadServiceManager.
* @param registry registry for spectator
* @param config System configuration
* @return The thread service manager to use
*/
@Bean
public ThreadServiceManager threadServiceManager(final Registry registry, final Config config) {
return new ThreadServiceManager(registry, config);
}
}
| 61 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/ManagerConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.metacat.common.server.converter.TypeConverterFactory;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.type.TypeManager;
import com.netflix.metacat.common.type.TypeRegistry;
import com.netflix.metacat.main.manager.CatalogManager;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.main.manager.DefaultCatalogManager;
import com.netflix.metacat.main.manager.PluginManager;
import com.netflix.spectator.api.Registry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration for Management beans.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class ManagerConfig {
/**
* Manager of the connectors.
*
* @param config System config
* @return The connector manager instance to use.
*/
@Bean
public ConnectorManager connectorManager(final Config config) {
return new ConnectorManager(config);
}
/**
* Type manager to use.
*
* @return The type registry
*/
@Bean
public TypeManager typeManager() {
// TODO: Get rid of this static instantiation as Spring will manage singleton
return TypeRegistry.getTypeRegistry();
}
/**
* The plugin manager.
*
* @param connectorManager Connector manager to use
* @param typeConverterFactory Type converter factory to use
* @return The plugin manager instance
*/
@Bean
public PluginManager pluginManager(
final ConnectorManager connectorManager,
final TypeConverterFactory typeConverterFactory
) {
return new PluginManager(connectorManager, typeConverterFactory);
}
/**
* Catalog manager.
*
* @param connectorManager The connector manager to use
* @param config The system configuration to use
* @param registry registry for spectator
* @return Configured catalog manager
*/
@Bean
@ConditionalOnMissingBean(CatalogManager.class)
public CatalogManager catalogManager(
final ConnectorManager connectorManager,
final Config config,
final Registry registry
) {
return new DefaultCatalogManager(connectorManager, config, registry);
}
}
| 62 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/SwaggerConfig.java | /*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.server.properties.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Spring configuration for Swagger via SpringFox.
*
* see: https://github.com/springfox/springfox
* @author tgianos
* @since 1.1.0
*/
@Configuration
@ConditionalOnProperty(value = "springfox.documentation.swagger-ui.enabled", havingValue = "true")
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
/**
* Configure Spring Fox.
*
* @param config The configuration
* @return The spring fox docket.
*/
@Bean
public Docket api(final Config config) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(
/**
* public ApiInfo(
String title,
String description,
String version,
String termsOfServiceUrl,
Contact contact,
String license,
String licenseUrl,
Collection<VendorExtension> vendorExtensions)
*/
new ApiInfo(
"Metacat API",
"The set of APIs available in this version of metacat",
"1.1.0", // TODO: Swap out with dynamic from config
null,
new Contact("Netflix, Inc.", "https://jobs.netflix.com/", null),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
Lists.newArrayList()
)
)
.select()
.apis(RequestHandlerSelectors.basePackage("com.netflix.metacat.main.api"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.useDefaultResponseMessages(false);
}
//TODO: Update with more detailed swagger configurations
// see: http://tinyurl.com/glla6vc
}
| 63 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/ApiConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.netflix.metacat.main.api.ApiFilter;
import com.netflix.metacat.main.api.MetacatErrorController;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.Map;
/**
* Spring configuration for the API tier.
*
* @author tgianos
* @since 1.1.0
*/
@Configuration
public class ApiConfig extends WebMvcConfigurerAdapter {
/**
* {@inheritDoc}
* <p>
* Turn off {@literal .} Turn off suffix-based content negotiation. The table name may have extension, e.g. knp,
* , which is a type and will be rejected by spring
*
* @see <a href="https://stackoverflow.com/questions/30793717">Stack Overflow Issue</a>
*/
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
/**
* {@inheritDoc}
* <p>
* Turn off {@literal .} recognition in paths. Needed due to table's name potentially having '.' as character.
*
* @see <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html">SpringDoc</a>
*/
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
/**
* The rest filter registration bean.
*
* @param apiFilter the api filter
* @return The rest filter
*/
@Bean
public FilterRegistrationBean metacatApiFilter(final ApiFilter apiFilter) {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(apiFilter);
registrationBean.addUrlPatterns("/mds/*");
return registrationBean;
}
/**
* The API filter.
*
* @return the API filter.
*/
@Bean
@ConditionalOnMissingBean(ApiFilter.class)
public ApiFilter apiFilter() {
return new ApiFilter();
}
/**
* Override the default error attributes for backwards compatibility with older clients.
*
* @return New set of error attributes with 'message' copied into 'error'
*/
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
/**
* {@inheritDoc}
*/
@Override
public Map<String, Object> getErrorAttributes(final WebRequest webRequest,
final ErrorAttributeOptions options) {
final Map<String, Object> errorAttributes
= super.getErrorAttributes(webRequest, options);
errorAttributes.put("error", errorAttributes.get("message"));
return errorAttributes;
}
};
}
/**
* Returns the error controller.
* @param errorAttributes error attributes
* @param serverProperties server properties
* @return error controller
*/
@Bean
public MetacatErrorController metacatErrorController(final ErrorAttributes errorAttributes,
final ServerProperties serverProperties) {
return new MetacatErrorController(errorAttributes, serverProperties.getError());
}
}
| 64 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/SNSNotificationsConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.main.services.notifications.sns.SNSNotificationMetric;
import com.netflix.metacat.main.services.notifications.sns.SNSNotificationServiceImpl;
import com.netflix.metacat.main.services.notifications.sns.SNSNotificationServiceUtil;
import com.netflix.spectator.api.Registry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration for SNS Notifications.
*
* @author tgianos
* @since 1.1.0
*/
@Slf4j
@Configuration
@ConditionalOnProperty(value = "metacat.notifications.sns.enabled", havingValue = "true")
public class SNSNotificationsConfig {
/**
* If SNS notifications are desired and no existing client has been created elsewhere
* in the application create a default client here.
*
* @return The configured SNS client
*/
//TODO: See what spring-cloud-aws would provide automatically...
@Bean
@ConditionalOnMissingBean(AmazonSNS.class)
public AmazonSNS amazonSNS() {
return new AmazonSNSClient(DefaultAWSCredentialsProviderChain.getInstance());
}
/**
* SNS Notification Publisher.
*
* @param amazonSNS The SNS client to use
* @param config The system configuration abstraction to use
* @param objectMapper The object mapper to use
* @param snsNotificationMetric The sns notification metric
* @param snsNotificationServiceUtil The SNS notification util
* @return Configured Notification Service bean
*/
@Bean
public SNSNotificationServiceImpl snsNotificationService(
final AmazonSNS amazonSNS,
final Config config,
final ObjectMapper objectMapper,
final SNSNotificationMetric snsNotificationMetric,
final SNSNotificationServiceUtil snsNotificationServiceUtil
) {
final String tableArn = config.getSnsTopicTableArn();
if (StringUtils.isEmpty(tableArn)) {
throw new IllegalStateException(
"SNS Notifications are enabled but no table ARN provided. Unable to configure."
);
}
final String partitionArn = config.getSnsTopicPartitionArn();
if (StringUtils.isEmpty(partitionArn)) {
throw new IllegalStateException(
"SNS Notifications are enabled but no partition ARN provided. Unable to configure."
);
}
log.info("SNS notifications are enabled. Creating SNSNotificationServiceImpl bean.");
return new SNSNotificationServiceImpl(amazonSNS,
tableArn, partitionArn, objectMapper, config, snsNotificationMetric, snsNotificationServiceUtil);
}
/**
* SNS Notification Service Util.
*
* @param userMetadataService user metadata service
* @return SNSNotificationServiceUtil
*/
@Bean
public SNSNotificationServiceUtil snsNotificationServiceUtil(
final UserMetadataService userMetadataService
) {
return new SNSNotificationServiceUtil(userMetadataService);
}
/**
* SNS Notification Metric.
*
* @param registry registry for spectator
* @return Notification Metric bean
*/
@Bean
public SNSNotificationMetric snsNotificationMetric(
final Registry registry
) {
return new SNSNotificationMetric(registry);
}
}
| 65 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/ElasticSearchConfig.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.configs;
import com.google.common.base.Splitter;
import com.netflix.metacat.common.json.MetacatJson;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.main.services.CatalogService;
import com.netflix.metacat.main.services.DatabaseService;
import com.netflix.metacat.main.services.PartitionService;
import com.netflix.metacat.main.services.TableService;
import com.netflix.metacat.main.services.search.ElasticSearchCatalogTraversalAction;
import com.netflix.metacat.main.services.search.ElasticSearchEventHandlers;
import com.netflix.metacat.main.services.search.ElasticSearchRefresh;
import com.netflix.metacat.main.services.search.ElasticSearchUtil;
import com.netflix.metacat.main.services.search.ElasticSearchUtilImpl;
import com.netflix.spectator.api.Registry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Configuration for ElasticSearch which triggers when metacat.elasticsearch.enabled is true.
*
* @author tgianos
* @author zhenl
* @since 1.1.0
*/
@Slf4j
@Configuration
@ConditionalOnProperty(value = "metacat.elasticsearch.enabled", havingValue = "true")
public class ElasticSearchConfig {
/**
* The ElasticSearch client.
*
* @param config System config
* @return Configured client or error
*/
@Bean
@ConditionalOnMissingBean(Client.class)
public Client elasticSearchClient(final Config config) {
final String clusterName = config.getElasticSearchClusterName();
if (StringUtils.isBlank(clusterName)) {
throw new IllegalStateException("No cluster name set. Unable to continue");
}
final Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", true) //to dynamically add new hosts and remove old ones
.put("transport.tcp.connect_timeout", "60s")
.build();
final TransportClient client = new PreBuiltTransportClient(settings);
// Add the transport address if exists
final String clusterNodesStr = config.getElasticSearchClusterNodes();
if (StringUtils.isNotBlank(clusterNodesStr)) {
final int port = config.getElasticSearchClusterPort();
final Iterable<String> clusterNodes = Splitter.on(',').split(clusterNodesStr);
clusterNodes.
forEach(
clusterNode -> {
try {
client.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(clusterNode), port)
);
} catch (UnknownHostException exception) {
log.error("Skipping unknown host {}", clusterNode);
}
}
);
}
if (client.transportAddresses().isEmpty()) {
throw new IllegalStateException("No Elasticsearch cluster nodes added. Unable to create client.");
}
return client;
}
/**
* ElasticSearch utility wrapper.
*
* @param client The configured ElasticSearch client
* @param config System config
* @param metacatJson JSON utilities
* @param registry spectator registry
* @return The ElasticSearch utility instance
*/
@Bean
public ElasticSearchUtil elasticSearchUtil(
final Client client,
final Config config,
final MetacatJson metacatJson,
final Registry registry
) {
return new ElasticSearchUtilImpl(client, config, metacatJson, registry);
}
/**
* Event handler instance to publish event payloads to ElasticSearch.
*
* @param elasticSearchUtil The client wrapper utility to use
* @param registry registry of spectator
* @param config System config
* @return The event handler instance
*/
@Bean
public ElasticSearchEventHandlers elasticSearchEventHandlers(
final ElasticSearchUtil elasticSearchUtil,
final Registry registry,
final Config config
) {
return new ElasticSearchEventHandlers(elasticSearchUtil, registry, config);
}
/**
* The refresher of ElasticSearch.
*
* @param config System config
* @param eventBus Event bus
* @param catalogService Catalog service
* @param databaseService Database service
* @param tableService Table service
* @param partitionService Partition service
* @param userMetadataService User metadata service
* @param tagService Tag service
* @param elasticSearchUtil ElasticSearch client wrapper
* @param registry registry of spectator
* @return The refresh bean
*/
@Bean
public ElasticSearchRefresh elasticSearchRefresh(
final Config config,
final MetacatEventBus eventBus,
final CatalogService catalogService,
final DatabaseService databaseService,
final TableService tableService,
final PartitionService partitionService,
final UserMetadataService userMetadataService,
final TagService tagService,
final ElasticSearchUtil elasticSearchUtil,
final Registry registry
) {
return new ElasticSearchRefresh(
config,
eventBus,
catalogService,
databaseService,
tableService,
partitionService,
userMetadataService,
tagService,
elasticSearchUtil,
registry
);
}
/**
* Traversal action implementation for ElasticSearch refresh.
*
* @param config System config
* @param eventBus Event bus
* @param databaseService Database service
* @param tableService Table service
* @param userMetadataService User metadata service
* @param tagService Tag service
* @param elasticSearchUtil ElasticSearch client wrapper
* @param registry registry of spectator
* @return The refresh bean
*/
@Bean
public ElasticSearchCatalogTraversalAction elasticSearchCatalogTraversalAction(
final Config config,
final MetacatEventBus eventBus,
final DatabaseService databaseService,
final TableService tableService,
final UserMetadataService userMetadataService,
final TagService tagService,
final ElasticSearchUtil elasticSearchUtil,
final Registry registry
) {
return new ElasticSearchCatalogTraversalAction(
config,
eventBus,
databaseService,
tableService,
userMetadataService,
tagService,
elasticSearchUtil,
registry
);
}
}
| 66 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/configs/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Spring configuration classes.
*
* @author tgianos
* @since 1.1.0
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.main.configs;
import javax.annotation.ParametersAreNonnullByDefault;
| 67 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/RequestWrapper.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.exception.MetacatAlreadyExistsException;
import com.netflix.metacat.common.exception.MetacatBadRequestException;
import com.netflix.metacat.common.exception.MetacatException;
import com.netflix.metacat.common.exception.MetacatNotFoundException;
import com.netflix.metacat.common.exception.MetacatNotSupportedException;
import com.netflix.metacat.common.exception.MetacatPreconditionFailedException;
import com.netflix.metacat.common.exception.MetacatTooManyRequestsException;
import com.netflix.metacat.common.exception.MetacatUserMetadataException;
import com.netflix.metacat.common.server.api.traffic_control.RequestGateway;
import com.netflix.metacat.common.server.connectors.exception.ConnectorException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.InvalidMetaException;
import com.netflix.metacat.common.server.connectors.exception.NotFoundException;
import com.netflix.metacat.common.server.connectors.exception.PartitionAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.TableAlreadyExistsException;
import com.netflix.metacat.common.server.connectors.exception.TablePreconditionFailedException;
import com.netflix.metacat.common.server.monitoring.Metrics;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.AliasService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataServiceException;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* Request wrapper.
*
* @author amajumdar
* @since 0.1.50
*/
@Slf4j
@Component
public final class RequestWrapper {
private final Registry registry;
private final Config config;
private final AliasService aliasService;
private final RequestGateway requestGateway;
//Metrics
private final Id requestCounterId;
private final Id requestFailureCounterId;
private final Id requestTimerId;
/**
* Wrapper class for processing the request.
*
* @param registry registry
* @param config Config
* @param aliasService AliasService
* @param requestGateway RequestGateway
*/
@Autowired
public RequestWrapper(@NotNull @NonNull final Registry registry,
@NotNull @NonNull final Config config,
@NotNull @NonNull final AliasService aliasService,
@NotNull @NonNull final RequestGateway requestGateway) {
this.registry = registry;
this.config = config;
this.aliasService = aliasService;
this.requestGateway = requestGateway;
requestCounterId = registry.createId(Metrics.CounterRequestCount.getMetricName());
requestFailureCounterId = registry.createId(Metrics.CounterRequestFailureCount.getMetricName());
requestTimerId = registry.createId(Metrics.TimerRequest.getMetricName());
}
/**
* Creates the qualified name.
*
* @param nameSupplier supplier
* @return name
*/
public QualifiedName qualifyName(final Supplier<QualifiedName> nameSupplier) {
try {
final QualifiedName name = nameSupplier.get();
if (config.isTableAliasEnabled() && name.getType() == QualifiedName.Type.TABLE) {
return aliasService.getTableName(name);
}
return name;
} catch (Exception e) {
log.error("Invalid qualified name", e);
throw new MetacatBadRequestException(e.getMessage());
}
}
/**
* Request wrapper to to process request.
*
* @param name name
* @param resourceRequestName request name
* @param supplier supplier
* @param <R> response
* @return response of supplier
*/
public <R> R processRequest(
final QualifiedName name,
final String resourceRequestName,
final Supplier<R> supplier) {
return processRequest(name, resourceRequestName, Collections.emptyMap(), supplier);
}
/**
* Request wrapper to to process request.
*
* @param name name
* @param resourceRequestName request name
* @param requestTags tags that needs to be added to the registry
* @param supplier supplier
* @param <R> response
* @return response of supplier
*/
public <R> R processRequest(
final QualifiedName name,
final String resourceRequestName,
final Map<String, String> requestTags,
final Supplier<R> supplier) {
final long start = registry.clock().wallTime();
final Map<String, String> tags = new HashMap<>(name.parts());
if (requestTags != null) {
tags.putAll(requestTags);
}
tags.put("request", resourceRequestName);
tags.put("scheme", MetacatContextManager.getContext().getScheme());
registry.counter(requestCounterId.withTags(tags)).increment();
try {
requestGateway.validateRequest(resourceRequestName, name);
MetacatContextManager.getContext().setRequestName(resourceRequestName);
log.info("### Calling method: {} for {}", resourceRequestName, name);
return supplier.get();
} catch (UnsupportedOperationException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatNotSupportedException("Catalog does not support the operation. " + e.getMessage());
} catch (DatabaseAlreadyExistsException | TableAlreadyExistsException | PartitionAlreadyExistsException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatAlreadyExistsException(e.getMessage());
} catch (NotFoundException | MetacatNotFoundException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatNotFoundException(
String.format("Unable to locate for %s. Details: %s", name, e.getMessage()));
} catch (InvalidMetaException | IllegalArgumentException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatBadRequestException(
String.format("%s.%s", e.getMessage(), e.getCause() == null ? "" : e.getCause().getMessage()));
} catch (TablePreconditionFailedException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatPreconditionFailedException(
String.format("%s.%s", e.getMessage(), e.getCause() == null ? "" : e.getCause().getMessage()));
} catch (ConnectorException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
final String message = String.format("%s.%s -- %s failed for %s", e.getMessage(),
e.getCause() == null ? "" : e.getCause().getMessage(), resourceRequestName, name);
log.error(message, e);
for (Throwable ex : Throwables.getCausalChain(e)) {
if (ex.getMessage().contains("too many connections")
|| ex.getMessage().contains("Timeout: Pool empty")) {
throw new MetacatTooManyRequestsException(ex.getMessage());
}
}
throw new MetacatException(message, e);
} catch (UserMetadataServiceException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
final String message = String.format("%s.%s -- %s usermetadata operation failed for %s", e.getMessage(),
e.getCause() == null ? "" : e.getCause().getMessage(), resourceRequestName, name);
throw new MetacatUserMetadataException(message);
} catch (Exception e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
final String message = String.format("%s.%s -- %s failed for %s", e.getMessage(),
e.getCause() == null ? "" : e.getCause().getMessage(), resourceRequestName, name);
log.error(message, e);
if (e instanceof MetacatException) {
throw e;
} else {
throw new MetacatException(message, e);
}
} finally {
final long duration = registry.clock().wallTime() - start;
log.info("### Time taken to complete {} for {} is {} ms", resourceRequestName, name, duration);
tryAddTableTypeTag(tags, name);
this.registry.timer(requestTimerId.withTags(tags)).record(duration, TimeUnit.MILLISECONDS);
}
}
private static void tryAddTableTypeTag(final Map<String, String> tags, final QualifiedName qualifiedName) {
final MetacatRequestContext context = MetacatContextManager.getContext();
final String tableType = context.getTableType(qualifiedName);
if (!StringUtils.isBlank(tableType)) {
tags.put("tableType", tableType.toLowerCase());
}
}
/**
* Simple request wrapper to process request.
*
* @param resourceRequestName request name
* @param supplier supplier
* @param <R> response
* @return response of the supplier
*/
public <R> R processRequest(
final String resourceRequestName,
final Supplier<R> supplier) {
final long start = registry.clock().wallTime();
final Map<String, String> tags = Maps.newHashMap();
tags.put("request", resourceRequestName);
registry.counter(requestCounterId.withTags(tags)).increment();
try {
MetacatContextManager.getContext().setRequestName(resourceRequestName);
log.info("### Calling method: {}", resourceRequestName);
return supplier.get();
} catch (UnsupportedOperationException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatNotSupportedException("Catalog does not support the operation. " + e.getMessage());
} catch (IllegalArgumentException e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
log.error(e.getMessage(), e);
throw new MetacatBadRequestException(String.format("%s.%s", e.getMessage(),
e.getCause() == null ? "" : e.getCause().getMessage()));
} catch (Exception e) {
collectRequestExceptionMetrics(tags, e.getClass().getSimpleName());
final String message = String
.format("%s.%s -- %s failed.",
e.getMessage(), e.getCause() == null ? "" : e.getCause().getMessage(),
resourceRequestName);
log.error(message, e);
if (e instanceof MetacatException) {
throw e;
} else {
throw new MetacatException(message, e);
}
} finally {
final long duration = registry.clock().wallTime() - start;
log.info("### Time taken to complete {} is {} ms", resourceRequestName,
duration);
this.registry.timer(requestTimerId.withTags(tags)).record(duration, TimeUnit.MILLISECONDS);
}
}
private void collectRequestExceptionMetrics(final Map<String, String> tags, final String exceptionName) {
tags.put("exception", exceptionName);
registry.counter(requestFailureCounterId.withTags(tags)).increment();
}
}
| 68 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/MetacatErrorController.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;
/**
* Error controller.
*
* @author amajumdar
* @since 1.2.0
*/
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MetacatErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
/**
* Default constructor.
* @param errorAttributes error attributes
* @param errorProperties error properties
*/
public MetacatErrorController(final ErrorAttributes errorAttributes, final ErrorProperties errorProperties) {
super(errorAttributes, Collections.<ErrorViewResolver>emptyList());
this.errorProperties = errorProperties;
}
/**
* Mapping for error handling.
* @param request http request
* @return error response
*/
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(final HttpServletRequest request) {
final Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request));
final HttpStatus status = getStatus(request);
return new ResponseEntity<>(body, status);
}
private ErrorAttributeOptions getErrorAttributeOptions(final HttpServletRequest request) {
ErrorAttributeOptions options = ErrorAttributeOptions.defaults();
if (includeStackTrace(request)) {
options = options.including(ErrorAttributeOptions.Include.STACK_TRACE);
}
if (includeMessage(request)) {
options = options.including(ErrorAttributeOptions.Include.MESSAGE);
}
return options;
}
@SuppressWarnings("deprecation")
private boolean includeStackTrace(final HttpServletRequest request) {
switch (this.errorProperties.getIncludeStacktrace()) {
case ALWAYS:
return true;
case ON_PARAM:
return getBooleanParameter(request, "trace");
default:
return false;
}
}
private boolean includeMessage(final HttpServletRequest request) {
switch (this.errorProperties.getIncludeMessage()) {
case ALWAYS:
return true;
case ON_PARAM:
return getBooleanParameter(request, "message");
default:
return false;
}
}
}
| 69 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/IndexController.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* Default controller.
*/
@RestController
@RequestMapping("/mds")
public class IndexController {
/**
* Index API.
*/
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public void index() {
// TODO: Great place for hypermedia
}
}
| 70 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/ExceptionMapper.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api;
import com.netflix.metacat.common.exception.MetacatAlreadyExistsException;
import com.netflix.metacat.common.exception.MetacatBadRequestException;
import com.netflix.metacat.common.exception.MetacatException;
import com.netflix.metacat.common.exception.MetacatNotFoundException;
import com.netflix.metacat.common.exception.MetacatNotSupportedException;
import com.netflix.metacat.common.exception.MetacatPreconditionFailedException;
import com.netflix.metacat.common.exception.MetacatUserMetadataException;
import com.netflix.metacat.common.exception.MetacatTooManyRequestsException;
import com.netflix.metacat.common.exception.MetacatUnAuthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Exception mapper for converting exceptions in application to web status error messages.
*
* @author tgianos
* @since 1.1.0
*/
@Slf4j
@ControllerAdvice
public class ExceptionMapper {
/**
* Handle Metacat Exceptions.
*
* @param response The HTTP response
* @param e The exception to handle
* @throws IOException on error in sending error
*/
@ExceptionHandler(MetacatException.class)
public void handleMetacatException(
final HttpServletResponse response,
final MetacatException e
) throws IOException {
final int status;
boolean logErrorLevel = false;
if (e instanceof MetacatAlreadyExistsException) {
status = HttpStatus.CONFLICT.value();
} else if (e instanceof MetacatBadRequestException) {
status = HttpStatus.BAD_REQUEST.value();
} else if (e instanceof MetacatPreconditionFailedException) {
status = HttpStatus.PRECONDITION_FAILED.value();
} else if (e instanceof MetacatNotFoundException) {
status = HttpStatus.NOT_FOUND.value();
} else if (e instanceof MetacatNotSupportedException) {
logErrorLevel = true;
status = HttpStatus.NOT_IMPLEMENTED.value();
} else if (e instanceof MetacatUserMetadataException) {
// TODO: This makes no sense
status = HttpStatus.SEE_OTHER.value();
} else if (e instanceof MetacatTooManyRequestsException) {
status = HttpStatus.TOO_MANY_REQUESTS.value();
} else if (e instanceof MetacatUnAuthorizedException) {
status = HttpStatus.FORBIDDEN.value();
} else {
logErrorLevel = true;
status = HttpStatus.INTERNAL_SERVER_ERROR.value();
}
if (logErrorLevel) {
log.error(e.getLocalizedMessage(), e);
} else {
log.warn(e.getLocalizedMessage(), e);
}
response.sendError(status, e.getLocalizedMessage());
}
}
| 71 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/ApiFilter.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.api;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* REST Interceptor.
*
* @author amajumdar
* @author tgianos
* @since 1.1.0
*/
@Slf4j
public class ApiFilter implements Filter {
/**
* {@inheritDoc}
*/
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
/**
* {@inheritDoc}
*/
@Override
public void doFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws IOException, ServletException {
preFilter(request, response, chain);
try {
chain.doFilter(request, response);
} finally {
postFilter(request, response, chain);
}
}
protected void preFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws ServletException {
// Pre-processing
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Expected an HttpServletRequest but didn't get one");
}
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String userName = httpServletRequest.getHeader(MetacatRequestContext.HEADER_KEY_USER_NAME);
if (userName == null) {
userName = "metacat";
}
final String clientAppName = httpServletRequest.getHeader(MetacatRequestContext.HEADER_KEY_CLIENT_APP_NAME);
final String clientId = httpServletRequest.getHeader("X-Forwarded-For");
final String jobId = httpServletRequest.getHeader(MetacatRequestContext.HEADER_KEY_JOB_ID);
final String dataTypeContext = httpServletRequest.getHeader(MetacatRequestContext.HEADER_KEY_DATA_TYPE_CONTEXT);
final MetacatRequestContext context = buildRequestContext(
userName, clientAppName, clientId, jobId, dataTypeContext,
httpServletRequest.getScheme(),
httpServletRequest.getRequestURI(),
httpServletRequest
);
MetacatContextManager.setContext(context);
log.info(context.toString());
}
protected MetacatRequestContext buildRequestContext(final String userName,
final String clientAppName,
final String clientId,
final String jobId,
final String dataTypeContext,
final String scheme,
final String requestUri,
final HttpServletRequest httpServletRequest) {
return MetacatRequestContext.builder()
.userName(userName)
.clientAppName(clientAppName)
.clientId(clientId)
.jobId(jobId)
.dataTypeContext(dataTypeContext)
.scheme(scheme)
.apiUri(requestUri)
.build();
}
protected void postFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain) throws ServletException {
MetacatContextManager.removeContext();
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
}
}
| 72 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/package-info.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* This package includes REST API resources.
*
* @author amajumdar
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.main.api;
import javax.annotation.ParametersAreNonnullByDefault;
| 73 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/PartitionController.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api.v1;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.GetPartitionsRequestDto;
import com.netflix.metacat.common.dto.Pageable;
import com.netflix.metacat.common.dto.PartitionDto;
import com.netflix.metacat.common.dto.PartitionsSaveRequestDto;
import com.netflix.metacat.common.dto.PartitionsSaveResponseDto;
import com.netflix.metacat.common.dto.Sort;
import com.netflix.metacat.common.dto.SortOrder;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.server.api.v1.PartitionV1;
import com.netflix.metacat.main.api.RequestWrapper;
import com.netflix.metacat.main.services.MViewService;
import com.netflix.metacat.main.services.PartitionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Nullable;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.List;
/**
* Partition V1 API implementation.
*
* @author amajumdar
* @author zhenl
*/
@RestController
@RequestMapping(
path = "/mds/v1/partition",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Api(value = "PartitionV1",
description = "Federated partition metadata operations",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PartitionController implements PartitionV1 {
private final MetacatController v1;
private final MViewService mViewService;
private final PartitionService partitionService;
private final RequestWrapper requestWrapper;
/**
* Delete named partitions from a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param partitionIds lis of partition names
*/
@RequestMapping(
method = RequestMethod.DELETE,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
value = "Delete named partitions from a table",
notes = "List of partitions names of the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were deleted successfully"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
),
@ApiResponse(
code = HttpURLConnection.HTTP_BAD_REQUEST,
message = "The list of partitionNames is not present"
)
}
)
@Override
public void deletePartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "partitionId of the partitions to be deleted from this table", required = true)
@RequestBody final List<String> partitionIds
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
this.requestWrapper.processRequest(
name,
"deleteTablePartition",
() -> {
if (partitionIds.isEmpty()) {
throw new IllegalArgumentException("partitionIds are required");
}
this.partitionService.delete(name, partitionIds);
return null;
}
);
}
/**
* Delete partitions for the given view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName metacat view name
* @param partitionIds list of partition names
*/
@RequestMapping(
method = RequestMethod.DELETE,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
value = "Delete partitions for the given view",
notes = "Delete partitions for the given view"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were deleted successfully"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
),
@ApiResponse(
code = HttpURLConnection.HTTP_BAD_REQUEST,
message = "The list of partitionNames is not present"
)
}
)
public void deletePartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "partitionId of the partitions to be deleted from this table", required = true)
@RequestBody final List<String> partitionIds
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
this.requestWrapper.processRequest(
name,
"deleteMViewPartition",
() -> {
if (partitionIds.isEmpty()) {
throw new IllegalArgumentException("partitionIds are required");
}
this.mViewService.deletePartitions(name, partitionIds);
return null;
}
);
}
/**
* Return list of partitions for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param includeUserMetadata whether to include user metadata for every partition in the list
* @return list of partitions for a table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partitions for a table",
notes = "List of partitions for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public List<PartitionDto> getPartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "false") final boolean includeUserMetadata
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getPartitions",
Collections.singletonMap("filterPassed", StringUtils.isEmpty(filter) ? "false" : "true"),
() -> this.partitionService.list(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
includeUserMetadata,
includeUserMetadata,
new GetPartitionsRequestDto(filter, null, false, false)
)
);
}
/**
* Return list of partitions for a metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param includeUserMetadata whether to include user metadata for every partition in the list
* @return list of partitions for a metacat view
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partitions for a metacat view",
notes = "List of partitions for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<PartitionDto> getPartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "false") final boolean includeUserMetadata
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getPartitions",
Collections.singletonMap("filterPassed", StringUtils.isEmpty(filter) ? "false" : "true"),
() -> this.mViewService.listPartitions(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
includeUserMetadata,
new GetPartitionsRequestDto(filter, null, false, true)
)
);
}
/**
* Return list of partitions for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param includeUserMetadata whether to include user metadata for every partition in the list
* @param getPartitionsRequestDto request
* @return list of partitions for a table
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partitions for a table",
notes = "List of partitions for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were retrieved"
),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public List<PartitionDto> getPartitionsForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "false") final boolean includeUserMetadata,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this.getPartitions(
catalogName,
databaseName,
tableName,
sortBy,
sortOrder,
offset,
limit,
includeUserMetadata,
getPartitionsRequestDto
);
}
/**
* Return list of partitions for a view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param includeUserMetadata whether to include user metadata for every partition in the list
* @param getPartitionsRequestDto request
* @return list of partitions for a view
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partitions for a metacat view",
notes = "List of partitions for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<PartitionDto> getPartitionsForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "false") final boolean includeUserMetadata,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this.getPartitions(
catalogName,
databaseName,
tableName,
viewName,
sortBy,
sortOrder,
offset,
limit,
includeUserMetadata,
getPartitionsRequestDto
);
}
/**
* Return list of partition names for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @return list of partition names for a table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/keys"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition keys for a table",
notes = "List of partition keys for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions keys were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public List<String> getPartitionKeys(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit
) {
return this._getPartitionKeys(
catalogName,
databaseName,
tableName,
sortBy,
sortOrder,
offset,
limit,
new GetPartitionsRequestDto(filter, null, false, false)
);
}
/**
* Return list of partition names for a view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @return list of partition names for a view
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/keys"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition keys for a metacat view",
notes = "List of partition keys for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions keys were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<String> getPartitionKeys(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit
) {
return this._getMViewPartitionKeys(
catalogName,
databaseName,
tableName,
viewName,
sortBy,
sortOrder,
offset,
limit,
new GetPartitionsRequestDto(filter, null, false, true)
);
}
/**
* Return list of partition names for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param getPartitionsRequestDto request
* @return list of partition names for a table
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/keys-request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition keys for a table",
notes = "List of partition keys for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions keys were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public List<String> getPartitionKeysForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this._getPartitionKeys(
catalogName,
databaseName,
tableName,
sortBy,
sortOrder,
offset,
limit,
getPartitionsRequestDto
);
}
/**
* Return list of partition names for a view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param getPartitionsRequestDto request
* @return list of partition names for a view
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/keys-request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition keys for a metacat view",
notes = "List of partition keys for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions keys were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<String> getPartitionKeysForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this._getMViewPartitionKeys(
catalogName,
databaseName,
tableName,
viewName,
sortBy,
sortOrder,
offset,
limit,
getPartitionsRequestDto
);
}
/**
* Return list of partition uris for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @return list of partition uris for a table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/uris"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition uris for a table",
notes = "List of partition uris for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions uris were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public List<String> getPartitionUris(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit
) {
return this._getPartitionUris(
catalogName,
databaseName,
tableName,
sortBy,
sortOrder,
offset,
limit,
new GetPartitionsRequestDto(filter, null, false, false)
);
}
/**
* Return list of partition uris for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param filter filter expression
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @return list of partition uris for a table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/uris"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition uris for a metacat view",
notes = "List of partition uris for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions uris were retrieved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<String> getPartitionUris(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(name = "filter", required = false) final String filter,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit
) {
return this._getMViewPartitionUris(
catalogName,
databaseName,
tableName,
viewName,
sortBy,
sortOrder,
offset,
limit,
new GetPartitionsRequestDto(filter, null, false, true)
);
}
/**
* Return list of partition uris for a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param getPartitionsRequestDto request
* @return list of partition uris for a table
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/uris-request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition uris for a table",
notes = "List of partition uris for the given table name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions uris were retrieved"
),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public List<String> getPartitionUrisForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this._getPartitionUris(
catalogName,
databaseName,
tableName,
sortBy,
sortOrder,
offset,
limit,
getPartitionsRequestDto
);
}
/**
* Return list of partition uris for a view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param sortBy sort by this name
* @param sortOrder sort order to use
* @param offset offset of the list
* @param limit size of the list
* @param getPartitionsRequestDto request
* @return list of partition uris for a view
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/uris-request",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "List of partition uris for a metacat view",
notes = "List of partition uris for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partitions uris were retrieved"
),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public List<String> getPartitionUrisForRequest(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Sort the partition list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the partition list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "Request containing the filter expression for the partitions")
@Nullable @RequestBody(required = false) final GetPartitionsRequestDto getPartitionsRequestDto
) {
return this._getMViewPartitionUris(
catalogName,
databaseName,
tableName,
viewName,
sortBy,
sortOrder,
offset,
limit,
getPartitionsRequestDto
);
}
/**
* Add/update partitions to the given table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param partitionsSaveRequestDto partition request containing the list of partitions to be added/updated
* @return Response with the number of partitions added/updated
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 5,
value = "Add/update partitions to the given table",
notes = "Add/update partitions to the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The partitions were successfully saved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public PartitionsSaveResponseDto savePartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Request containing the list of partitions", required = true)
@RequestBody final PartitionsSaveRequestDto partitionsSaveRequestDto
) {
final QualifiedName name = QualifiedName.ofTable(catalogName, databaseName, tableName);
return this.requestWrapper.processRequest(
name,
"saveTablePartition",
() -> {
final PartitionsSaveResponseDto result;
if (partitionsSaveRequestDto.getPartitions() == null
|| partitionsSaveRequestDto.getPartitions().isEmpty()) {
result = new PartitionsSaveResponseDto();
} else {
result = this.partitionService.save(name, partitionsSaveRequestDto);
// This metadata is actually for the table, if it is present update that
if (partitionsSaveRequestDto.getDefinitionMetadata() != null
|| partitionsSaveRequestDto.getDataMetadata() != null) {
final TableDto dto = new TableDto();
dto.setName(name);
dto.setDefinitionMetadata(partitionsSaveRequestDto.getDefinitionMetadata());
dto.setDataMetadata(partitionsSaveRequestDto.getDataMetadata());
this.v1.updateTable(catalogName, databaseName, tableName, dto);
}
}
return result;
}
);
}
/**
* Add/update partitions to the given metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param partitionsSaveRequestDto partition request containing the list of partitions to be added/updated
* @return Response with the number of partitions added/updated
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 5,
value = "Add/update partitions to the given table",
notes = "Add/update partitions to the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The partitions were successfully saved"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public PartitionsSaveResponseDto savePartitions(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "Request containing the list of partitions", required = true)
@RequestBody final PartitionsSaveRequestDto partitionsSaveRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"saveMViewPartition",
() -> {
final PartitionsSaveResponseDto result;
if (partitionsSaveRequestDto.getPartitions() == null
|| partitionsSaveRequestDto.getPartitions().isEmpty()) {
result = new PartitionsSaveResponseDto();
} else {
result = mViewService.savePartitions(name, partitionsSaveRequestDto, true);
// This metadata is actually for the view, if it is present update that
if (partitionsSaveRequestDto.getDefinitionMetadata() != null
|| partitionsSaveRequestDto.getDataMetadata() != null) {
final TableDto dto = new TableDto();
dto.setName(name);
dto.setDefinitionMetadata(partitionsSaveRequestDto.getDefinitionMetadata());
dto.setDataMetadata(partitionsSaveRequestDto.getDataMetadata());
this.v1.updateMView(catalogName, databaseName, tableName, viewName, dto);
}
}
return result;
}
);
}
/**
* Get the partition count for the given table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @return partition count for the given table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/count"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 5,
value = "Partition count for the given table",
notes = "Partition count for the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partition count was returned successfully"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public Integer getPartitionCount(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getPartitionCount",
() -> this.partitionService.count(name)
);
}
/**
* Get the partition count for the given metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @return partition count for the given view
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}/count"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 5,
value = "Partition count for the given table",
notes = "Partition count for the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The partition count was returned successfully"
),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public Integer getPartitionCount(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the view", required = true)
@PathVariable("view-name") final String viewName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getPartitionCount",
() -> this.mViewService.partitionCount(name)
);
}
private List<PartitionDto> getPartitions(
final String catalogName,
final String databaseName,
final String tableName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
final boolean includeUserMetadata,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getPartitions",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> partitionService.list(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
includeUserMetadata,
includeUserMetadata,
getPartitionsRequestDto
)
);
}
private List<PartitionDto> getPartitions(
final String catalogName,
final String databaseName,
final String tableName,
final String viewName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
final boolean includeUserMetadata,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getPartitions",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> this.mViewService.listPartitions(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
includeUserMetadata,
getPartitionsRequestDto
)
);
}
@SuppressWarnings("checkstyle:methodname")
private List<String> _getPartitionUris(
final String catalogName,
final String databaseName,
final String tableName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getPartitionUris",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> this.partitionService.getPartitionUris(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
getPartitionsRequestDto
)
);
}
@SuppressWarnings("checkstyle:methodname")
private List<String> _getMViewPartitionKeys(
final String catalogName,
final String databaseName,
final String tableName,
final String viewName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getMViewPartitionKeys",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> this.mViewService.getPartitionKeys(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
getPartitionsRequestDto
)
);
}
@SuppressWarnings("checkstyle:methodname")
private List<String> _getMViewPartitionUris(
final String catalogName,
final String databaseName,
final String tableName,
final String viewName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getMViewPartitionUris",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> this.mViewService.getPartitionUris(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
getPartitionsRequestDto
)
);
}
@SuppressWarnings("checkstyle:methodname")
private List<String> _getPartitionKeys(
final String catalogName,
final String databaseName,
final String tableName,
@Nullable final String sortBy,
@Nullable final SortOrder sortOrder,
@Nullable final Integer offset,
@Nullable final Integer limit,
@Nullable final GetPartitionsRequestDto getPartitionsRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getPartitionKeys",
Collections.singletonMap("filterPassed",
getPartitionsRequestDto == null || StringUtils.isEmpty(
getPartitionsRequestDto.getFilter()) ? "false" : "true"),
() -> partitionService.getPartitionKeys(
name,
new Sort(sortBy, sortOrder),
new Pageable(limit, offset),
getPartitionsRequestDto
)
);
}
}
| 74 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/TagController.java | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.api.v1;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.dto.TagCreateRequestDto;
import com.netflix.metacat.common.dto.TagRemoveRequestDto;
import com.netflix.metacat.common.exception.MetacatNotFoundException;
import com.netflix.metacat.common.server.connectors.exception.DatabaseNotFoundException;
import com.netflix.metacat.common.server.connectors.exception.TableNotFoundException;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.events.MetacatUpdateDatabasePostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateTablePostEvent;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.metacat.main.api.RequestWrapper;
import com.netflix.metacat.main.services.CatalogService;
import com.netflix.metacat.main.services.DatabaseService;
import com.netflix.metacat.main.services.GetCatalogServiceParameters;
import com.netflix.metacat.main.services.GetTableServiceParameters;
import com.netflix.metacat.main.services.MViewService;
import com.netflix.metacat.main.services.TableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Nullable;
import java.beans.PropertyEditorSupport;
import java.net.HttpURLConnection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Tag API implementation.
*
* @author amajumdar
*/
@RestController
@RequestMapping(
path = "/mds/v1/tag",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Api(
value = "TagV1",
description = "Federated metadata tag operations",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TagController {
private final RequestWrapper requestWrapper;
private final TagService tagService;
private final MetacatEventBus eventBus;
private final TableService tableService;
private final DatabaseService databaseService;
private final CatalogService catalogService;
private final MViewService mViewService;
/**
* Return the list of tags.
*
* @return list of tags
*/
@RequestMapping(method = RequestMethod.GET, path = "/tags")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Returns the tags",
notes = "Returns the tags"
)
public Set<String> getTags() {
return this.requestWrapper.processRequest(
"TagV1Resource.getTags",
this.tagService::getTags
);
}
/**
* Returns the list of qualified names for the given input.
*
* @param includeTags Set of matching tags
* @param excludeTags Set of un-matching tags
* @param sourceName Prefix of the source name
* @param databaseName Prefix of the database name
* @param tableName Prefix of the table name
* @param type metacat qualifed name type
* @return list of qualified names
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/list"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Returns the list of qualified names that are tagged with the given tags."
+ " Qualified names will be excluded if the contained tags matches the excluded tags",
notes = "Returns the list of qualified names that are tagged with the given tags."
+ " Qualified names will be excluded if the contained tags matches the excluded tags"
)
public List<QualifiedName> list(
@ApiParam(value = "Set of matching tags")
@Nullable @RequestParam(name = "include", required = false) final Set<String> includeTags,
@ApiParam(value = "Set of un-matching tags")
@Nullable @RequestParam(name = "exclude", required = false) final Set<String> excludeTags,
@ApiParam(value = "Prefix of the source name")
@Nullable @RequestParam(name = "sourceName", required = false) final String sourceName,
@ApiParam(value = "Prefix of the database name")
@Nullable @RequestParam(name = "databaseName", required = false) final String databaseName,
@ApiParam(value = "Prefix of the table name")
@Nullable @RequestParam(name = "tableName", required = false) final String tableName,
@ApiParam(value = "Qualified name type")
@Nullable
@RequestParam(name = "type", required = false) final QualifiedName.Type type
) {
return this.requestWrapper.processRequest(
"TagV1Resource.list",
() -> this.tagService.list(
includeTags,
excludeTags,
sourceName,
databaseName,
tableName,
type)
);
}
/**
* Returns the list of qualified names that are tagged with tags containing the given tag text.
*
* @param tag Tag partial text
* @param sourceName Prefix of the source name
* @param databaseName Prefix of the database name
* @param tableName Prefix of the table name
* @return list of qualified names
*/
@RequestMapping(method = RequestMethod.GET, path = "/search")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Returns the list of qualified names that are tagged with tags containing the given tagText",
notes = "Returns the list of qualified names that are tagged with tags containing the given tagText"
)
public List<QualifiedName> search(
@ApiParam(value = "Tag partial text")
@Nullable @RequestParam(name = "tag", required = false) final String tag,
@ApiParam(value = "Prefix of the source name")
@Nullable @RequestParam(name = "sourceName", required = false) final String sourceName,
@ApiParam(value = "Prefix of the database name")
@Nullable @RequestParam(name = "databaseName", required = false) final String databaseName,
@ApiParam(value = "Prefix of the table name")
@Nullable @RequestParam(name = "tableName", required = false) final String tableName
) {
return this.requestWrapper.processRequest(
"TagV1Resource.search",
() -> tagService.search(tag, sourceName, databaseName, tableName)
);
}
/**
* Sets the tags on the given object.
*
* @param tagCreateRequestDto tag create request dto
* @return set of tags
*/
@RequestMapping(
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
value = "Sets the tags on the given resource",
notes = "Sets the tags on the given resource"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The tags were successfully created"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public Set<String> setTags(
@ApiParam(value = "Request containing the set of tags and qualifiedName", required = true)
@RequestBody final TagCreateRequestDto tagCreateRequestDto
) {
return this.requestWrapper.processRequest(
tagCreateRequestDto.getName(),
"TagV1Resource.setTags",
() -> this.setResourceTags(tagCreateRequestDto)
);
}
private Set<String> setResourceTags(@NonNull final TagCreateRequestDto tagCreateRequestDto) {
final QualifiedName name = tagCreateRequestDto.getName();
final Set<String> tags = new HashSet<>(tagCreateRequestDto.getTags());
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
Set<String> result = new HashSet<>();
switch (name.getType()) {
case CATALOG:
//catalog service will throw exception if not found
this.catalogService.get(name, GetCatalogServiceParameters.builder()
.includeDatabaseNames(false).includeUserMetadata(false).build());
return this.tagService.setTags(name, tags, true);
case DATABASE:
if (!this.databaseService.exists(name)) {
throw new DatabaseNotFoundException(name);
}
result = this.tagService.setTags(name, tags, true);
this.eventBus.post(
new MetacatUpdateDatabasePostEvent(name, metacatRequestContext, this)
);
return result;
case TABLE:
if (!this.tableService.exists(name)) {
throw new TableNotFoundException(name);
}
final TableDto oldTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
result = this.tagService.setTags(name, tags, true);
final TableDto currentTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.eventBus.post(
new MetacatUpdateTablePostEvent(name, metacatRequestContext, this, oldTable, currentTable)
);
return result;
case MVIEW:
if (!this.mViewService.exists(name)) {
throw new MetacatNotFoundException(name.toString());
}
final Optional<TableDto> oldView = this.mViewService.getOpt(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build()
);
if (oldView.isPresent()) {
result = this.tagService.setTags(name, tags, true);
final Optional<TableDto> currentView = this.mViewService
.getOpt(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build());
currentView.ifPresent(p ->
this.eventBus.post(
new MetacatUpdateTablePostEvent(name, metacatRequestContext, this, oldView.get(),
currentView.get())
)
);
return result;
}
break;
default:
throw new MetacatNotFoundException("Unsupported qualifiedName type {}" + name);
}
return result;
}
/**
* Sets the tags on the given table.
* TODO: remove after setTags api is adopted
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param tags set of tags
* @return set of tags
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
value = "Sets the tags on the given table",
notes = "Sets the tags on the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The tags were successfully created on the table"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public Set<String> setTableTags(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "Set of tags", required = true)
@RequestBody final Set<String> tags
) {
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"TagV1Resource.setTableTags",
() -> {
// TODO: shouldn't this be in the tag service?
if (!this.tableService.exists(name)) {
throw new TableNotFoundException(name);
}
final TableDto oldTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
final Set<String> result = this.tagService.setTags(name, tags, true);
final TableDto currentTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.eventBus.post(
new MetacatUpdateTablePostEvent(name, metacatRequestContext, this, oldTable, currentTable)
);
return result;
}
);
}
/**
* Remove the tags from the given table.
* TODO: remove after removeTags api is adopted
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param deleteAll True if all tags need to be removed
* @param tags Tags to be removed from the given table
*/
@RequestMapping(
method = RequestMethod.DELETE,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 4,
value = "Remove the tags from the given table",
notes = "Remove the tags from the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_NO_CONTENT,
message = "The tags were successfully deleted from the table"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public void removeTableTags(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "True if all tags need to be removed")
@RequestParam(name = "all", defaultValue = "false") final boolean deleteAll,
@ApiParam(value = "Tags to be removed from the given table")
@Nullable @RequestBody(required = false) final Set<String> tags
) {
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
this.requestWrapper.processRequest(
name,
"TagV1Resource.removeTableTags",
() -> {
//TODO: Business logic in API tier...
if (!this.tableService.exists(name)) {
// Delete tags if exists
this.tagService.delete(name, false);
throw new TableNotFoundException(name);
}
final TableDto oldTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.tagService.removeTags(name, deleteAll, tags, true);
final TableDto currentTable = this.tableService
.get(name, GetTableServiceParameters.builder().includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.eventBus.post(
new MetacatUpdateTablePostEvent(
name,
metacatRequestContext,
this,
oldTable,
currentTable
)
);
return null;
}
);
}
/**
* Remove the tags from the given resource.
*
* @param tagRemoveRequestDto remove tag request dto
*/
@RequestMapping(
method = RequestMethod.DELETE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
value = "Remove the tags from the given resource",
notes = "Remove the tags from the given resource"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_NO_CONTENT,
message = "The tags were successfully deleted from the table"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public void removeTags(
@ApiParam(value = "Request containing the set of tags and qualifiedName", required = true)
@RequestBody final TagRemoveRequestDto tagRemoveRequestDto
) {
this.requestWrapper.processRequest(
tagRemoveRequestDto.getName(),
"TagV1Resource.removeTableTags",
() -> {
this.removeResourceTags(tagRemoveRequestDto);
return null;
}
);
}
private void removeResourceTags(final TagRemoveRequestDto tagRemoveRequestDto) {
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
final QualifiedName name = tagRemoveRequestDto.getName();
switch (name.getType()) {
case CATALOG:
//catalog service will throw exception if not found
this.catalogService.get(name, GetCatalogServiceParameters.builder()
.includeDatabaseNames(false).includeUserMetadata(false).build());
this.tagService.removeTags(name, tagRemoveRequestDto.getDeleteAll(),
new HashSet<>(tagRemoveRequestDto.getTags()), true);
break;
case DATABASE:
if (!this.databaseService.exists(name)) {
throw new DatabaseNotFoundException(name);
}
this.tagService.removeTags(name, tagRemoveRequestDto.getDeleteAll(),
new HashSet<>(tagRemoveRequestDto.getTags()), true);
this.eventBus.post(
new MetacatUpdateDatabasePostEvent(name, metacatRequestContext, this)
);
break;
case TABLE:
if (!this.tableService.exists(name)) {
this.tagService.delete(name, false);
throw new TableNotFoundException(name);
}
final TableDto oldTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.tagService.removeTags(name, tagRemoveRequestDto.getDeleteAll(),
new HashSet<>(tagRemoveRequestDto.getTags()), true);
final TableDto currentTable = this.tableService
.get(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build())
.orElseThrow(IllegalStateException::new);
this.eventBus.post(
new MetacatUpdateTablePostEvent(name, metacatRequestContext, this, oldTable, currentTable)
);
break;
case MVIEW:
if (!this.mViewService.exists(name)) {
throw new MetacatNotFoundException(name.toString());
}
final Optional<TableDto> oldView = this.mViewService.getOpt(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build()
);
if (oldView.isPresent()) {
this.tagService.removeTags(name, tagRemoveRequestDto.getDeleteAll(),
new HashSet<>(tagRemoveRequestDto.getTags()), true);
final Optional<TableDto> currentView = this.mViewService
.getOpt(name, GetTableServiceParameters.builder()
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.disableOnReadMetadataIntercetor(false)
.build());
currentView.ifPresent(p ->
this.eventBus.post(
new MetacatUpdateTablePostEvent(name, metacatRequestContext, this, oldView.get(),
currentView.get())
)
);
}
break;
default:
throw new MetacatNotFoundException("Unsupported qualifiedName type {}" + name);
}
}
@InitBinder
private void bindsCustomRequestParamType(final WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(QualifiedName.Type.class, new QualifiedNameTypeConverter());
}
private static class QualifiedNameTypeConverter extends PropertyEditorSupport {
@Override
public void setAsText(final String text) throws IllegalArgumentException {
super.setValue(QualifiedName.Type.fromValue(text));
}
}
}
| 75 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/MetacatController.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.api.v1;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.netflix.metacat.common.NameDateDto;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.CatalogDto;
import com.netflix.metacat.common.dto.CatalogMappingDto;
import com.netflix.metacat.common.dto.CreateCatalogDto;
import com.netflix.metacat.common.dto.DatabaseCreateRequestDto;
import com.netflix.metacat.common.dto.DatabaseDto;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.exception.MetacatNotFoundException;
import com.netflix.metacat.common.exception.MetacatNotSupportedException;
import com.netflix.metacat.common.server.api.v1.MetacatV1;
import com.netflix.metacat.common.server.connectors.exception.TableNotFoundException;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.metacat.main.api.RequestWrapper;
import com.netflix.metacat.main.services.CatalogService;
import com.netflix.metacat.main.services.DatabaseService;
import com.netflix.metacat.main.services.GetCatalogServiceParameters;
import com.netflix.metacat.main.services.GetDatabaseServiceParameters;
import com.netflix.metacat.main.services.GetTableNamesServiceParameters;
import com.netflix.metacat.main.services.GetTableServiceParameters;
import com.netflix.metacat.main.services.MViewService;
import com.netflix.metacat.main.services.MetacatServiceHelper;
import com.netflix.metacat.main.services.TableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Nullable;
import javax.validation.Valid;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Metacat V1 API implementation.
*/
@RestController
@RequestMapping(
path = "/mds/v1",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Api(
value = "MetacatV1",
description = "Federated metadata operations",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@Slf4j
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MetacatController implements MetacatV1 {
private final CatalogService catalogService;
private final DatabaseService databaseService;
private final MViewService mViewService;
private final TableService tableService;
private final RequestWrapper requestWrapper;
private final Config config;
/**
* Simple get on / to show API is up and available.
*/
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void index() {
// TODO: Hypermedia
}
/**
* Creates a new catalog.
*
* @param createCatalogDto catalog
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 3,
value = "Creates a new catalog",
notes = "Returns success if there were no errors creating the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_IMPLEMENTED,
message = "Not yet implemented"
)
}
)
public void createCatalog(@Valid @RequestBody final CreateCatalogDto createCatalogDto) {
throw new MetacatNotSupportedException("Create catalog is not supported.");
}
/**
* Creates the given database in the given catalog.
*
* @param catalogName catalog name
* @param databaseName database name
* @param databaseCreateRequestDto database create request
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 2,
value = "Creates the given database in the given catalog",
notes = "Given a catalog and a database name, creates the database in the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The database was created"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database cannot be located"
)
}
)
@Override
public void createDatabase(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The database information")
@Nullable @RequestBody(required = false) final DatabaseCreateRequestDto databaseCreateRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofDatabase(catalogName, databaseName)
);
this.requestWrapper.processRequest(
name,
"createDatabase",
() -> {
final DatabaseDto newDto = new DatabaseDto();
newDto.setName(name);
if (databaseCreateRequestDto != null) {
newDto.setUri(databaseCreateRequestDto.getUri());
newDto.setMetadata(databaseCreateRequestDto.getMetadata());
newDto.setDefinitionMetadata(databaseCreateRequestDto.getDefinitionMetadata());
}
this.databaseService.create(name, newDto);
return null;
}
);
}
/**
* Creates a table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param table TableDto with table details
* @return created <code>TableDto</code> table
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 2,
value = "Creates a table",
notes = "Creates the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The table was created"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public TableDto createTable(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The table information", required = true)
@Valid @RequestBody final TableDto table
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
if (MetacatServiceHelper.isIcebergTable(table)) {
MetacatContextManager.getContext().updateTableTypeMap(name, MetacatServiceHelper.ICEBERG_TABLE_TYPE);
}
log.info("Creating table: {} with info: {}", name, table);
return this.requestWrapper.processRequest(
name,
"createTable",
() -> {
Preconditions.checkArgument(
table.getName() != null
&& tableName.equalsIgnoreCase(table.getName().getTableName()
),
"Table name does not match the name in the table"
);
return this.tableService.create(name, table);
}
);
}
/**
* Creates a metacat view. A staging table that can contain partitions referring to the table partition locations.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param snapshot boolean to snapshot or not
* @param filter filter expression to use
* @return created <code>TableDto</code> mview
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 2,
value = "Creates a metacat view. A staging table that can contain partitions referring to the table partition "
+ "locations.",
notes = "Creates the given metacat view. A staging table that can contain partitions referring to the table "
+ "partition locations."
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_CREATED,
message = "The mView was created"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public TableDto createMView(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(
value = "To snapshot a list of partitions of the table to this view. "
+ "If true, it will restore the partitions from the table to this view."
)
@RequestParam(name = "snapshot", defaultValue = "false") final boolean snapshot,
@ApiParam(value = "Filter expression string to use")
@Nullable @RequestParam(value = "filter", required = false) final String filter
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"createMView",
() -> this.mViewService.createAndSnapshotPartitions(name, snapshot, filter)
);
}
/**
* Deletes the given database from the given catalog.
*
* @param catalogName catalog name
* @param databaseName database name
*/
@RequestMapping(method = RequestMethod.DELETE, path = "/catalog/{catalog-name}/database/{database-name}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 4,
value = "Deletes the given database from the given catalog",
notes = "Given a catalog and database, deletes the database from the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Database was successfully deleted"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database cannot be located"
)
}
)
public void deleteDatabase(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofDatabase(catalogName, databaseName)
);
this.requestWrapper.processRequest(
name,
"deleteDatabase",
() -> {
this.databaseService.delete(name);
return null;
}
);
}
/**
* Delete table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @return deleted <code>TableDto</code> table.
*/
@RequestMapping(
method = RequestMethod.DELETE,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 4,
value = "Delete table",
notes = "Deletes the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Table was successfully deleted"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public TableDto deleteTable(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"deleteTable",
() -> this.tableService.deleteAndReturn(name, false)
);
}
/**
* Delete metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @return deleted <code>TableDto</code> mview.
*/
@RequestMapping(
method = RequestMethod.DELETE,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 4,
value = "Delete metacat view",
notes = "Deletes the given metacat view"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "View was successfully deleted"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or metacat view cannot be located"
)
}
)
public TableDto deleteMView(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the metacat view", required = true)
@PathVariable("view-name") final String viewName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"deleteMView",
() -> this.mViewService.deleteAndReturn(name)
);
}
@Override
public CatalogDto getCatalog(final String catalogName) {
return getCatalog(catalogName, true, true);
}
/**
* Get the catalog by name.
*
* @param catalogName catalog name
* @return catalog
*/
@RequestMapping(method = RequestMethod.GET, path = "/catalog/{catalog-name}")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 2,
value = "Databases for the requested catalog",
notes = "The list of databases that belong to the given catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The catalog is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
@Override
public CatalogDto getCatalog(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "Whether to include list of database names")
@Nullable @RequestParam(name = "includeDatabaseNames", required = false) final Boolean includeDatabaseNames,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "true") final boolean includeUserMetadata) {
final QualifiedName name = this.requestWrapper.qualifyName(() -> QualifiedName.ofCatalog(catalogName));
return this.requestWrapper.processRequest(
name,
"getCatalog",
() -> this.catalogService.get(name, GetCatalogServiceParameters.builder()
.includeDatabaseNames(includeDatabaseNames == null
? config.listDatabaseNameByDefaultOnGetCatalog() : includeDatabaseNames)
.includeUserMetadata(includeUserMetadata).build())
);
}
/**
* List registered catalogs.
*
* @return registered catalogs.
*/
@RequestMapping(method = RequestMethod.GET, path = "/catalog")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "List registered catalogs",
notes = "The names and types of all catalogs registered with this server"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The catalogs are returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "No catalogs are registered with the server"
)
}
)
public List<CatalogMappingDto> getCatalogNames() {
final QualifiedName name = QualifiedName.ofCatalog("getCatalogNames");
return this.requestWrapper.processRequest(
name,
"getCatalogNames",
this.catalogService::getCatalogNames);
}
/**
* Get the database with the list of table names under it.
*
* @param catalogName catalog name
* @param databaseName database name
* @param includeUserMetadata true if details should include user metadata
* @return database with details
*/
@RequestMapping(method = RequestMethod.GET, path = "/catalog/{catalog-name}/database/{database-name}")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Tables for the requested database",
notes = "The list of tables that belong to the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The database is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database cannot be located"
)
}
)
@Override
public DatabaseDto getDatabase(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "Whether to include user metadata information to the response")
@RequestParam(name = "includeUserMetadata", defaultValue = "true") final boolean includeUserMetadata,
@ApiParam(value = "Whether to include list of table names")
@Nullable @RequestParam(name = "includeTableNames", required = false) final Boolean includeTableNames
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofDatabase(catalogName, databaseName)
);
return this.requestWrapper.processRequest(
name,
"getDatabase",
Collections.singletonMap("includeTableNamesPassed", includeTableNames == null ? "false" : "true"),
() -> databaseService.get(name,
GetDatabaseServiceParameters.builder()
.includeUserMetadata(includeUserMetadata)
.includeTableNames(includeTableNames == null
? config.listTableNamesByDefaultOnGetDatabase() : includeTableNames)
.disableOnReadMetadataIntercetor(false)
.build())
);
}
/**
* Get the table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name.
* @param includeInfo true if the details need to be included
* @param includeDefinitionMetadata true if the definition metadata to be included
* @param includeDataMetadata true if the data metadata to be included
* @return table
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}"
)
@ApiOperation(
position = 1,
value = "Table information",
notes = "Table information for the given table name under the given catalog and database")
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The table is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public TableDto getTable(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(
value = "Whether to include the core information about the table (location, serde, columns) in "
+ "the response. You would only say false here if you only want metadata."
)
@RequestParam(name = "includeInfo", defaultValue = "true") final boolean includeInfo,
@ApiParam(value = "Whether to include user definition metadata information to the response")
@RequestParam(
name = "includeDefinitionMetadata",
defaultValue = "true"
) final boolean includeDefinitionMetadata,
@ApiParam(value = "Whether to include user data metadata information to the response")
@RequestParam(name = "includeDataMetadata", defaultValue = "true") final boolean includeDataMetadata,
@ApiParam(value = "Whether to include more info details to the response. This value is considered only if "
+ "includeInfo is true.")
@RequestParam(name = "includeInfoDetails", defaultValue = "false") final boolean includeInfoDetails,
@ApiParam(value = "Whether to include only the metadata location in the response")
@RequestParam(
name = "includeMetadataLocationOnly",
defaultValue = "false") final boolean includeMetadataLocationOnly
) {
final Supplier<QualifiedName> qualifiedNameSupplier =
() -> QualifiedName.ofTable(catalogName, databaseName, tableName);
final QualifiedName name = this.requestWrapper.qualifyName(qualifiedNameSupplier);
return this.requestWrapper.processRequest(
name,
"getTable",
ImmutableMap.<String, String>builder()
.put("includeInfo", String.valueOf(includeInfo))
.put("includeDefinitionMetadata", String.valueOf(includeDefinitionMetadata))
.put("includeDataMetadata", String.valueOf(includeDataMetadata))
.put("includeMetadataFromConnector", String.valueOf(includeInfoDetails))
.put("includeMetadataLocationOnly", String.valueOf(includeMetadataLocationOnly))
.build(),
() -> {
final Optional<TableDto> table = this.tableService.get(
name,
GetTableServiceParameters.builder()
.includeInfo(includeInfo)
.includeDefinitionMetadata(includeDefinitionMetadata)
.includeDataMetadata(includeDataMetadata)
.disableOnReadMetadataIntercetor(false)
.includeMetadataFromConnector(includeInfoDetails)
.includeMetadataLocationOnly(includeMetadataLocationOnly)
.useCache(true)
.build()
);
final TableDto tableDto = table.orElseThrow(() -> new TableNotFoundException(name));
// Set the name to whatever the request was for because
// for aliases, this could've been set to the original name
tableDto.setName(qualifiedNameSupplier.get());
return tableDto;
}
);
}
/**
* Check if the table exists.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name.
*/
@RequestMapping(
method = RequestMethod.HEAD,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}"
)
@ApiOperation(
position = 1,
value = "Table information",
notes = "Table information for the given table name under the given catalog and database")
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Table exists"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "Table does not exists"
)
}
)
@Override
public void tableExists(@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName) {
final Supplier<QualifiedName> qualifiedNameSupplier =
() -> QualifiedName.ofTable(catalogName, databaseName, tableName);
final QualifiedName name = this.requestWrapper.qualifyName(qualifiedNameSupplier);
this.requestWrapper.processRequest(
name,
"exists",
() -> {
if (!tableService.exists(name)) {
throw new TableNotFoundException(name);
}
return null;
}
);
}
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/table-names"
)
@ApiOperation(
value = "Filtered list of table names",
notes = "Filtered list of table names for the given catalog. The filter expression pattern depends on the "
+ "catalog")
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "List of table names is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
@Override
public List<QualifiedName> getTableNames(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "filter expression")
@RequestParam(name = "filter") final String filter,
@ApiParam(value = "Size of the list")
@Nullable @RequestParam(name = "limit", required = false, defaultValue = "-1") final Integer limit) {
final Supplier<QualifiedName> qualifiedNameSupplier =
() -> QualifiedName.ofCatalog(catalogName);
final QualifiedName name = this.requestWrapper.qualifyName(qualifiedNameSupplier);
return this.requestWrapper.processRequest(
name,
"getTableNames",
() -> {
return this.tableService.getQualifiedNames(
name,
GetTableNamesServiceParameters.builder()
.filter(filter)
.limit(limit)
.build()
);
}
);
}
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table-names"
)
@ApiOperation(
value = "Filtered list of table names",
notes = "Filtered list of table names for the given database. The filter expression pattern depends on the "
+ "catalog")
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "List of table names is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
@Override
public List<QualifiedName> getTableNames(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "filter expression")
@RequestParam(name = "filter") final String filter,
@ApiParam(value = "Size of the list")
@Nullable @RequestParam(name = "limit", required = false, defaultValue = "-1") final Integer limit) {
final Supplier<QualifiedName> qualifiedNameSupplier =
() -> QualifiedName.ofDatabase(catalogName, databaseName);
final QualifiedName name = this.requestWrapper.qualifyName(qualifiedNameSupplier);
return this.requestWrapper.processRequest(
name,
"getTableNames",
() -> {
return this.tableService.getQualifiedNames(
name,
GetTableNamesServiceParameters.builder()
.filter(filter)
.limit(limit)
.build()
);
}
);
}
/**
* List of metacat view names.
*
* @param catalogName catalog name
* @return list of metacat view names.
*/
@RequestMapping(method = RequestMethod.GET, path = "/catalog/{catalog-name}/mviews")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "List of metacat views",
notes = "List of metacat views for a catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The list of views is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
public List<NameDateDto> getMViews(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName
) {
final QualifiedName name = this.requestWrapper.qualifyName(() -> QualifiedName.ofCatalog(catalogName));
return this.requestWrapper.processRequest(
name,
"getMViews",
() -> mViewService.list(name)
);
}
/**
* List of metacat view names.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @return List of metacat view names.
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mviews"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "List of metacat views",
notes = "List of metacat views for a catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The list of views is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog cannot be located"
)
}
)
public List<NameDateDto> getMViews(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"getMViews",
() -> this.mViewService.list(name)
);
}
/**
* Get metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @return metacat view
*/
@RequestMapping(
method = RequestMethod.GET,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}"
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Metacat View information",
notes = "View information for the given view name under the given catalog and database"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "The view is returned"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public TableDto getMView(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the view", required = true)
@PathVariable("view-name") final String viewName
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getMView",
() -> {
final Optional<TableDto> table = this.mViewService.getOpt(name,
GetTableServiceParameters.builder()
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.includeInfo(true)
.disableOnReadMetadataIntercetor(false)
.build());
return table.orElseThrow(() -> new MetacatNotFoundException("Unable to find view: " + name));
}
);
}
/**
* Rename table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param newTableName new table name
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/rename"
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 3,
value = "Rename table",
notes = "Renames the given table with the new name")
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Table successfully renamed"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public void renameTable(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the table", required = true)
@RequestParam("newTableName") final String newTableName
) {
final QualifiedName oldName = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
final QualifiedName newName = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, newTableName)
);
this.requestWrapper.processRequest(
oldName,
"renameTable",
() -> {
this.tableService.rename(oldName, newName, false);
return null;
}
);
}
/**
* Updates an existing catalog.
*
* @param catalogName catalog name
* @param createCatalogDto catalog
*/
@RequestMapping(
method = RequestMethod.PUT,
path = "/catalog/{catalog-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 4,
value = "Updates an existing catalog",
notes = "Returns success if there were no errors updating the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Catalog successfully updated"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "No catalogs are registered with the server"
)
}
)
public void updateCatalog(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The metadata to update in the catalog", required = true)
@RequestBody final CreateCatalogDto createCatalogDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(() -> QualifiedName.ofCatalog(catalogName));
this.requestWrapper.processRequest(
name,
"updateCatalog",
() -> {
createCatalogDto.setName(name);
this.catalogService.update(name, createCatalogDto);
return null;
}
);
}
/**
* Updates the given database in the given catalog.
*
* @param catalogName catalog name.
* @param databaseName database name.
* @param databaseUpdateRequestDto database
*/
@RequestMapping(
method = RequestMethod.PUT,
path = "/catalog/{catalog-name}/database/{database-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 3,
value = "Updates the given database in the given catalog",
notes = "Given a catalog and a database name, updates the database in the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Database successfully updated"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database cannot be located"
)
}
)
public void updateDatabase(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The database information", required = true)
@RequestBody final DatabaseCreateRequestDto databaseUpdateRequestDto
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofDatabase(catalogName, databaseName)
);
this.requestWrapper.processRequest(
name,
"updateDatabase",
() -> {
final DatabaseDto newDto = new DatabaseDto();
newDto.setName(name);
newDto.setUri(databaseUpdateRequestDto.getUri());
newDto.setMetadata(databaseUpdateRequestDto.getMetadata());
newDto.setDefinitionMetadata(databaseUpdateRequestDto.getDefinitionMetadata());
this.databaseService.update(name, newDto);
return null;
}
);
}
/**
* Update metacat view.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param viewName view name
* @param table view
* @return updated metacat view
*/
@RequestMapping(
method = RequestMethod.PUT,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 3,
value = "Update mview",
notes = "Updates the given mview"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "View successfully updated"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
public TableDto updateMView(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The name of the view", required = true)
@PathVariable("view-name") final String viewName,
@ApiParam(value = "The view information", required = true)
@RequestBody final TableDto table
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
);
return this.requestWrapper.processRequest(
name,
"getMView",
() -> this.mViewService.updateAndReturn(name, table)
);
}
/**
* Update table.
*
* @param catalogName catalog name
* @param databaseName database name
* @param tableName table name
* @param table table
* @return table
*/
@RequestMapping(
method = RequestMethod.PUT,
path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ApiOperation(
position = 3,
value = "Update table",
notes = "Updates the given table"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_OK,
message = "Table successfully updated"
),
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_FOUND,
message = "The requested catalog or database or table cannot be located"
)
}
)
@Override
public TableDto updateTable(
@ApiParam(value = "The name of the catalog", required = true)
@PathVariable("catalog-name") final String catalogName,
@ApiParam(value = "The name of the database", required = true)
@PathVariable("database-name") final String databaseName,
@ApiParam(value = "The name of the table", required = true)
@PathVariable("table-name") final String tableName,
@ApiParam(value = "The table information", required = true)
@RequestBody final TableDto table
) {
final QualifiedName name = this.requestWrapper.qualifyName(
() -> QualifiedName.ofTable(catalogName, databaseName, tableName)
);
return this.requestWrapper.processRequest(
name,
"updateTable",
() -> {
Preconditions.checkArgument(table.getName() != null
&& tableName.equalsIgnoreCase(table.getName().getTableName()
),
"Table name does not match the name in the table"
);
return this.tableService.updateAndReturn(name, table);
}
);
}
}
| 76 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/SearchController.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api.v1;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.main.api.RequestWrapper;
import com.netflix.metacat.main.services.search.ElasticSearchUtil;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Search API.
*/
@ConditionalOnProperty(value = "metacat.elasticsearch.enabled", havingValue = "true")
@RestController
@RequestMapping(
path = "/mds/v1/search",
produces = MediaType.APPLICATION_JSON_VALUE
)
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SearchController {
private final ElasticSearchUtil elasticSearchUtil;
private final RequestWrapper requestWrapper;
/**
* Searches the list of tables for the given search string.
*
* @param searchString search string
* @return list of tables
*/
@RequestMapping(method = RequestMethod.GET, path = "/table")
@ResponseStatus(HttpStatus.OK)
public List<TableDto> searchTables(
@ApiParam(value = "The query parameter", required = true)
@RequestParam(name = "q") final String searchString
) {
return this.requestWrapper.processRequest(
"SearchMetacatV1Resource.searchTables",
() -> this.elasticSearchUtil.simpleSearch(searchString)
);
}
}
| 77 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/ResolverController.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api.v1;
import com.netflix.metacat.common.dto.ResolveByUriRequestDto;
import com.netflix.metacat.common.dto.ResolveByUriResponseDto;
import com.netflix.metacat.common.exception.MetacatNotFoundException;
import com.netflix.metacat.main.services.PartitionService;
import com.netflix.metacat.main.services.TableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* Resolver V1 Implementation as Jersey Resource.
*
* @author zhenl
* @since 1.0.0
*/
@RestController
@RequestMapping(
path = "/mds/v1/resolver",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Api(
value = "ResolverV1",
description = "Metadata resolver operations",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ResolverController {
private final TableService tableService;
private final PartitionService partitionService;
/**
* Gets the qualified name by uri.
*
* @param resolveByUriRequestDto resolveByUriRequestDto
* @param prefixSearch search by prefix flag
* @return the qualified name of uri
*/
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
value = "Returns the list of qualified names of tables and partitions containing the given URI path",
notes = "Returns the list of qualified names of tables and partitions containing the given URI path"
)
public ResolveByUriResponseDto resolveByUri(
@ApiParam(value = "do prefix search for URI")
@RequestParam(name = "prefixSearch", defaultValue = "false") final boolean prefixSearch,
@RequestBody final ResolveByUriRequestDto resolveByUriRequestDto
) {
final ResolveByUriResponseDto result = new ResolveByUriResponseDto();
result.setTables(this.tableService.getQualifiedNames(resolveByUriRequestDto.getUri(), prefixSearch));
result.setPartitions(this.partitionService.getQualifiedNames(resolveByUriRequestDto.getUri(), prefixSearch));
return result;
}
/**
* Check if the uri used more than once.
*
* @param prefixSearch search by prefix flag
* @param resolveByUriRequestDto resolveByUriRequestDto
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/isUriUsedMoreThanOnce",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 1,
value = "Returns status 204 if the given URI is being referred more than once."
+ " Returns status 404 if the given URI is not found or not being referred more than once.",
notes = "Returns status 204 if the given URI is being referred more than once."
+ " Returns status 404 if the given URI is not found or not being referred more than once.")
public void isUriUsedMoreThanOnce(
@ApiParam(value = "do prefix search for URI", defaultValue = "false")
@RequestParam(name = "prefixSearch", defaultValue = "false") final Boolean prefixSearch,
@RequestBody final ResolveByUriRequestDto resolveByUriRequestDto
) {
final String uri = resolveByUriRequestDto.getUri();
int size = this.tableService.getQualifiedNames(uri, prefixSearch).size();
if (size < 2) {
size += this.partitionService.getQualifiedNames(uri, prefixSearch).size();
}
if (size <= 1) {
throw new MetacatNotFoundException("URI not found more than once");
}
}
}
| 78 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/package-info.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* V1 API Controllers.
*
* @author tgianos
* @since 1.1.0
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.main.api.v1;
import javax.annotation.ParametersAreNonnullByDefault;
| 79 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/api/v1/MetadataController.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.api.v1;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Sets;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.DataMetadataDto;
import com.netflix.metacat.common.dto.DataMetadataGetRequestDto;
import com.netflix.metacat.common.dto.DefinitionMetadataDto;
import com.netflix.metacat.common.dto.SortOrder;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.metacat.main.api.RequestWrapper;
import com.netflix.metacat.main.services.GetTableServiceParameters;
import com.netflix.metacat.main.services.MetacatServiceHelper;
import com.netflix.metacat.main.services.MetadataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Metadata V1 API implementation.
*
* @author amajumdar
*/
@RestController
@RequestMapping(
path = "/mds/v1/metadata",
produces = MediaType.APPLICATION_JSON_VALUE
)
@Api(
value = "MetadataV1",
description = "Federated user metadata operations",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
@DependsOn("metacatCoreInitService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MetadataController {
private final UserMetadataService userMetadataService;
private final MetacatServiceHelper helper;
private final MetadataService metadataService;
private final RequestWrapper requestWrapper;
/**
* Returns the data metadata.
*
* @param metadataGetRequestDto metadata request
* @return data metadata
*/
@RequestMapping(method = RequestMethod.POST, path = "/data", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 1,
value = "Returns the data metadata",
notes = "Returns the data metadata"
)
public DataMetadataDto getDataMetadata(@RequestBody final DataMetadataGetRequestDto metadataGetRequestDto) {
return this.requestWrapper.processRequest(
"getDataMetadata",
() -> {
DataMetadataDto result = null;
if (metadataGetRequestDto.getUri() != null) {
final Optional<ObjectNode> o
= this.userMetadataService.getDataMetadata(metadataGetRequestDto.getUri());
if (o.isPresent()) {
result = new DataMetadataDto();
result.setDataMetadata(o.get());
result.setUri(metadataGetRequestDto.getUri());
}
}
return result;
}
);
}
/**
* Returns the list of definition metadata. Client should be aware that
* this api does not apply the metadata read interceptor,
* it queries the original results from database. The definition metadata results from this API can
* be different from the table get API.
* TODO: we need to find a way to address the interceptor application or remove this API.
*
* @param sortBy Sort the list by this value
* @param sortOrder Sorting order to use
* @param offset Offset of the list returned
* @param limit Size of the list
* @param lifetime has lifetime set
* @param type Type of the metadata item. Values: database, table, partition
* @param name Text that matches the name of the metadata (accepts sql wildcards)
* @param dataProperties Set of data property names.
* Filters the returned list that only contains the given property names
* @return list of definition metadata
*/
@RequestMapping(method = RequestMethod.GET, path = "/definition/list")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 2,
value = "Returns the definition metadata",
notes = "Returns the definition metadata"
)
public List<DefinitionMetadataDto> getDefinitionMetadataList(
@ApiParam(value = "Sort the list by this value")
@Nullable @RequestParam(name = "sortBy", required = false) final String sortBy,
@ApiParam(value = "Sorting order to use")
@Nullable @RequestParam(name = "sortOrder", required = false) final SortOrder sortOrder,
@ApiParam(value = "Offset of the list returned")
@Nullable @RequestParam(name = "offset", required = false) final Integer offset,
@ApiParam(value = "Size of the list")
@Nullable @RequestParam(name = "limit", required = false) final Integer limit,
@ApiParam(value = "has lifetime set", defaultValue = "false")
@RequestParam(name = "lifetime", defaultValue = "false") final boolean lifetime,
@ApiParam(value = "Type of the metadata item. Values: database, table, partition")
@Nullable @RequestParam(name = "type", required = false) final String type,
@ApiParam(value = "Text that matches the name of the metadata (accepts sql wildcards)")
@Nullable @RequestParam(name = "name", required = false) final String name,
@ApiParam(
value = "Set of data property names. Filters the returned list that only contains the given property names"
)
@Nullable @RequestParam(name = "data-property", required = false) final Set<String> dataProperties
) {
final Set<String> localDataProperties = dataProperties != null ? dataProperties : Sets.newHashSet();
if (lifetime) {
localDataProperties.add("lifetime");
}
return requestWrapper.processRequest(
"getDefinitionMetadataList",
() -> this.userMetadataService.searchDefinitionMetadata(
localDataProperties,
type,
name,
getTableDto(name),
sortBy,
sortOrder != null ? sortOrder.name() : null,
offset,
limit
)
);
}
private TableDto getTableDto(@Nullable final String name) {
Optional<TableDto> optionalTableDto = Optional.empty();
if (name != null) {
final QualifiedName qualifiedName = QualifiedName.fromString(name);
if (qualifiedName.isTableDefinition()) {
optionalTableDto = this.metadataService.getTableService().get(qualifiedName, GetTableServiceParameters
.builder().disableOnReadMetadataIntercetor(true)
.includeInfo(true)
.includeDefinitionMetadata(false)
.includeDataMetadata(false)
.build());
}
}
return optionalTableDto.isPresent() ? optionalTableDto.get() : null;
}
/**
* Returns the list of qualified names owned by the given owners.
*
* @param owners set of owners
* @return the list of qualified names owned by the given owners
*/
@RequestMapping(method = RequestMethod.GET, path = "/searchByOwners")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(
position = 3,
value = "Returns the qualified names owned by the given owners",
notes = "Returns the qualified names owned by the given owners"
)
public List<QualifiedName> searchByOwners(
@ApiParam(value = "Set of owners", required = true)
@RequestParam("owner") final Set<String> owners
) {
return this.requestWrapper.processRequest(
"searchByOwners",
() -> userMetadataService.searchByOwners(owners)
);
}
/**
* Delete the definition metadata for the given name.
*
* @param name Name of definition metadata to be deleted
* @param force If true, deletes the metadata without checking if the database/table/partition exists
*/
@RequestMapping(method = RequestMethod.DELETE, path = "/definition")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
position = 4,
value = "Deletes the given definition metadata"
)
public void deleteDefinitionMetadata(
@ApiParam(value = "Name of definition metadata to be deleted", required = true)
@RequestParam(name = "name") final String name,
@ApiParam(value = "If true, deletes the metadata without checking if the database/table/partition exists")
@RequestParam(name = "force", defaultValue = "false") final boolean force
) {
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
requestWrapper.processRequest(
"deleteDefinitionMetadata",
() -> {
metadataService.deleteDefinitionMetadata(QualifiedName.fromString(name), force, metacatRequestContext);
return null;
}
);
}
/**
* Deletes the data metadata marked for deletion.
*/
@RequestMapping(method = RequestMethod.DELETE, path = "/data/cleanup")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
hidden = true,
value = "Admin API to delete obsolete data metadata"
)
public void cleanUpDeletedDataMetadata() {
this.metadataService.cleanUpDeletedDataMetadata();
}
/**
* Deletes the obsolete metadata.
*/
@RequestMapping(method = RequestMethod.DELETE, path = "/definition/cleanup")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation(
hidden = true,
value = "Admin API to delete obsolete metadata"
)
public void cleanUpObsoleteMetadata() {
this.metadataService.cleanUpObsoleteDefinitionMetadata();
}
}
| 80 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/IcebergTableEventHandler.java | package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.server.events.AsyncListener;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.events.MetacatUpdateIcebergTablePostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateTablePostEvent;
import com.netflix.metacat.common.server.monitoring.Metrics;
import com.netflix.spectator.api.Registry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* Handler for Iceberg table specific events.
*/
@Slf4j
@Component
@AsyncListener
public class IcebergTableEventHandler {
private final TableService tableService;
private final MetacatEventBus eventBus;
private final Registry registry;
/**
* Constructor.
*
* @param tableService The table service.
* @param eventBus The metacat event bus.
* @param registry The registry.
*/
@Autowired
public IcebergTableEventHandler(
final TableService tableService,
final MetacatEventBus eventBus,
final Registry registry
) {
this.tableService = tableService;
this.eventBus = eventBus;
this.registry = registry;
}
/**
* The update table event handler.
*
* @param event The event.
*/
@EventListener
public void metacatUpdateTableEventHandler(final MetacatUpdateIcebergTablePostEvent event) {
final QualifiedName name = event.getName();
final TableDto tableDto = event.getRequestTable();
TableDto updatedDto = tableDto;
try {
updatedDto = tableService.get(name,
GetTableServiceParameters.builder()
.disableOnReadMetadataIntercetor(false)
.includeInfo(true)
.includeDataMetadata(true)
.includeDefinitionMetadata(true)
.build()).orElse(tableDto);
} catch (Exception ex) {
handleException(name, "getTable", ex);
}
try {
eventBus.post(new MetacatUpdateTablePostEvent(event.getName(), event.getRequestContext(),
this, event.getOldTable(),
updatedDto, updatedDto != tableDto));
} catch (Exception ex) {
handleException(name, "postEvent", ex);
}
}
private void handleException(final QualifiedName name,
final String request,
final Exception ex) {
log.warn("Failed {} for table {}. Error: {}", request, name, ex.getMessage());
registry.counter(registry.createId(
Metrics.CounterTableUpdateIgnoredException.getMetricName()).withTags(name.parts())
.withTag("request", request)).increment();
}
}
| 81 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/GetTableServiceParameters.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.services;
import lombok.Builder;
import lombok.Value;
/**
* Getable Parameters.
*
* @author zhenl
* @since 1.2.0
*/
@Value
@Builder
public class GetTableServiceParameters {
private final boolean includeInfo;
private final boolean includeDefinitionMetadata;
private final boolean includeDataMetadata;
private final boolean disableOnReadMetadataIntercetor;
private final boolean useCache;
private final boolean includeMetadataFromConnector;
private final boolean includeMetadataLocationOnly;
}
| 82 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MetacatServiceHelper.java | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.BaseDto;
import com.netflix.metacat.common.dto.DatabaseDto;
import com.netflix.metacat.common.dto.PartitionDto;
import com.netflix.metacat.common.dto.PartitionsSaveRequestDto;
import com.netflix.metacat.common.dto.PartitionsSaveResponseDto;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.server.events.MetacatDeleteDatabasePreEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteMViewPostEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteMViewPreEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteTablePartitionPostEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteTablePartitionPreEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteTablePostEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteTablePreEvent;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.events.MetacatSaveTablePartitionPostEvent;
import com.netflix.metacat.common.server.events.MetacatSaveTablePartitionPreEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateDatabasePostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateDatabasePreEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateMViewPostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateMViewPreEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateTablePostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateTablePreEvent;
import java.util.List;
/**
* Generic Service helper.
*
* @author amajumdar
*/
public class MetacatServiceHelper {
/**
* Defines the table type.
*/
public static final String PARAM_TABLE_TYPE = "table_type";
/**
* Iceberg table type.
*/
public static final String ICEBERG_TABLE_TYPE = "ICEBERG";
private final DatabaseService databaseService;
private final TableService tableService;
private final PartitionService partitionService;
private final MViewService mViewService;
private final MetacatEventBus eventBus;
/**
* Constructor.
*
* @param databaseService database service
* @param tableService table service
* @param partitionService partition service
* @param mViewService mview service
* @param eventBus event bus
*/
public MetacatServiceHelper(
final DatabaseService databaseService,
final TableService tableService,
final PartitionService partitionService,
final MViewService mViewService,
final MetacatEventBus eventBus
) {
this.databaseService = databaseService;
this.tableService = tableService;
this.partitionService = partitionService;
this.mViewService = mViewService;
this.eventBus = eventBus;
}
/**
* Get the relevant service for the given qualified name.
*
* @param name name
* @return service
*/
public MetacatService getService(final QualifiedName name) {
final MetacatService result;
if (name.isPartitionDefinition()) {
result = partitionService;
} else if (name.isViewDefinition()) {
result = mViewService;
} else if (name.isTableDefinition()) {
result = tableService;
} else if (name.isDatabaseDefinition()) {
result = databaseService;
} else {
throw new IllegalArgumentException(String.format("Invalid name %s", name));
}
return result;
}
/**
* Calls the right method of the event bus for the given qualified name.
*
* @param name name
* @param metacatRequestContext context
* @param dto dto
*/
public void postPreUpdateEvent(
final QualifiedName name,
final MetacatRequestContext metacatRequestContext,
final BaseDto dto
) {
if (name.isPartitionDefinition()) {
final PartitionsSaveRequestDto partitionsSaveRequestDto = new PartitionsSaveRequestDto();
if (dto != null) {
partitionsSaveRequestDto.setPartitions(ImmutableList.of((PartitionDto) dto));
}
this.eventBus.post(
new MetacatSaveTablePartitionPreEvent(name, metacatRequestContext, this, partitionsSaveRequestDto)
);
} else if (name.isViewDefinition()) {
this.eventBus.post(
new MetacatUpdateMViewPreEvent(name, metacatRequestContext, this, (TableDto) dto)
);
} else if (name.isTableDefinition()) {
this.eventBus.post(
new MetacatUpdateTablePreEvent(name, metacatRequestContext, this, (TableDto) dto, (TableDto) dto)
);
} else if (name.isDatabaseDefinition()) {
eventBus.post(new MetacatUpdateDatabasePreEvent(name, metacatRequestContext, this));
} else {
throw new IllegalArgumentException(String.format("Invalid name %s", name));
}
}
/**
* Calls the right method of the event bus for the given qualified name.
*
* @param name name
* @param metacatRequestContext context
* @param oldDTo dto
* @param currentDto dto
*/
public void postPostUpdateEvent(
final QualifiedName name,
final MetacatRequestContext metacatRequestContext,
final BaseDto oldDTo,
final BaseDto currentDto
) {
if (name.isPartitionDefinition()) {
final List<PartitionDto> dtos = Lists.newArrayList();
if (currentDto != null) {
dtos.add((PartitionDto) currentDto);
}
// This request neither added nor updated partitions
final PartitionsSaveResponseDto partitionsSaveResponseDto = new PartitionsSaveResponseDto();
this.eventBus.post(
new MetacatSaveTablePartitionPostEvent(
name,
metacatRequestContext,
this,
dtos,
partitionsSaveResponseDto
)
);
} else if (name.isViewDefinition()) {
final MetacatUpdateMViewPostEvent event = new MetacatUpdateMViewPostEvent(
name,
metacatRequestContext,
this,
(TableDto) currentDto
);
this.eventBus.post(event);
} else if (name.isTableDefinition()) {
final MetacatUpdateTablePostEvent event = new MetacatUpdateTablePostEvent(
name,
metacatRequestContext,
this,
(TableDto) oldDTo,
(TableDto) currentDto
);
this.eventBus.post(event);
} else if (name.isDatabaseDefinition()) {
this.eventBus.post(new MetacatUpdateDatabasePostEvent(name, metacatRequestContext, this));
} else {
throw new IllegalArgumentException(String.format("Invalid name %s", name));
}
}
/**
* Calls the right method of the event bus for the given qualified name.
*
* @param name name
* @param metacatRequestContext context
*/
public void postPreDeleteEvent(
final QualifiedName name,
final MetacatRequestContext metacatRequestContext
) {
if (name.isPartitionDefinition()) {
final PartitionsSaveRequestDto partitionsSaveRequestDto = new PartitionsSaveRequestDto();
partitionsSaveRequestDto.setPartitionIdsForDeletes(Lists.newArrayList(name.getPartitionName()));
this.eventBus.post(
new MetacatDeleteTablePartitionPreEvent(name, metacatRequestContext, this, partitionsSaveRequestDto)
);
} else if (name.isViewDefinition()) {
this.eventBus.post(
new MetacatDeleteMViewPreEvent(name, metacatRequestContext, this)
);
} else if (name.isTableDefinition()) {
this.eventBus.post(new MetacatDeleteTablePreEvent(name, metacatRequestContext, this));
} else if (name.isDatabaseDefinition()) {
final DatabaseDto dto = new DatabaseDto();
dto.setName(name);
eventBus.post(new MetacatDeleteDatabasePreEvent(name, metacatRequestContext, this, dto));
} else {
throw new IllegalArgumentException(String.format("Invalid name %s", name));
}
}
/**
* Calls the right method of the event bus for the given qualified name.
*
* @param name name
* @param metacatRequestContext context
*/
public void postPostDeleteEvent(
final QualifiedName name,
final MetacatRequestContext metacatRequestContext
) {
if (name.isPartitionDefinition()) {
this.eventBus.post(
new MetacatDeleteTablePartitionPostEvent(
name,
metacatRequestContext,
this,
Lists.newArrayList(PartitionDto.builder().name(name).build())
)
);
} else if (name.isViewDefinition()) {
final TableDto dto = new TableDto();
dto.setName(name);
this.eventBus.post(new MetacatDeleteMViewPostEvent(name, metacatRequestContext, this, dto));
} else if (name.isTableDefinition()) {
final TableDto dto = new TableDto();
dto.setName(name);
this.eventBus.post(new MetacatDeleteTablePostEvent(name, metacatRequestContext, this, dto,
false));
} else if (name.isDatabaseDefinition()) {
this.eventBus.post(new MetacatUpdateDatabasePostEvent(name, metacatRequestContext, this));
} else {
throw new IllegalArgumentException(String.format("Invalid name %s", name));
}
}
/**
* check if the table is an Iceberg Table.
*
* @param tableDto table dto
* @return true for iceberg table
*/
public static boolean isIcebergTable(final TableDto tableDto) {
return tableDto.getMetadata() != null
&& tableDto.getMetadata().containsKey(PARAM_TABLE_TYPE)
&& ICEBERG_TABLE_TYPE
.equalsIgnoreCase(tableDto.getMetadata().get(PARAM_TABLE_TYPE));
}
}
| 83 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MetacatThriftService.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.server.spi.MetacatCatalogConfig;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.thrift.CatalogThriftService;
import com.netflix.metacat.thrift.CatalogThriftServiceFactory;
import javax.inject.Inject;
import java.util.List;
import java.util.stream.Collectors;
/**
* Metacat thrift service.
*
* @author zhenl
* @since 1.1.0
*/
public class MetacatThriftService {
private final ConnectorManager connectorManager;
private final CatalogThriftServiceFactory thriftServiceFactory;
/**
* Constructor.
*
* @param catalogThriftServiceFactory factory
* @param connectorManager connecter manager
*/
@Inject
public MetacatThriftService(final CatalogThriftServiceFactory catalogThriftServiceFactory,
final ConnectorManager connectorManager) {
this.thriftServiceFactory = catalogThriftServiceFactory;
this.connectorManager = connectorManager;
}
public List<CatalogThriftService> getCatalogThriftServices() {
return connectorManager.getCatalogConfigs()
.stream()
.filter(MetacatCatalogConfig::isThriftInterfaceRequested)
.map(catalog -> thriftServiceFactory.create(catalog.getCatalogName(), catalog.getThriftPort()))
.collect(Collectors.toList());
}
/**
* Start.
*
* @throws Exception error
*/
public void start() throws Exception {
for (CatalogThriftService service : getCatalogThriftServices()) {
service.start();
}
}
/**
* Stop.
*
* @throws Exception error
*/
public void stop() throws Exception {
for (CatalogThriftService service : getCatalogThriftServices()) {
service.stop();
}
}
}
| 84 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MetacatService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.BaseDto;
/**
* Base service interface for all entities like catalog, database, table, view and partition.
*
* @author amajumdar,zhenl
*
* @param <T> Resource entity type.
*/
public interface MetacatService<T extends BaseDto> {
/**
* Creates the object.
*
* @param name qualified name of the object
* @param dto object metadata
* @return created object
*/
T create(QualifiedName name, T dto);
/**
* Updates the object.
*
* @param name qualified name of the object
* @param dto object dto
*/
void update(QualifiedName name, T dto);
/**
* Updates the object and return the updated object.
*
* @param name qualified name of the object
* @param dto object dto
* @return updated object
*/
T updateAndReturn(QualifiedName name, T dto);
/**
* Deletes the object. Returns the metadata of the object deleted.
*
* @param name qualified name of the object to be deleted
*/
void delete(QualifiedName name);
/**
* Returns the object with the given name.
*
* @param name qualified name of the object
* @return Returns the object with the given name
*/
T get(QualifiedName name);
/**
* Returns true, if the object exists.
*
* @param name qualified name of the object
* @return boolean
*/
boolean exists(QualifiedName name);
}
| 85 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/CatalogTraversal.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.google.common.base.Functions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.CatalogDto;
import com.netflix.metacat.common.dto.DatabaseDto;
import com.netflix.metacat.common.dto.TableDto;
import com.netflix.metacat.common.server.monitoring.Metrics;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.spectator.api.Registry;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.Instant;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* This class does a refresh of all the metadata entities from original data sources to elastic search.
*
* @author amajumdar
*/
@Slf4j
public class CatalogTraversal {
private static final Predicate<Object> NOT_NULL = Objects::nonNull;
private static AtomicBoolean isTraversalAlreadyRunning = new AtomicBoolean(false);
private final CatalogTraversalServiceHelper catalogTraversalServiceHelper;
private final List<CatalogTraversalAction> actions;
private final Config config;
private Registry registry;
// Traversal state
private Context context;
// Fixed thread pool
private ListeningExecutorService service;
private ListeningExecutorService actionService;
private ExecutorService defaultService;
/**
* Constructor.
*
* @param config System config
* @param catalogTraversalServiceHelper Catalog service helper
* @param registry registry of spectator
*/
public CatalogTraversal(
@Nonnull @NonNull final Config config,
@Nonnull @NonNull final CatalogTraversalServiceHelper catalogTraversalServiceHelper,
@Nonnull @NonNull final Registry registry
) {
this.config = config;
this.actions = Lists.newArrayList();
this.catalogTraversalServiceHelper = catalogTraversalServiceHelper;
this.registry = registry;
}
private static ExecutorService newFixedThreadPool(
final int nThreads,
final String threadFactoryName,
final int queueSize
) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(queueSize),
new ThreadFactoryBuilder()
.setNameFormat(threadFactoryName)
.build(),
(r, executor) -> {
// this will block if the queue is full
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw Throwables.propagate(e);
}
});
}
/**
* Adds the action handlers.
* @param actionHandlers list of action handlers
*/
public void addActions(final List<CatalogTraversalAction> actionHandlers) {
this.actions.addAll(actionHandlers);
}
/**
* Does a sweep across all catalogs to refresh the same data in elastic search.
*/
public void process() {
processCatalogs(catalogTraversalServiceHelper.getCatalogNames());
}
/**
* Does a sweep across given catalogs to refresh the same data in elastic search.
*
* @param catalogNames catalog names
*/
public void processCatalogs(final List<String> catalogNames) {
final List<QualifiedName> qNames = catalogNames.stream()
.map(QualifiedName::ofCatalog).collect(Collectors.toList());
_process(qNames, () -> _processCatalogs(catalogNames), "processCatalogs", true, 1000);
}
@SuppressWarnings("checkstyle:methodname")
private void _process(final List<QualifiedName> qNames, final Supplier<ListenableFuture<Void>> supplier,
final String requestName, final boolean delete, final int queueSize) {
if (isTraversalAlreadyRunning.compareAndSet(false, true)) {
final long start = registry.clock().wallTime();
try {
log.info("Start Traversal: Full catalog traversal. Processing {} ...", qNames);
final MetacatRequestContext requestContext = MetacatRequestContext.builder()
.userName("admin")
.clientAppName("catalogTraversal")
.apiUri("catalogTraversal")
.scheme("internal")
.build();
MetacatContextManager.setContext(requestContext);
final Instant startInstant = Instant.now();
context = new Context(startInstant.toString(), startInstant, qNames,
config.getElasticSearchRefreshExcludeQualifiedNames());
service = MoreExecutors
.listeningDecorator(newFixedThreadPool(10, "catalog-traversal-%d", queueSize));
actionService = MoreExecutors
.listeningDecorator(newFixedThreadPool(5, "catalog-traversal-action-service-%d", queueSize));
defaultService = Executors.newSingleThreadExecutor();
actions.forEach(a -> a.init(context));
supplier.get().get(24, TimeUnit.HOURS);
actions.forEach(a -> a.done(context));
log.info("End Traversal: Full catalog traversal");
} catch (Exception e) {
log.error("Traversal: Full catalog traversal failed", e);
registry.counter(registry.createId(Metrics.CounterCatalogTraversal.getMetricName())
.withTags(Metrics.tagStatusFailureMap)).increment();
} finally {
try {
shutdown(service);
shutdown(defaultService);
} finally {
isTraversalAlreadyRunning.set(false);
final long duration = registry.clock().wallTime() - start;
this.registry.timer(Metrics.TimerCatalogTraversal.getMetricName()
+ "." + requestName).record(duration, TimeUnit.MILLISECONDS);
log.info("### Time taken to complete {} is {} ms", requestName, duration);
}
actions.clear();
}
} else {
log.info("Traversal: Full catalog traversal is already running.");
registry.counter(registry.createId(Metrics.CounterCatalogTraversalAlreadyRunning.getMetricName()))
.increment();
}
}
private void shutdown(@Nullable final ExecutorService executorService) {
if (executorService != null) {
executorService.shutdown();
try {
// Wait a while for existing tasks to terminate
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
log.warn("Thread pool for metacat traversal did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executorService.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
log.info("Start: Full traversal of catalogs: {}", catalogNames);
final List<List<String>> subCatalogNamesList = Lists.partition(catalogNames, 5);
final List<ListenableFuture<Void>> futures =
subCatalogNamesList.stream().map(this::_processSubCatalogList).collect(Collectors.toList());
return Futures.transform(Futures.successfulAsList(futures), Functions.constant(null), defaultService);
}
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processSubCatalogList(final List<String> catalogNames) {
log.info("Start: Full traversal of catalogs: {}", catalogNames);
final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
.map(catalogName -> service.submit(() -> {
CatalogDto result = null;
try {
result = catalogTraversalServiceHelper.getCatalog(catalogName);
} catch (Exception e) {
log.error("Traversal: Failed to retrieve catalog: {}", catalogName);
registry.counter(
registry.createId(Metrics.CounterCatalogTraversalCatalogReadFailed.getMetricName())
.withTag("catalogName", catalogName))
.increment();
}
return result;
}))
.collect(Collectors.toList());
return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures),
input -> {
final ListenableFuture<Void> processCatalogFuture = applyCatalogs(input);
final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL).map(
catalogDto -> {
final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
return _processDatabases(catalogDto, databaseNames);
}).filter(NOT_NULL).collect(Collectors.toList());
processCatalogFutures.add(processCatalogFuture);
return Futures.transform(Futures.successfulAsList(processCatalogFutures),
Functions.constant(null), defaultService);
}, defaultService);
}
private List<QualifiedName> getDatabaseNamesToRefresh(final CatalogDto catalogDto) {
final List<QualifiedName> result = catalogDto.getDatabases().stream()
.map(n -> QualifiedName.ofDatabase(catalogDto.getName().getCatalogName(), n))
.collect(Collectors.toList());
final List<QualifiedName> excludeQNames = context.getExcludeQNames();
if (excludeQNames != null && !excludeQNames.isEmpty()) {
result.removeAll(excludeQNames);
}
return result;
}
/**
* Process the list of databases.
*
* @param catalogDto catalog dto
* @param databaseNames database names
* @return future
*/
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processDatabases(final CatalogDto catalogDto,
final List<QualifiedName> databaseNames) {
ListenableFuture<Void> resultFuture = null;
final QualifiedName catalogName = catalogDto.getName();
log.info("Traversal: Full traversal of catalog {} for databases({}): {}",
catalogName, databaseNames.size(), databaseNames);
final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream()
.map(databaseName -> service.submit(() -> {
DatabaseDto result = null;
try {
result = catalogTraversalServiceHelper.getDatabase(catalogDto, databaseName);
} catch (Exception e) {
log.error("Traversal: Failed to retrieve database: {}", databaseName);
registry.counter(
registry.createId(Metrics.CounterCatalogTraversalDatabaseReadFailed.getMetricName())
.withTags(databaseName.parts()))
.increment();
}
return result;
}))
.collect(Collectors.toList());
if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) {
resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures),
input -> {
final ListenableFuture<Void> processDatabaseFuture = applyDatabases(catalogName, input);
final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL)
.map(databaseDto -> {
final List<QualifiedName> tableNames = databaseDto.getTables().stream()
.map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(),
databaseDto.getName().getDatabaseName(), s))
.collect(Collectors.toList());
log.info("Traversal: Full traversal of database {} for tables({}): {}",
databaseDto.getName(),
databaseDto.getTables().size(), databaseDto.getTables());
return processTables(databaseDto, tableNames);
}).filter(NOT_NULL).collect(Collectors.toList());
processDatabaseFutures.add(processDatabaseFuture);
return Futures.transform(Futures.successfulAsList(processDatabaseFutures),
Functions.constant(null), defaultService);
}, defaultService);
}
return resultFuture;
}
/**
* Apply all catalogs to all registered actions.
*
* @param dtos catalog dtos
* @return future
*/
private ListenableFuture<Void> applyCatalogs(final List<CatalogDto> dtos) {
final List<ListenableFuture<Void>> actionFutures = actions.stream()
.map(a -> actionService.submit((Callable<Void>) () -> {
a.applyCatalogs(context, dtos);
return null;
})).collect(Collectors.toList());
return Futures.transform(Futures.successfulAsList(actionFutures),
Functions.constant(null), defaultService);
}
/**
* Apply all databases to all registered actions.
*
* @param name catalog name
* @param dtos database dtos
* @return future
*/
private ListenableFuture<Void> applyDatabases(final QualifiedName name, final List<DatabaseDto> dtos) {
log.info("Traversal: Apply databases for catalog: {}", name);
final List<ListenableFuture<Void>> actionFutures = actions.stream()
.map(a -> actionService.submit((Callable<Void>) () -> {
a.applyDatabases(context, dtos);
return null;
})).collect(Collectors.toList());
return Futures.transform(Futures.successfulAsList(actionFutures),
Functions.constant(null), defaultService);
}
/**
* Apply all tables to all registered actions.
*
* @param name database Name
* @param dtos table dtos
* @return future
*/
private ListenableFuture<Void> applyTables(final QualifiedName name, final List<Optional<TableDto>> dtos) {
log.info("Traversal: Apply tables for database: {}", name);
final List<ListenableFuture<Void>> actionFutures = actions.stream()
.map(a -> actionService.submit((Callable<Void>) () -> {
a.applyTables(context, dtos);
return null;
})).collect(Collectors.toList());
return Futures.transform(Futures.successfulAsList(actionFutures),
Functions.constant(null), defaultService);
}
/**
* Process the list of tables in batches.
*
* @param databaseDto database dto
* @param tableNames table names
* @return A future containing the tasks
*/
private ListenableFuture<Void> processTables(final DatabaseDto databaseDto,
final List<QualifiedName> tableNames) {
final List<List<QualifiedName>> tableNamesBatches = Lists.partition(tableNames, 500);
final List<ListenableFuture<Void>> processTablesBatchFutures = tableNamesBatches.stream().map(
subTableNames -> _processTables(databaseDto, subTableNames)).collect(Collectors.toList());
return Futures.transform(Futures.successfulAsList(processTablesBatchFutures),
Functions.constant(null), defaultService);
}
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processTables(final DatabaseDto databaseDto,
final List<QualifiedName> tableNames) {
final QualifiedName databaseName = databaseDto.getName();
final List<ListenableFuture<Optional<TableDto>>> getTableFutures = tableNames.stream()
.map(tableName -> service.submit(() -> {
Optional<TableDto> result = null;
try {
result = catalogTraversalServiceHelper.getTable(databaseDto, tableName);
} catch (Exception e) {
log.error("Traversal: Failed to retrieve table: {}", tableName);
registry.counter(
registry.createId(Metrics.CounterCatalogTraversalTableReadFailed.getMetricName())
.withTags(tableName.parts()))
.increment();
}
return result;
}))
.collect(Collectors.toList());
return Futures.transformAsync(Futures.successfulAsList(getTableFutures),
input -> applyTables(databaseName, input), defaultService);
}
/**
* Traversal context.
*/
@Data
@AllArgsConstructor
public static class Context {
private String runId;
private Instant startInstant;
private List<QualifiedName> qNames;
private List<QualifiedName> excludeQNames;
}
}
| 86 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MViewService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.netflix.metacat.common.NameDateDto;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.GetPartitionsRequestDto;
import com.netflix.metacat.common.dto.Pageable;
import com.netflix.metacat.common.dto.PartitionDto;
import com.netflix.metacat.common.dto.PartitionsSaveRequestDto;
import com.netflix.metacat.common.dto.PartitionsSaveResponseDto;
import com.netflix.metacat.common.dto.Sort;
import com.netflix.metacat.common.dto.TableDto;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;
/**
* View service.
*/
public interface MViewService extends MetacatService<TableDto> {
/**
* Create the view and returns the newly created view.
*
* @param name name of the origin table
* @return view
*/
TableDto create(QualifiedName name);
/**
* Create the view and returns the newly created view.
*
* @param name name of the origin table
* @param snapshot To snapshot a list of partitions of the table to this view.
* @param filter Filter expression string to use
* @return view
*/
TableDto createAndSnapshotPartitions(QualifiedName name, boolean snapshot, @Nullable String filter);
/**
* Deletes the view and returns the deleted view.
*
* @param name name of the view to be deleted
* @return deleted view
*/
TableDto deleteAndReturn(QualifiedName name);
/**
* Get the view for the given name.
*
* @param name name
* @param parameters getTable parameters
* @return view
*/
Optional<TableDto> getOpt(QualifiedName name, GetTableServiceParameters parameters);
/**
* Copy partitions from the given table name.
*
* @param name table name
* @param filter filter
*/
void snapshotPartitions(QualifiedName name, String filter);
/**
* Saves the list of partitions to the given view.
*
* @param name name
* @param partitionsSaveRequestDto request dto containing the partitions to be added and deleted
* @param merge if true, this method merges
* @return no. of partitions added and updated.
*/
PartitionsSaveResponseDto savePartitions(QualifiedName name,
PartitionsSaveRequestDto partitionsSaveRequestDto, boolean merge);
/**
* Deletes the list of partitions with the given ids <code>partitionIds</code>.
*
* @param name view name
* @param partitionIds partition names
*/
void deletePartitions(QualifiedName name, List<String> partitionIds);
/**
* Returns the list of partitions.
*
* @param name view name
* @param sort sort info
* @param pageable pagination info
* @param includeUserMetadata if true, includes the user metadata
* @param getPartitionsRequestDto get partitions request
* @return list of partitions
*/
List<PartitionDto> listPartitions(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
boolean includeUserMetadata,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto);
/**
* Returns a list of partition names.
*
* @param name view name
* @param sort sort info
* @param pageable pagination info
* @param getPartitionsRequestDto get partition request dto
* @return list of partition names
*/
List<String> getPartitionKeys(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto
);
/**
* Returns a list of partition uris.
*
* @param name view name
* @param sort sort info
* @param pageable pagination info
* @param getPartitionsRequestDto get partition request dto
* @return list of partition uris
*/
List<String> getPartitionUris(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto);
/**
* Partition count for the given view name.
*
* @param name view name
* @return no. of partitions
*/
Integer partitionCount(QualifiedName name);
/**
* Returns the list of view names for the given name.
*
* @param qualifiedName name
* @return list of view names
*/
List<NameDateDto> list(QualifiedName qualifiedName);
/**
* Save metadata for the view.
*
* @param name view name
* @param definitionMetadata definition metadata
* @param dataMetadata data metadata
*/
void saveMetadata(QualifiedName name, ObjectNode definitionMetadata, ObjectNode dataMetadata);
/**
* Rename view.
*
* @param name view name
* @param newViewName new view name
*/
void rename(QualifiedName name, QualifiedName newViewName);
}
| 87 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/GetTableNamesServiceParameters.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import lombok.Builder;
import lombok.Value;
/**
* GetTableNames Parameters.
*
* @author amajumdar
* @since 1.3.0
*/
@Value
@Builder
public class GetTableNamesServiceParameters {
private final String filter;
private final Integer limit;
}
| 88 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/CatalogTraversalServiceHelper.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.CatalogDto;
import com.netflix.metacat.common.dto.CatalogMappingDto;
import com.netflix.metacat.common.dto.DatabaseDto;
import com.netflix.metacat.common.dto.TableDto;
import lombok.NonNull;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service helper class for catalog traversal.
*/
public class CatalogTraversalServiceHelper {
protected final CatalogService catalogService;
protected final TableService tableService;
protected final DatabaseService databaseService;
/**
* Constructor.
*
* @param catalogService Catalog service
* @param databaseService Database service
* @param tableService Table service
*/
public CatalogTraversalServiceHelper(
@Nonnull @NonNull final CatalogService catalogService,
@Nonnull @NonNull final DatabaseService databaseService,
@Nonnull @NonNull final TableService tableService
) {
this.catalogService = catalogService;
this.databaseService = databaseService;
this.tableService = tableService;
}
/**
* Returns the list of catalog names.
* @return list of catalog names
*/
public List<String> getCatalogNames() {
return catalogService.getCatalogNames().stream().map(CatalogMappingDto::getCatalogName).collect(
Collectors.toList());
}
/**
* Returns the catalog for the given <code>name</code>.
* @param catalogName catalog name
* @return catalog
*/
public CatalogDto getCatalog(final String catalogName) {
return catalogService.get(QualifiedName.ofCatalog(catalogName));
}
/**
* Returns the database for the given <code>databaseName</code>.
* @param catalogDto catalog dto
* @param databaseName database name
* @return database
*/
public DatabaseDto getDatabase(final CatalogDto catalogDto, final QualifiedName databaseName) {
return databaseService.get(databaseName,
GetDatabaseServiceParameters.builder()
.disableOnReadMetadataIntercetor(false)
.includeTableNames(true)
.includeUserMetadata(true)
.build());
}
/**
* Returns the table for the given <code>tableName</code>.
* @param databaseDto database dto
* @param tableName table name
* @return table dto
*/
public Optional<TableDto> getTable(final DatabaseDto databaseDto, final QualifiedName tableName) {
return tableService.get(tableName, GetTableServiceParameters.builder()
.disableOnReadMetadataIntercetor(false)
.includeInfo(true)
.includeDefinitionMetadata(true)
.includeDataMetadata(true)
.build());
}
}
| 89 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/DatabaseService.java | /*
* Copyright 2017 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.DatabaseDto;
/**
* Database service.
*/
public interface DatabaseService extends MetacatService<DatabaseDto> {
/**
* Gets the database with the given name.
* @param name qualified name of the table
* @param getDatabaseServiceParameters get table request
* @return database info with the given name
*/
DatabaseDto get(QualifiedName name, GetDatabaseServiceParameters getDatabaseServiceParameters);
}
| 90 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MetadataService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.BaseDto;
import com.netflix.metacat.common.dto.DefinitionMetadataDto;
import com.netflix.metacat.common.server.connectors.exception.NotFoundException;
import com.netflix.metacat.common.server.monitoring.Metrics;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.TagService;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.spectator.api.Registry;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Metadata Service. This class includes any common services for the user metadata.
*
* @author amajumdar
*/
@Slf4j
@Getter
public class MetadataService {
private final Config config;
private final TableService tableService;
private final PartitionService partitionService;
private final UserMetadataService userMetadataService;
private final TagService tagService;
private final MetacatServiceHelper helper;
private final Registry registry;
/**
* Constructor.
*
* @param config configuration
* @param tableService table service
* @param partitionService partition service
* @param userMetadataService user metadata service
* @param tagService tag service
* @param helper service helper
* @param registry registry
*/
public MetadataService(final Config config,
final TableService tableService,
final PartitionService partitionService,
final UserMetadataService userMetadataService,
final TagService tagService,
final MetacatServiceHelper helper,
final Registry registry) {
this.config = config;
this.tableService = tableService;
this.partitionService = partitionService;
this.userMetadataService = userMetadataService;
this.tagService = tagService;
this.helper = helper;
this.registry = registry;
}
/**
* Deletes all the data metadata marked for deletion.
*/
public void cleanUpDeletedDataMetadata() {
// Get the data metadata that were marked deleted a number of days back
// Check if the uri is being used
// If uri is not used then delete the entry from data_metadata
log.info("Start deleting data metadata");
try {
final DateTime priorTo = DateTime.now().minusDays(config.getDataMetadataDeleteMarkerLifetimeInDays());
final int limit = 100000;
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
while (true) {
final List<String> urisToDelete =
userMetadataService.getDeletedDataMetadataUris(priorTo.toDate(), 0, limit);
log.info("Count of deleted marked data metadata: {}", urisToDelete.size());
if (urisToDelete.size() > 0) {
final List<String> uris = urisToDelete.parallelStream().filter(uri -> !uri.contains("="))
.map(userMetadataService::getDescendantDataUris)
.flatMap(Collection::stream).collect(Collectors.toList());
uris.addAll(urisToDelete);
log.info("Count of deleted marked data metadata (including descendants) : {}", uris.size());
final List<List<String>> subListsUris = Lists.partition(uris, 1000);
subListsUris.parallelStream().forEach(subUris -> {
MetacatContextManager.setContext(metacatRequestContext);
final Map<String, List<QualifiedName>> uriPartitionQualifiedNames = partitionService
.getQualifiedNames(subUris, false);
final Map<String, List<QualifiedName>> uriTableQualifiedNames = tableService
.getQualifiedNames(subUris, false);
final Map<String, List<QualifiedName>> uriQualifiedNames =
Stream.concat(uriPartitionQualifiedNames.entrySet().stream(),
uriTableQualifiedNames.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {
final List<QualifiedName> subNames = Lists.newArrayList(a);
subNames.addAll(b);
return subNames;
}));
final List<String> canDeleteMetadataForUris = subUris.parallelStream()
.filter(s -> !Strings.isNullOrEmpty(s))
.filter(s -> uriQualifiedNames.get(s) == null || uriQualifiedNames.get(s).size() == 0)
.collect(Collectors.toList());
log.info("Start deleting data metadata: {}", canDeleteMetadataForUris.size());
userMetadataService.deleteDataMetadata(canDeleteMetadataForUris);
userMetadataService.deleteDataMetadataDeletes(subUris);
MetacatContextManager.removeContext();
});
}
if (urisToDelete.size() < limit) {
break;
}
}
} catch (Exception e) {
registry.counter(Metrics.CounterDeleteMetaData.getMetricName()).increment();
log.warn("Failed deleting data metadata", e);
}
log.info("End deleting data metadata");
}
/**
* Deletes definition metadata of tables/views/partitions that have been deleted already.
*/
public void cleanUpObsoleteDefinitionMetadata() {
log.info("Start deleting obsolete definition metadata");
final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
List<DefinitionMetadataDto> dtos = null;
int offset = 0;
final int limit = 10000;
int totalDeletes = 0;
while (offset == 0 || dtos.size() == limit) {
dtos = userMetadataService.searchDefinitionMetadata(null, null, null, null,
"id", null, offset, limit);
final long deletes = dtos.parallelStream().map(dto -> {
try {
return deleteDefinitionMetadata(dto.getName(), false, metacatRequestContext);
} catch (Exception e) {
log.warn("Failed deleting obsolete definition metadata for table {}", dto.getName(), e);
return false;
}
})
.filter(b -> b).count();
totalDeletes += deletes;
offset += limit - deletes;
}
log.info("End deleting obsolete definition metadata. Deleted {} number of definition metadatas", totalDeletes);
}
/**
* Deletes definition metadata for the given <code>name</code>.
*
* @param name qualified name
* @param force If true, deletes the metadata without checking if database/table/partition exists
* @param metacatRequestContext request context
* @return true if deleted
*/
public boolean deleteDefinitionMetadata(final QualifiedName name, final boolean force,
final MetacatRequestContext metacatRequestContext) {
try {
final MetacatService service = this.helper.getService(name);
BaseDto dto = null;
if (!force) {
try {
dto = service.get(name);
} catch (final NotFoundException ignored) {
}
}
if ((force || dto == null) && !"rds".equalsIgnoreCase(name.getCatalogName())) {
if (dto != null) {
this.helper.postPreUpdateEvent(name, metacatRequestContext, dto);
} else {
this.helper.postPreDeleteEvent(name, metacatRequestContext);
}
this.userMetadataService.deleteDefinitionMetadata(Lists.newArrayList(name));
this.tagService.delete(name, false);
log.info("Deleted definition metadata for {}", name);
if (dto != null) {
final BaseDto newDto = service.get(name);
this.helper.postPostUpdateEvent(name, metacatRequestContext, dto, newDto);
} else {
this.helper.postPostDeleteEvent(name, metacatRequestContext);
}
return true;
}
} catch (Exception e) {
log.warn("Failed deleting definition metadata for name {}.", name, e);
throw e;
}
return false;
}
/**
* Deletes tags for deleted tables.
*/
public void cleanUpObsoleteTags() {
log.info("Start deleting obsolete tags");
final List<QualifiedName> names = tagService.list(null, null, null, null, null,
null);
names.forEach(name -> {
if (!name.isPartitionDefinition() && !name.isViewDefinition() && name.isTableDefinition()
&& !tableService.exists(name)) {
this.tagService.delete(name, false);
log.info("Deleted obsolete tag for {}", name);
}
});
log.info("End deleting obsolete tags");
}
}
| 91 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/MViewServiceEventHandler.java |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.NameDateDto;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.server.events.AsyncListener;
import com.netflix.metacat.common.server.events.MetacatDeleteTablePostEvent;
import com.netflix.metacat.common.server.events.MetacatRenameTablePostEvent;
import com.netflix.metacat.common.server.properties.Config;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Event handler for view changes based on table changes.
*
* @author amajumdar
*/
@Slf4j
@Component
@AsyncListener
public class MViewServiceEventHandler {
private final Config config;
private final MViewService mViewService;
private final UserMetadataService userMetadataService;
/**
* Default constructor.
* @param config server configurations
* @param mViewService view service
* @param userMetadataService user metadata service
*/
@Autowired
public MViewServiceEventHandler(final Config config,
final MViewService mViewService,
final UserMetadataService userMetadataService) {
this.config = config;
this.mViewService = mViewService;
this.userMetadataService = userMetadataService;
}
/**
* Subscriber.
*
* @param event event
*/
@EventListener
public void metacatDeleteTablePostEventHandler(final MetacatDeleteTablePostEvent event) {
if (config.canCascadeViewsMetadataOnTableDelete() && !event.isMView()) {
final QualifiedName name = event.getTable().getName();
try {
// delete views associated with this table
final List<NameDateDto> viewNames = mViewService.list(name);
viewNames.forEach(viewName -> mViewService.deleteAndReturn(viewName.getName()));
} catch (Exception e) {
log.warn("Failed cleaning mviews after deleting table {}", name);
}
// delete table partitions metadata
try {
final List<QualifiedName> names = userMetadataService.getDescendantDefinitionNames(name);
if (names != null && !names.isEmpty()) {
userMetadataService.deleteDefinitionMetadata(names);
}
} catch (Exception e) {
log.warn("Failed cleaning partition definition metadata after deleting table {}", name);
}
}
}
/**
* Subscriber.
*
* @param event event
*/
@EventListener
public void metacatRenameTablePostEventHandler(final MetacatRenameTablePostEvent event) {
if (!event.isMView()) {
final QualifiedName oldName = event.getOldTable().getName();
final QualifiedName newName = event.getCurrentTable().getName();
final List<NameDateDto> views = mViewService.list(oldName);
if (views != null && !views.isEmpty()) {
views.forEach(view -> {
final QualifiedName newViewName = QualifiedName
.ofView(oldName.getCatalogName(), oldName.getDatabaseName(), newName.getTableName(),
view.getName().getViewName());
mViewService.rename(view.getName(), newViewName);
});
}
}
}
}
| 92 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/CatalogService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.CatalogDto;
import com.netflix.metacat.common.dto.CatalogMappingDto;
import com.netflix.metacat.common.dto.CreateCatalogDto;
import javax.annotation.Nonnull;
import java.util.List;
/**
* Catalog service.
*/
public interface CatalogService {
/**
* Gets the catalog.
* @param name Qualified name of the catalog
* @return the information about the given catalog
*/
@Nonnull
CatalogDto get(QualifiedName name);
/**
* Gets the catalog. Returned dto will have details if asked.
* @param name Qualified name of the catalog
* @param getCatalogServiceParameters parameters
* @return the information about the given catalog
*/
@Nonnull
CatalogDto get(QualifiedName name, GetCatalogServiceParameters getCatalogServiceParameters);
/**
* List of registered catalogs.
* @return all of the registered catalogs
*/
@Nonnull
List<CatalogMappingDto> getCatalogNames();
/**
* Updates the catalog.
* @param name Qualified name of the catalog
* @param createCatalogDto catalog
*/
void update(QualifiedName name, CreateCatalogDto createCatalogDto);
}
| 93 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/GetCatalogServiceParameters.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import lombok.Builder;
import lombok.Value;
/**
* Get Catalog Parameters.
*
* @author amajumdar
* @since 1.2.0
*/
@Value
@Builder
public class GetCatalogServiceParameters {
private final boolean includeDatabaseNames;
private final boolean includeUserMetadata;
private final boolean includeMetadataFromConnector;
}
| 94 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/GetDatabaseServiceParameters.java | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.main.services;
import lombok.Builder;
import lombok.Value;
/**
* Getdatabase Parameters.
* @author zhenl
* @since 1.2.0
*/
@Value
@Builder
public class GetDatabaseServiceParameters {
private final boolean disableOnReadMetadataIntercetor;
private final boolean includeTableNames;
private final boolean includeUserMetadata;
private final boolean includeMetadataFromConnector;
}
| 95 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/TableService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.TableDto;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Table service.
*/
public interface TableService extends MetacatService<TableDto> {
/**
* Deletes the table. Returns the table metadata of the table deleted.
* @param name qualified name of the table to be deleted
* @param isMView true if this table is created for a mview
* @return Returns the deleted table
*/
TableDto deleteAndReturn(QualifiedName name, boolean isMView);
/**
* Returns the table with the given name.
* @param name qualified name of the table
* @param getTableServiceParameters get table parameters
* @return Returns the table with the given name
*/
Optional<TableDto> get(QualifiedName name, GetTableServiceParameters getTableServiceParameters);
/**
* Rename the table from <code>oldName</code> to <code>newName</code>.
* @param oldName old qualified name of the existing table
* @param newName new qualified name of the table
* @param isMView true, if the object is a view
*/
void rename(QualifiedName oldName, QualifiedName newName, boolean isMView);
/**
* Copies the table metadata from source table <code>name</code> to target table <code>targetName</code>.
* @param name qualified name of the source table
* @param targetName qualified name of the target table
* @return Returns the copied table
*/
TableDto copy(QualifiedName name, QualifiedName targetName);
/**
* Copies the table metadata from source table <code>name</code> to target table <code>targetName</code>.
* @param tableDto source table
* @param targetName qualified name of the target table
* @return Returns the copied table
*/
TableDto copy(TableDto tableDto, QualifiedName targetName);
/**
* Saves the user metadata for the given table.
* @param name qualified name of the table
* @param definitionMetadata user definition metadata json
* @param dataMetadata user data metadata json
*/
void saveMetadata(QualifiedName name, ObjectNode definitionMetadata, ObjectNode dataMetadata);
/**
* Returns a list of qualified names of tables that refers to the given <code>uri</code>. If prefixSearch is true,
* it will consider the uri has a prefix and so it does not do a exact match.
* @param uri uri/location
* @param prefixSearch if false, the method looks for exact match for the uri
* @return list of table names
*/
List<QualifiedName> getQualifiedNames(String uri, boolean prefixSearch);
/**
* Returns a map of list of qualified names of tables that refers to the given <code>uri</code>.
* If prefixSearch is true, it will consider the uri has a prefix and so it does not do a exact match.
* @param uris uris/locations
* @param prefixSearch if false, the method looks for exact match for the uri
* @return Map of list of table names
*/
Map<String, List<QualifiedName>> getQualifiedNames(List<String> uris, boolean prefixSearch);
/**
* Returns a list of qualified names of tables that matches the given filter.
* @param name catalog name
* @param parameters parameters used to get the table names
* @return list of table names
*/
List<QualifiedName> getQualifiedNames(QualifiedName name, GetTableNamesServiceParameters parameters);
}
| 96 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/OwnerValidationService.java | package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.TableDto;
import lombok.NonNull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
/**
* Interface for validating table owner attribute.
*/
public interface OwnerValidationService {
/**
* Returns an ordered list of owners to use used for validation and owner assignment. Since metacat owners
* in a request may come from a number of places (DTO, Request context) this method centralizes that order.
*
* @param dto the input Table Dto
* @return an ordered list of owners to use used for validation and owner assignment
*/
List<String> extractPotentialOwners(@NonNull TableDto dto);
/**
* Returns an ordered list of owner groups to use used for validation and owner assignment. Since metacat owners
* in a request may come from a number of places (DTO, Request context) this method centralizes that order.
*
* @param dto the input Table Dto
* @return an ordered list of owner groups to use used for validation and owner assignment
*/
default List<String> extractPotentialOwnerGroups(@NonNull TableDto dto) {
return Collections.emptyList();
}
/**
* Checks whether the given owner is valid against a registry.
*
* @param user the user
* @return true if the owner is valid, else false
*/
boolean isUserValid(@Nullable String user);
/**
* Checks whether the given owner group is valid against a registry.
*
* @param groupName the groupName
* @return true if the owner group is valid, else false
*/
default boolean isGroupValid(@Nullable String groupName) {
return true;
}
/**
* Enforces valid table owner attribute. Implementations are free to
* handle it as needed - throw exceptions or ignore. The owner attribute
* in the DTO may or may not be valid so implementations should check for validity
* before enforcement.
*
* @param operationName the name of the metacat API, useful for logging
* @param tableName the name of the table
* @param tableDto the table dto containing the owner in the definition metadata field
*/
void enforceOwnerValidation(@NonNull String operationName,
@NonNull QualifiedName tableName,
@NonNull TableDto tableDto);
}
| 97 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/PartitionService.java | /*
* Copyright 2016 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.metacat.main.services;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.GetPartitionsRequestDto;
import com.netflix.metacat.common.dto.Pageable;
import com.netflix.metacat.common.dto.PartitionDto;
import com.netflix.metacat.common.dto.PartitionsSaveRequestDto;
import com.netflix.metacat.common.dto.PartitionsSaveResponseDto;
import com.netflix.metacat.common.dto.Sort;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
/**
* Partition service.
*/
public interface PartitionService extends MetacatService<PartitionDto> {
/**
* Returns the list of partitions.
*
* @param name table name
* @param sort sort info
* @param pageable pagination info
* @param includeUserDefinitionMetadata if true, includes the definition metadata
* @param includeUserDataMetadata if true, includes the data metadata
* @param getPartitionsRequestDto getPartitionsRequestDto
* @return list of partitions
*/
List<PartitionDto> list(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
boolean includeUserDefinitionMetadata,
boolean includeUserDataMetadata,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto);
/**
* Partition count for the given table name.
*
* @param name table name
* @return no. of partitions
*/
Integer count(QualifiedName name);
/**
* Saves the list of partitions to the given table <code>name</code>. By default, if a partition exists, it drops
* the partition before adding it. If <code>alterIfExists</code> is true, then it will alter the partition.
*
* @param name table name
* @param partitionsSaveRequestDto request dto containing the partitions to be added and deleted
* @return no. of partitions added and updated.
*/
PartitionsSaveResponseDto save(QualifiedName name, PartitionsSaveRequestDto partitionsSaveRequestDto);
/**
* Deletes the partitions with the given <code>partitionIds</code> for the given table name.
*
* @param name table name
* @param partitionIds partition names
*/
void delete(QualifiedName name, List<String> partitionIds);
/**
* Returns the qualified names of partitions that refer to the given uri.
*
* @param uri uri
* @param prefixSearch if true, this method does a prefix search
* @return list of names
*/
List<QualifiedName> getQualifiedNames(String uri, boolean prefixSearch);
/**
* Returns a map of uri to qualified names.
*
* @param uris list of uris
* @param prefixSearch if true, this method does a prefix search
* @return map of uri to qualified names
*/
Map<String, List<QualifiedName>> getQualifiedNames(List<String> uris, boolean prefixSearch);
/**
* Returns a list of partition names.
*
* @param name table name
* @param sort sort info
* @param pageable pagination info
* @param getPartitionsRequestDto get partition request dto
* @return list of partition names
*/
List<String> getPartitionKeys(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto);
/**
* Returns a list of partition uris.
*
* @param name table name
* @param sort sort info
* @param pageable pagination info
* @param getPartitionsRequestDto get partition request dto
* @return list of partition uris
*/
List<String> getPartitionUris(
QualifiedName name,
@Nullable Sort sort,
@Nullable Pageable pageable,
@Nullable GetPartitionsRequestDto getPartitionsRequestDto);
}
| 98 |
0 | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main | Create_ds/metacat/metacat-main/src/main/java/com/netflix/metacat/main/services/package-info.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* This package includes services.
*
* @author amajumdar
*/
@ParametersAreNonnullByDefault
package com.netflix.metacat.main.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 99 |
Subsets and Splits