index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/metacat/metacat-connector-s3/src/main/java/com/netflix/metacat/connector/s3
Create_ds/metacat/metacat-connector-s3/src/main/java/com/netflix/metacat/connector/s3/model/Field.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.connector.s3.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.UniqueConstraint; /** * Field. */ @Entity @javax.persistence.Table(name = "field", uniqueConstraints = @UniqueConstraint(name = "field_u1", columnNames = { "schema_id", "name", "pos" })) public class Field extends IdEntity { private int pos; private String name; private String type; private String sourceType; private String comment; private boolean partitionKey; private Schema schema; @Column(name = "pos", nullable = false) public int getPos() { return pos; } public void setPos(final int pos) { this.pos = pos; } @Column(name = "name", nullable = false) public String getName() { return name; } public void setName(final String name) { this.name = name; } @Column(name = "type", nullable = false, length = 4000) public String getType() { return type; } public void setType(final String type) { this.type = type; } @Column(name = "source_type", nullable = true) public String getSourceType() { return sourceType; } public void setSourceType(final String sourceType) { this.sourceType = sourceType; } @Column(name = "comment", nullable = true) public String getComment() { return comment; } public void setComment(final String comment) { this.comment = comment; } @Column(name = "partition_key", nullable = false) public boolean isPartitionKey() { return partitionKey; } public void setPartitionKey(final boolean partitionKey) { this.partitionKey = partitionKey; } @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "schema_id", nullable = false) public Schema getSchema() { return schema; } public void setSchema(final Schema schema) { this.schema = schema; } }
1,700
0
Create_ds/metacat/metacat-connector-s3/src/main/java/com/netflix/metacat/connector/s3
Create_ds/metacat/metacat-connector-s3/src/main/java/com/netflix/metacat/connector/s3/model/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 s3 connector model classes. * * @author amajumdar */ package com.netflix.metacat.connector.s3.model;
1,701
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/NameDateDto.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.common; import com.netflix.metacat.common.dto.BaseDto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Date; /** * DTO containing the qualified name and the audit info. * * @author amajumdar */ @Data @EqualsAndHashCode(callSuper = false) public class NameDateDto extends BaseDto { private static final long serialVersionUID = -5713826608609231492L; @ApiModelProperty(value = "The date the entity was created") private Date createDate; @ApiModelProperty(value = "The date the entity was last updated") private Date lastUpdated; @ApiModelProperty(value = "The entity's name", required = true) private QualifiedName name; }
1,702
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/QualifiedName.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.common; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.JsonNode; import com.netflix.metacat.common.dto.PartitionDto; import lombok.Getter; import lombok.NonNull; import javax.annotation.Nullable; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * A fully qualified name that references a source of data. * * @author amajumdar */ @Getter public final class QualifiedName implements Serializable { private static final long serialVersionUID = -7916364073519921672L; private static final String CATALOG_CDE_NAME_PREFIX = "cde_"; private final String catalogName; private final String databaseName; private final String partitionName; private final String tableName; private final String viewName; private final Type type; private QualifiedName( @NonNull final String catalogName, @Nullable final String databaseName, @Nullable final String tableName, @Nullable final String partitionName, @Nullable final String viewName ) { this.catalogName = standardizeRequired("catalogName", catalogName); // TODO: Temporary hack to support a certain catalog that has mixed case naming. final boolean forceLowerCase = !catalogName.startsWith(CATALOG_CDE_NAME_PREFIX); this.databaseName = standardizeOptional(databaseName, forceLowerCase); this.tableName = standardizeOptional(tableName, forceLowerCase); this.partitionName = standardizeOptional(partitionName, false); this.viewName = standardizeOptional(viewName, forceLowerCase); if (this.databaseName.isEmpty() && (!this.tableName.isEmpty() || !this.partitionName.isEmpty())) { throw new IllegalStateException("databaseName is not present but tableName or partitionName are present"); } else if (this.tableName.isEmpty() && !this.partitionName.isEmpty()) { throw new IllegalStateException("tableName is not present but partitionName is present"); } if (!this.viewName.isEmpty()) { type = Type.MVIEW; } else if (!this.partitionName.isEmpty()) { type = Type.PARTITION; } else if (!this.tableName.isEmpty()) { type = Type.TABLE; } else if (!this.databaseName.isEmpty()) { type = Type.DATABASE; } else { type = Type.CATALOG; } } private QualifiedName( @NonNull final String catalogName, @Nullable final String databaseName, @Nullable final String tableName, @Nullable final String partitionName, @Nullable final String viewName, @NonNull final Type type) { this.catalogName = catalogName; this.databaseName = databaseName; this.partitionName = partitionName; this.tableName = tableName; this.viewName = viewName; this.type = type; } /** * Creates the name from the json. * * @param node json node * @return qualified name */ @JsonCreator public static QualifiedName fromJson(@NonNull final JsonNode node) { final JsonNode catalogNameNode = node.path("catalogName"); if (catalogNameNode.isMissingNode() || catalogNameNode.isNull() || !catalogNameNode.isTextual()) { // If catalogName is not present try to load from the qualifiedName node instead final JsonNode nameNode = node.path("qualifiedName"); if (!nameNode.isNull() && nameNode.isTextual()) { return fromString(nameNode.asText(), false); } else { // if neither are available throw an exception throw new IllegalStateException("Node '" + node + "' is missing catalogName"); } } final String catalogName = catalogNameNode.asText(); final JsonNode databaseNameNode = node.path("databaseName"); String databaseName = null; if (databaseNameNode != null) { databaseName = databaseNameNode.asText(); } final JsonNode tableNameNode = node.path("tableName"); String tableName = null; if (tableNameNode != null) { tableName = tableNameNode.asText(); } final JsonNode partitionNameNode = node.path("partitionName"); String partitionName = null; if (partitionNameNode != null) { partitionName = partitionNameNode.asText(); } final JsonNode viewNameNode = node.path("viewName"); String viewName = null; if (viewNameNode != null) { viewName = viewNameNode.asText(); } return new QualifiedName(catalogName, databaseName, tableName, partitionName, viewName); } /** * Creates the qualified name from text. * * @param s name * @return qualified name */ public static QualifiedName fromString(@NonNull final String s) { return fromString(s, false); } /** * Creates the qualified name from text. * * @param s name * @param isView true if it represents a view * @return qualified name */ public static QualifiedName fromString(@NonNull final String s, final boolean isView) { //noinspection ConstantConditions final String name = s.trim(); if (name.isEmpty()) { throw new IllegalArgumentException("passed in an empty definition name"); } final String[] parts = name.split("/", 4); switch (parts.length) { case 1: return ofCatalog(parts[0]); case 2: return ofDatabase(parts[0], parts[1]); case 3: return ofTable(parts[0], parts[1], parts[2]); case 4: if (isView || !parts[3].contains("=")) { return ofView(parts[0], parts[1], parts[2], parts[3]); } else { return ofPartition(parts[0], parts[1], parts[2], parts[3]); } default: throw new IllegalArgumentException("Unable to convert '" + s + "' into a qualifiedDefinition"); } } /** * Returns a copy of this qualified name with the database/table/view names in upper case. * * @return QualifiedName */ public QualifiedName cloneWithUpperCase() { return new QualifiedName(catalogName, databaseName == null ? null : databaseName.toUpperCase(), tableName == null ? null : tableName.toUpperCase(), partitionName, viewName == null ? null : viewName.toUpperCase(), type); } /** * Creates the qualified name representing a catalog. * * @param catalogName catalog name * @return qualified name */ public static QualifiedName ofCatalog(@NonNull final String catalogName) { return new QualifiedName(catalogName, null, null, null, null); } /** * Creates the qualified name representing a database. * * @param catalogName catalog name * @param databaseName database name * @return qualified name */ public static QualifiedName ofDatabase( @NonNull final String catalogName, @NonNull final String databaseName ) { return new QualifiedName(catalogName, databaseName, null, null, null); } /** * Creates the qualified name representing a view. * * @param catalogName catalog name * @param databaseName database name * @param tableName table name * @param viewName view name * @return qualified name */ public static QualifiedName ofView( @NonNull final String catalogName, @NonNull final String databaseName, @NonNull final String tableName, @NonNull final String viewName ) { return new QualifiedName(catalogName, databaseName, tableName, null, viewName); } /** * Creates the qualified name representing a partition. * * @param tableName table name * @param partitionDto partition * @return qualified name */ public static QualifiedName ofPartition( @NonNull final QualifiedName tableName, @NonNull final PartitionDto partitionDto ) { return ofPartition( tableName.catalogName, tableName.databaseName, tableName.tableName, partitionDto.getName().getPartitionName() ); } /** * Creates the qualified name representing a partition. * * @param catalogName catalog name * @param databaseName database name * @param tableName table name * @param partitionName partition name * @return qualified name */ public static QualifiedName ofPartition( @NonNull final String catalogName, @NonNull final String databaseName, @NonNull final String tableName, @NonNull final String partitionName ) { return new QualifiedName(catalogName, databaseName, tableName, partitionName, null); } /** * Creates the qualified name representing a table. * * @param catalogName catalog name * @param databaseName database name * @param tableName table name * @return qualified name */ public static QualifiedName ofTable( @NonNull final String catalogName, @NonNull final String databaseName, @NonNull final String tableName ) { return new QualifiedName(catalogName, databaseName, tableName, null, null); } /** * Creates a wild card string format of the qualified name. * * @param sourceName catalog/source name * @param databaseName database name * @param tableName table name * @return wild card string format of the qualified name */ public static String toWildCardString( @Nullable final String sourceName, @Nullable final String databaseName, @Nullable final String tableName ) { if (sourceName == null && databaseName == null && tableName == null) { return null; } final StringBuilder builder = new StringBuilder(); if (sourceName != null) { builder.append(sourceName); } else { builder.append('%'); } if (databaseName != null) { builder.append('/').append(databaseName); } else { builder.append("/%"); } if (tableName != null) { builder.append('/').append(tableName); } else { builder.append("/%"); } builder.append('%'); return builder.toString(); } /** * Change the qualified name query parameter to wildcard query string to allow source/database/table * like queries. It uses '%' to represent the other field if not provided. e.g. * query database like string is '%/database/%' * query catalog and database like string is 'catalog/database/%' * * @param sourceName source name * @param databaseName database name * @param tableName table name * @return query string */ public static String qualifiedNameToWildCardQueryString( @Nullable final String sourceName, @Nullable final String databaseName, @Nullable final String tableName ) { if (sourceName == null && databaseName == null && tableName == null) { return null; } final StringBuilder builder = new StringBuilder(); if (!isNullOrEmpty(sourceName)) { builder.append(sourceName); } else { builder.append('%'); } if (isNullOrEmpty(databaseName) && isNullOrEmpty(tableName)) { return builder.append('%').toString(); //query source level } if (!isNullOrEmpty(databaseName)) { builder.append('/').append(databaseName); } else { builder.append("/%"); } if (isNullOrEmpty(tableName)) { return builder.append('%').toString(); //database level query } else { builder.append('/').append(tableName); } builder.append('%'); return builder.toString(); } /** * Get the catalog name. * * @return The catalog name */ public String getCatalogName() { return this.catalogName; } /** * Returns the database name. * * @return database name */ public String getDatabaseName() { // TODO: This is a bad exception to throw. If its truly an illegal state exception we shouldn't allow that // object to be built. if (this.databaseName.isEmpty()) { throw new IllegalStateException("This is not a database definition"); } return this.databaseName; } /** * Returns the partition name. * * @return partition name */ public String getPartitionName() { // TODO: This is a bad exception to throw. If its truly an illegal state exception we shouldn't allow that // object to be built. if (partitionName.isEmpty()) { throw new IllegalStateException("This is not a partition definition"); } return partitionName; } /** * Returns the table name. * * @return table name */ public String getTableName() { // TODO: This is a bad exception to throw. If its truly an illegal state exception we shouldn't allow that // object to be built. if (tableName.isEmpty()) { throw new IllegalStateException("This is not a table definition"); } return tableName; } /** * Returns whether other is prefix of this. * * @param other the other QualifiedName * @return whether other is prefix */ public boolean startsWith(final QualifiedName other) { return other == null ? true : toString().startsWith(other.toString()); } public boolean isCatalogDefinition() { return !catalogName.isEmpty(); } public boolean isDatabaseDefinition() { return !databaseName.isEmpty(); } public boolean isPartitionDefinition() { return !partitionName.isEmpty(); } public boolean isTableDefinition() { return !tableName.isEmpty(); } private static String standardizeOptional(@Nullable final String value, final boolean forceLowerCase) { if (value == null) { return ""; } else { String returnValue = value.trim(); if (forceLowerCase) { returnValue = returnValue.toLowerCase(); } return returnValue; } } private static String standardizeRequired(final String name, @Nullable final String value) { if (value == null) { throw new IllegalStateException(name + " cannot be null"); } final String returnValue = value.trim(); if (returnValue.isEmpty()) { throw new IllegalStateException(name + " cannot be an empty string"); } return returnValue.toLowerCase(); } /** * Returns the qualified name in the JSON format. * * @return qualified name */ @JsonValue public Map<String, String> toJson() { final Map<String, String> map = new HashMap<>(5); map.put("qualifiedName", toString()); map.put("catalogName", catalogName); if (!databaseName.isEmpty()) { map.put("databaseName", databaseName); } if (!tableName.isEmpty()) { map.put("tableName", tableName); } if (!partitionName.isEmpty()) { map.put("partitionName", partitionName); } if (!viewName.isEmpty()) { map.put("viewName", viewName); } return map; } /** * Returns the qualified name in parts. * * @return parts of the qualified name as a Map */ public Map<String, String> parts() { final Map<String, String> map = new HashMap<>(5); map.put("catalogName", catalogName); if (!databaseName.isEmpty()) { map.put("databaseName", databaseName); } if (!tableName.isEmpty()) { map.put("tableName", tableName); } if (!partitionName.isEmpty()) { map.put("partitionName", partitionName); } if (!viewName.isEmpty()) { map.put("viewName", viewName); } return map; } public boolean isViewDefinition() { return !viewName.isEmpty(); } // TODO: Replace custom equals and hashcode with generated. Tried but broke tests. /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof QualifiedName)) { return false; } final QualifiedName that = (QualifiedName) o; return Objects.equals(catalogName, that.catalogName) && Objects.equals(databaseName, that.databaseName) && Objects.equals(partitionName, that.partitionName) && Objects.equals(tableName, that.tableName) && Objects.equals(viewName, that.viewName); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(catalogName, databaseName, partitionName, tableName, viewName); } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(catalogName); if (!databaseName.isEmpty()) { sb.append('/'); sb.append(databaseName); } if (!tableName.isEmpty()) { sb.append('/'); sb.append(tableName); } if (!partitionName.isEmpty()) { sb.append('/'); sb.append(partitionName); } if (!viewName.isEmpty()) { sb.append('/'); sb.append(viewName); } return sb.toString(); } /** * Checks if a CharSequence is empty ("") or null. */ private static boolean isNullOrEmpty(@Nullable final CharSequence cs) { return cs == null || cs.length() == 0; } /** * Type of the connector resource. */ public enum Type { /** * Catalog type. */ CATALOG("^([^\\/]+)$"), /** * Database type. */ DATABASE("^([^\\/]+)\\/([^\\/]+)$"), /** * Table type. */ TABLE("^([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)$"), /** * Partition type. */ PARTITION("^(.*)$"), /** * MView type. */ MVIEW("^([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)$"); private final String regexValue; /** * Constructor. * * @param value category value. */ Type(final String value) { this.regexValue = value; } /** * get Regex Value. * @return regex value */ public String getRegexValue() { return regexValue; } /** * Type create from value. * * @param value string value * @return Type object */ public static Type fromValue(final String value) { for (Type type : values()) { if (type.name().equalsIgnoreCase(value)) { return type; } } throw new IllegalArgumentException( "Unknown enum type " + value + ", Allowed values are " + Arrays.toString(values())); } } }
1,703
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/MetacatRequestContext.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.common; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import javax.annotation.Nullable; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * The context of the request to metacat. * * @author amajumdar * @author tgianos * @author zhenl */ @Getter public class MetacatRequestContext implements Serializable { /** * Request header representing the user name. */ public static final String HEADER_KEY_USER_NAME = "X-Netflix.user.name"; /** * Request header representing the client application name. */ public static final String HEADER_KEY_CLIENT_APP_NAME = "X-Netflix.client.app.name"; /** * Request header representing the job id. */ public static final String HEADER_KEY_JOB_ID = "X-Netflix.job.id"; /** * Request header representing the data type context. */ public static final String HEADER_KEY_DATA_TYPE_CONTEXT = "X-Netflix.data.type.context"; /** * Default if unknown. */ public static final String UNKNOWN = "UNKNOWN"; private static final long serialVersionUID = -1486145626431113817L; private final String id = UUID.randomUUID().toString(); // TODO: Move to Java 8 and use java.time.Instant private final long timestamp = new Date().getTime(); // the following fields are immutable. private final String clientAppName; private final String clientId; private final String jobId; private final String dataTypeContext; private final String apiUri; private final String scheme; // The following fields are set during request processing and are mutable. // The general expectation is that these would be set zero or one times. @Setter private String userName; @Getter(AccessLevel.NONE) private Map<QualifiedName, String> tableTypeMap; @Getter private final Map<String, String> additionalContext = new HashMap<>(); @Setter private String requestName = UNKNOWN; /** * Constructor. */ public MetacatRequestContext() { this.userName = null; this.clientAppName = null; this.clientId = null; this.jobId = null; this.dataTypeContext = null; this.apiUri = UNKNOWN; this.scheme = UNKNOWN; this.tableTypeMap = new HashMap<>(); } /** * Constructor. * * @param userName user name * @param clientAppName client application name * @param clientId client id * @param jobId job id * @param dataTypeContext data type context * @param apiUri the uri of rest api * @param scheme http, thrift, internal, etc. */ protected MetacatRequestContext( @Nullable final String userName, @Nullable final String clientAppName, @Nullable final String clientId, @Nullable final String jobId, @Nullable final String dataTypeContext, final String apiUri, final String scheme ) { this.userName = userName; this.clientAppName = clientAppName; this.clientId = clientId; this.jobId = jobId; this.dataTypeContext = dataTypeContext; this.apiUri = apiUri; this.scheme = scheme; this.tableTypeMap = new HashMap<>(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("MetacatRequestContext{"); sb.append("id='").append(id).append('\''); sb.append(", timestamp=").append(timestamp); sb.append(", userName='").append(userName).append('\''); sb.append(", clientAppName='").append(clientAppName).append('\''); sb.append(", clientId='").append(clientId).append('\''); sb.append(", jobId='").append(jobId).append('\''); sb.append(", dataTypeContext='").append(dataTypeContext).append('\''); sb.append(", apiUri='").append(apiUri).append('\''); sb.append(", scheme='").append(scheme).append('\''); sb.append(", additionalContext='").append(additionalContext).append('\''); sb.append(", requestName='").append(requestName).append('\''); sb.append('}'); return sb.toString(); } /** * Store the tableType associated with table specified by qualifiedName param. * @param qualifiedName fully qualified name of table * @param tableType table type of table */ public void updateTableTypeMap(@NonNull final QualifiedName qualifiedName, final String tableType) { this.tableTypeMap.put(qualifiedName, tableType); } /** * Clear all entries from the tableType map. */ public void clearTableTypeMap() { this.tableTypeMap.clear(); } /** * Gets tableType. * @param qualifiedName fully qualified name of the table * @return the tableType associated with table specified by qualifiedName param. */ public String getTableType(@NonNull final QualifiedName qualifiedName) { return this.tableTypeMap.get(qualifiedName); } /** * builder class for MetacatRequestContext. * @return the builder class for MetacatRequestContext */ public static MetacatRequestContext.MetacatRequestContextBuilder builder() { return new MetacatRequestContext.MetacatRequestContextBuilder(); } /** * MetacatRequestContext builder class. */ public static class MetacatRequestContextBuilder { private String bUserName; private String bClientAppName; private String bClientId; private String bJobId; private String bDataTypeContext; private String bApiUri; private String bScheme; MetacatRequestContextBuilder() { this.bApiUri = UNKNOWN; this.bScheme = UNKNOWN; } /** * set userName. * * @param userName user name at client side * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder userName(@Nullable final String userName) { this.bUserName = userName; return this; } /** * set clientAppName. * * @param clientAppName application name of client * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder clientAppName(@Nullable final String clientAppName) { this.bClientAppName = clientAppName; return this; } /** * set clientId. * * @param clientId client identifier, such as host name * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder clientId(@Nullable final String clientId) { this.bClientId = clientId; return this; } /** * set jobId. * * @param jobId jobid from client side * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder jobId(@Nullable final String jobId) { this.bJobId = jobId; return this; } /** * set datatypeContext. * * @param dataTypeContext the data type context in rest api * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder dataTypeContext( @Nullable final String dataTypeContext) { this.bDataTypeContext = dataTypeContext; return this; } /** * set apiUri. * * @param apiUri the uri in rest api * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder apiUri(final String apiUri) { this.bApiUri = apiUri; return this; } /** * set scheme. * * @param scheme the scheme component in restapi such as http * @return the builder */ public MetacatRequestContext.MetacatRequestContextBuilder scheme(final String scheme) { this.bScheme = scheme; return this; } /** * builder. * * @return MetacatRequestContext object */ public MetacatRequestContext build() { return new MetacatRequestContext(this.bUserName, this.bClientAppName, this.bClientId, this.bJobId, this.bDataTypeContext, this.bApiUri, this.bScheme); } } }
1,704
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/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. * */ /** * Common package for Metacat. * * @author amajumdar */ @ParametersAreNonnullByDefault package com.netflix.metacat.common; import javax.annotation.ParametersAreNonnullByDefault;
1,705
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/DataMetadataDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import javax.annotation.Nonnull; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Data metadata DTO. */ @Data @EqualsAndHashCode(callSuper = false) public class DataMetadataDto extends BaseDto implements HasDataMetadata { private static final long serialVersionUID = -874750260731085106L; private String uri; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata") @JsonProperty private transient ObjectNode dataMetadata; /** * Returns uri. * @return The uri that points to the location of the external data. * @throws IllegalStateException if this instance does not have external data */ @Nonnull @Override @JsonIgnore public String getDataUri() { return uri; } /** * Returns true if this particular instance points to external data. * @return true if this particular instance points to external data */ @Override public boolean isDataExternal() { return false; } /** * Sets the data external property. * @param ignored is data external */ @SuppressWarnings("EmptyMethod") public void setDataExternal(final boolean ignored) { } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); dataMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, dataMetadata); } }
1,706
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/Sort.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.common.dto; /** * Sort info. */ public class Sort { private String sortBy; private SortOrder order; /** * Default constructor. */ public Sort() { } /** * Constructor. * * @param sortBy sort by * @param order order of the list */ public Sort(final String sortBy, final SortOrder order) { this.sortBy = sortBy; this.order = order; } public String getSortBy() { return sortBy; } public void setSortBy(final String sortBy) { this.sortBy = sortBy; } public SortOrder getOrder() { return order == null ? SortOrder.ASC : order; } public void setOrder(final SortOrder order) { this.order = order; } /** * True if sortBy is specified. * * @return true if sortBy is specified */ public boolean hasSort() { return sortBy != null; } }
1,707
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/FieldDto.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.common.dto; import com.fasterxml.jackson.databind.JsonNode; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Field DTO. */ @ApiModel(description = "Table field/column metadata") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor @Builder @AllArgsConstructor public class FieldDto extends BaseDto { private static final long serialVersionUID = 9096928516299407324L; @ApiModelProperty(value = "Comment of the field/column") private String comment; @ApiModelProperty(value = "Name of the field/column", required = true) private String name; @ApiModelProperty(value = "Is it a partition Key. If true, it is a partition key.") @SuppressWarnings("checkstyle:membername") private boolean partition_key; @ApiModelProperty(value = "Position of the field/column", required = true) private Integer pos; @ApiModelProperty(value = "Source type of the field/column") @SuppressWarnings("checkstyle:membername") private String source_type; @ApiModelProperty(value = "Type of the field/column", required = true) private String type; @ApiModelProperty(value = "Type of the field/column in JSON format", accessMode = ApiModelProperty.AccessMode.READ_ONLY) private JsonNode jsonType; @ApiModelProperty(value = "Can the field/column be null") private Boolean isNullable; @ApiModelProperty(value = "Size of the field/column") private Integer size; @ApiModelProperty(value = "Default value of the column") private String defaultValue; @ApiModelProperty(value = "Is the column a sorted key") private Boolean isSortKey; @ApiModelProperty(value = "Is the column an index key") private Boolean isIndexKey; @SuppressWarnings("checkstyle:methodname") public String getSource_type() { return source_type; } @SuppressWarnings("checkstyle:methodname") public void setSource_type(final String sourceType) { this.source_type = sourceType; } @SuppressWarnings("checkstyle:methodname") public boolean isPartition_key() { return partition_key; } @SuppressWarnings("checkstyle:methodname") public void setPartition_key(final boolean partitionKey) { this.partition_key = partitionKey; } }
1,708
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/DatabaseCreateRequestDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; /** * Database create request. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) public class DatabaseCreateRequestDto extends BaseDto { private static final long serialVersionUID = 6308417213106650174L; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the physical data") @JsonProperty private transient ObjectNode definitionMetadata; @ApiModelProperty(value = "Any extra metadata properties of the database") private Map<String, String> metadata; @ApiModelProperty(value = "URI of the database. Only applies to certain data sources like hive, S3") private String uri; private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, definitionMetadata); } }
1,709
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/HasMetadata.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.common.dto; import java.io.Serializable; /** * Marker interface for objects with metadata. */ public interface HasMetadata extends Serializable { }
1,710
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/ViewDto.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.common.dto; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Hive Virtual View Dto information. * @author zhenl * @since 1.2.0 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = false) public class ViewDto extends BaseDto { private static final long serialVersionUID = -1044988220491063480L; @ApiModelProperty(value = "View original text.", required = true) private String viewOriginalText; @ApiModelProperty(value = "View expanded text.") private String viewExpandedText; }
1,711
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/DefinitionMetadataDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Definition metadata DTO. */ @Data @EqualsAndHashCode(callSuper = false) public class DefinitionMetadataDto extends BaseDto implements HasDefinitionMetadata { private static final long serialVersionUID = 3826462875655878L; private QualifiedName name; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata") @JsonProperty private transient ObjectNode definitionMetadata; private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, definitionMetadata); } @Override @JsonIgnore public QualifiedName getDefinitionName() { return name; } }
1,712
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/DatabaseDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Date; import java.util.List; import java.util.Map; /** * Database information. */ @ApiModel(description = "Tables and other information about the given database") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) public class DatabaseDto extends BaseDto implements HasDefinitionMetadata { private static final long serialVersionUID = -4530516372664788451L; private Date dateCreated; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the logical database") @JsonProperty private transient ObjectNode definitionMetadata; private Date lastUpdated; @ApiModelProperty(value = "the name of this entity", required = true) @JsonProperty private QualifiedName name; @ApiModelProperty(value = "Names of the tables in this database", required = true) private List<String> tables; @ApiModelProperty(value = "Connector type of this catalog", required = true) private String type; @ApiModelProperty(value = "Any extra metadata properties of the database") private Map<String, String> metadata; @ApiModelProperty(value = "URI of the database. Only applies to certain data sources like hive, S3") private String uri; @JsonIgnore public QualifiedName getDefinitionName() { return name; } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, definitionMetadata); } }
1,713
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/GetPartitionsRequestDto.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.common.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; /** * Partition get request. */ @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) public class GetPartitionsRequestDto extends BaseDto { private String filter; private List<String> partitionNames; private Boolean includePartitionDetails = false; /* for audit tables with wap patterns if true, getPartitionsForRequest will only return audit table's own partitions. Metacat does not interpreate this flag for regular table, i.e. they should always return their own partitions. */ private Boolean includeAuditOnly = false; }
1,714
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/StorageDto.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.common.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.Map; /** * Storage DTO. * <pre> * { * "inputFormat": "org.apache.hadoop.mapred.TextInputFormat", * "outputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat", * "serializationLib": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe", * "parameters": { * "serialization.format": "1" * }, * "owner": "charsmith" * } * </pre> */ @ApiModel(description = "Serialization/Deserialization metadata of the table data") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @Builder @NoArgsConstructor @AllArgsConstructor public class StorageDto extends BaseDto { private static final long serialVersionUID = 4933906340321707232L; @ApiModelProperty(value = "Input format of the table data stored") private String inputFormat; @ApiModelProperty(value = "Output format of the table data stored") private String outputFormat; @ApiModelProperty(value = "Owner of the table") private String owner; @ApiModelProperty(value = "Extra storage parameters") private Map<String, String> parameters; @ApiModelProperty(value = "Extra storage parameters") private Map<String, String> serdeInfoParameters; @ApiModelProperty(value = "Serialization library of the data") private String serializationLib; @ApiModelProperty(value = "URI of the table. Only applies to certain data sources like hive, S3") private String uri; }
1,715
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/PartitionsSaveRequestDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiParam; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; /** * Partition save request. */ @Data @EqualsAndHashCode(callSuper = false) public class PartitionsSaveRequestDto extends BaseDto { private static final long serialVersionUID = -5922699691074685961L; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to this table") @JsonProperty private transient ObjectNode dataMetadata; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the physical data") @JsonProperty private transient ObjectNode definitionMetadata; // List of partitions @ApiParam(value = "List of partitions", required = true) private List<PartitionDto> partitions; // List of partition ids/names for deletes private List<String> partitionIdsForDeletes; // If true, we check if partition exists and drop it before adding it back. If false, we do not check and just add. private Boolean checkIfExists = true; // If true, we alter if partition exists. If checkIfExists=false, then this is false too. private Boolean alterIfExists = false; // If true, metacat will only update metadata. For optimization purpose, metacat skips the partition validation // and other flags settings, such as checkIfExists, for partition operations. private Boolean saveMetadataOnly = false; private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); dataMetadata = deserializeObjectNode(in); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, dataMetadata); serializeObjectNode(out, definitionMetadata); } @Override public String toString() { return "PartitionsSaveRequestDto{" + "dataMetadata=" + dataMetadata + ", definitionMetadata=" + definitionMetadata + ", partitions=" + partitions + ", partitionIdsForDeletes=" + partitionIdsForDeletes + ", checkIfExists=" + checkIfExists + ", alterIfExists=" + alterIfExists + '}'; } }
1,716
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/TagRemoveRequestDto.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.common.dto; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; /** * Tag Remove Request Dto. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) public class TagRemoveRequestDto extends BaseDto { private static final long serialVersionUID = 8698531483258796673L; @ApiModelProperty(value = "The qualified name", required = true) private QualifiedName name; @ApiModelProperty(value = "True to delete all tags") private Boolean deleteAll; @ApiModelProperty(value = "Tags to remove") private List<String> tags; }
1,717
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/SortOrder.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.common.dto; /** * Sort order. */ public enum SortOrder { /** Ascending order. */ ASC, /** Descending order. */ DESC }
1,718
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/PartitionsSaveResponseDto.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.common.dto; import java.util.ArrayList; import java.util.List; /** * Partition save response. */ public class PartitionsSaveResponseDto extends BaseDto { /** * List of added partition names. */ private List<String> added; /** * List of updated partition names. */ private List<String> updated; /** * Default constructor. */ public PartitionsSaveResponseDto() { added = new ArrayList<>(); updated = new ArrayList<>(); } public List<String> getAdded() { return added; } /** * Sets list of added partition names. * * @param added list of added partition names */ public void setAdded(final List<String> added) { if (added != null) { this.added = added; } } public List<String> getUpdated() { return updated; } /** * Sets list of updated partition names. * * @param updated list of updated partition names */ public void setUpdated(final List<String> updated) { if (updated != null) { this.updated = updated; } } }
1,719
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/CatalogDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import java.util.Map; /** * Information about a catalog. */ @ApiModel(description = "Information about a catalog") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) public class CatalogDto extends BaseDto implements HasDefinitionMetadata { private static final long serialVersionUID = -5713826608609231492L; @ApiModelProperty(value = "a list of the names of the databases that belong to this catalog", required = true) private List<String> databases; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the logical catalog") @JsonProperty private transient ObjectNode definitionMetadata; @ApiModelProperty(value = "the name of this entity", required = true) @JsonProperty private QualifiedName name; @ApiModelProperty(value = "the type of the connector of this catalog", required = true) private String type; @ApiModelProperty(value = "Cluster information referred to by this catalog", required = true) @JsonProperty private ClusterDto cluster; @JsonProperty private Map<String, String> metadata; @JsonIgnore public QualifiedName getDefinitionName() { return name; } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, definitionMetadata); } }
1,720
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/HasDataMetadata.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.common.dto; import com.fasterxml.jackson.databind.node.ObjectNode; import javax.annotation.Nonnull; /** * Marker interface for objects with data metadata. */ public interface HasDataMetadata extends HasMetadata { /** * Returns data metadata. * * @return data metadata */ ObjectNode getDataMetadata(); /** * Sets the data metadata json. * * @param metadata data metadata json */ void setDataMetadata(ObjectNode metadata); /** * Returns uri. * * @return The uri that points to the location of the external data. * @throws IllegalStateException if this instance does not have external data */ @Nonnull String getDataUri(); /** * Returns true if this particular instance points to external data. * * @return true if this particular instance points to external data */ boolean isDataExternal(); }
1,721
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/ResolveByUriRequestDto.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.common.dto; import lombok.Data; import lombok.EqualsAndHashCode; /** * ResolveByUriRequestDto. * * @author zhenl * @since 1.0.0 */ @Data @EqualsAndHashCode(callSuper = false) public class ResolveByUriRequestDto extends BaseDto { private static final long serialVersionUID = -2649784382533439526L; private String uri; }
1,722
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/Pageable.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.common.dto; import lombok.Data; /** * Represents the pagination information. * * @author amajumdar */ @Data public class Pageable { private Integer limit; private Integer offset; /** * Default constructor. */ public Pageable() { } /** * Constructor. * * @param limit size of the list * @param offset offset of the list */ public Pageable(final Integer limit, final Integer offset) { this.limit = limit; this.offset = offset; } public Integer getOffset() { return offset == null ? Integer.valueOf(0) : offset; } public boolean isPageable() { return limit != null; } }
1,723
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/HasDefinitionMetadata.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.common.dto; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; /** * Marker interface for objects with data metadata. */ public interface HasDefinitionMetadata extends HasMetadata { /** * Returns definition metadata. * * @return definition metadata */ ObjectNode getDefinitionMetadata(); /** * Sets definition metadata. * * @param metadata definition metadata */ void setDefinitionMetadata(ObjectNode metadata); /** * Returns the qualified name. * * @return qualified name */ QualifiedName getDefinitionName(); }
1,724
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/DataMetadataGetRequestDto.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.common.dto; import lombok.Data; import lombok.EqualsAndHashCode; /** * Data metadata request. */ @Data @EqualsAndHashCode(callSuper = false) public class DataMetadataGetRequestDto extends BaseDto { private String uri; }
1,725
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/CreateCatalogDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Information required to create a new catalog. */ @ApiModel(description = "Information required to create a new catalog") @Data @EqualsAndHashCode(callSuper = false) public class CreateCatalogDto extends BaseDto implements HasDefinitionMetadata { private static final long serialVersionUID = -6745573078608938941L; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the logical catalog") @JsonProperty private transient ObjectNode definitionMetadata; @ApiModelProperty(value = "the name of this entity", required = true) @JsonProperty private QualifiedName name; @ApiModelProperty(value = "the type of the connector of this catalog", required = true) private String type; @Override @JsonIgnore public QualifiedName getDefinitionName() { return name; } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, definitionMetadata); } }
1,726
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/AuditDto.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.common.dto; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.Date; /** * Audit information. */ @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @Builder @AllArgsConstructor @NoArgsConstructor public class AuditDto extends BaseDto { private static final long serialVersionUID = 9221109874202093789L; /* Created By */ @ApiModelProperty(value = "User name who created the table") private String createdBy; /* Created date */ @ApiModelProperty(value = "Creation date") private Date createdDate; /* Last modified by */ @ApiModelProperty(value = "User name who last modified the table") private String lastModifiedBy; /* Last modified date */ @ApiModelProperty(value = "Last modified date") private Date lastModifiedDate; }
1,727
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/PartitionDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.annotation.Nonnull; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; /** * Partition DTO. */ @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @Builder @AllArgsConstructor @NoArgsConstructor public class PartitionDto extends BaseDto implements HasDataMetadata, HasDefinitionMetadata { private static final long serialVersionUID = 783462697901395508L; @ApiModelProperty(value = "audit information about the partition") private AuditDto audit; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "Physical metadata: metadata about the physical data referred by the partition.") @JsonProperty private transient ObjectNode dataMetadata; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "Logical metadata: metadata about the logical construct of the partition.") @JsonProperty private transient ObjectNode definitionMetadata; @ApiModelProperty(value = "the name of this entity", required = true) @JsonProperty private QualifiedName name; @ApiModelProperty(value = "Storage/Serialization/Deserialization info of the partition ") private StorageDto serde; @ApiModelProperty(value = "Any extra metadata properties of the partition") private Map<String, String> metadata; @Nonnull @Override @JsonIgnore public String getDataUri() { final String uri = serde != null ? serde.getUri() : null; if (uri == null || uri.isEmpty()) { throw new IllegalStateException("This instance does not have external data"); } return uri; } @JsonIgnore public QualifiedName getDefinitionName() { return name; } @Override @JsonProperty public boolean isDataExternal() { return serde != null && serde.getUri() != null && !serde.getUri().isEmpty(); } /** * Sets the data external property. * * @param ignored is data external */ @SuppressWarnings("EmptyMethod") public void setDataExternal(final boolean ignored) { } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); dataMetadata = deserializeObjectNode(in); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, dataMetadata); serializeObjectNode(out, definitionMetadata); } }
1,728
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/BaseDto.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.common.dto; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.json.MetacatJsonLocator; import lombok.NonNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * Base class for all common DTOs. * * @author amajumdar */ //TODO: All DTO's should be READ-ONLY public abstract class BaseDto implements Serializable { protected static final MetacatJsonLocator METACAT_JSON_LOCATOR = new MetacatJsonLocator(); /** * Deserialize the input stream. * * @param inputStream input stream * @return Json node * @throws IOException exception deserializing the stream */ @Nullable public static ObjectNode deserializeObjectNode( @Nonnull @NonNull final ObjectInputStream inputStream ) throws IOException { return METACAT_JSON_LOCATOR.deserializeObjectNode(inputStream); } /** * Serialize the stream. * * @param outputStream output stream * @param json Json Node * @throws IOException exception serializing the json */ public static void serializeObjectNode( @Nonnull @NonNull final ObjectOutputStream outputStream, @Nullable final ObjectNode json ) throws IOException { METACAT_JSON_LOCATOR.serializeObjectNode(outputStream, json); } /** * {@inheritDoc} */ @Override public String toString() { return METACAT_JSON_LOCATOR.toJsonString(this); } }
1,729
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/ClusterDto.java
package com.netflix.metacat.common.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.io.Serializable; /** * Catalog cluster information. * * @author rveeramacheneni * @since 1.3.0 */ @ApiModel(description = "Information about the catalog cluster") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @Builder @NoArgsConstructor @AllArgsConstructor public class ClusterDto implements Serializable { private static final long serialVersionUID = 3575620733293405903L; /** Name of the cluster. */ @ApiModelProperty(value = "the cluster hosting this catalog", required = false) private String name; /** Type of the cluster. */ @ApiModelProperty(value = "the type of the cluster", required = true) private String type; /** Name of the account under which the cluster was created. Ex: "abc_test" */ @ApiModelProperty(value = "Name of the account under which the cluster was created.", required = false) private String account; /** Id of the Account under which the cluster was created. Ex: "abc_test" */ @ApiModelProperty(value = "Id of the Account under which the cluster was created", required = false) private String accountId; /** Environment under which the cluster exists. Ex: "prod", "test" */ @ApiModelProperty(value = "the environment in which the cluster exists", required = false) private String env; /** Region in which the cluster exists. Ex: "us-east-1" */ @ApiModelProperty(value = "the region of this cluster", required = false) private String region; }
1,730
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/TableDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.annotation.Nonnull; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; /** * Table DTO. */ @ApiModel(description = "Table metadata") @SuppressWarnings("unused") @Data @EqualsAndHashCode(callSuper = false) @Builder @NoArgsConstructor @AllArgsConstructor public class TableDto extends BaseDto implements HasDataMetadata, HasDefinitionMetadata { private static final long serialVersionUID = 5922768252406041451L; @ApiModelProperty(value = "Contains information about table changes") private AuditDto audit; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the physical data") @JsonProperty private transient ObjectNode dataMetadata; // Marked as transient because we serialize it manually, however as a JsonProperty because Jackson does serialize it @ApiModelProperty(value = "metadata attached to the logical table") @JsonProperty private transient ObjectNode definitionMetadata; private List<FieldDto> fields; @ApiModelProperty(value = "Any extra metadata properties of the database table") private Map<String, String> metadata; @ApiModelProperty(value = "the name of this entity", required = true) @JsonProperty private QualifiedName name; @ApiModelProperty(value = "serialization/deserialization info about the table") private StorageDto serde; @ApiModelProperty(value = "Hive virtual view info.") //Naming as view required by dozer mapping private ViewDto view; @Nonnull @Override @JsonIgnore public String getDataUri() { final String uri = serde != null ? serde.getUri() : null; if (uri == null || uri.isEmpty()) { throw new IllegalStateException("This instance does not have external data"); } return uri; } @JsonIgnore public QualifiedName getDefinitionName() { return name; } @JsonIgnore public Optional<String> getTableOwner() { return Optional.ofNullable(definitionMetadata) .map(definitionMetadataJson -> definitionMetadataJson.get("owner")) .map(ownerJson -> ownerJson.get("userId")) .map(JsonNode::textValue); } @JsonIgnore public Optional<String> getTableOwnerGroup() { return Optional.ofNullable(definitionMetadata) .map(definitionMetadataJson -> definitionMetadataJson.get("owner")) .map(ownerJson -> ownerJson.get("google_group")) .map(JsonNode::textValue); } /** * Returns the list of partition keys. * @return list of partition keys */ @ApiModelProperty(value = "List of partition key names") @JsonProperty @SuppressWarnings("checkstyle:methodname") public List<String> getPartition_keys() { if (fields == null) { return null; } else if (fields.isEmpty()) { return Collections.emptyList(); } final List<String> keys = new LinkedList<>(); for (FieldDto field : fields) { if (field.isPartition_key()) { keys.add(field.getName()); } } return keys; } /** * Sets the partition keys. * @param ignored list of partition keys */ @SuppressWarnings({"EmptyMethod", "checkstyle:methodname"}) public void setPartition_keys(final List<String> ignored) { } @Override @JsonProperty public boolean isDataExternal() { return serde != null && serde.getUri() != null && !serde.getUri().isEmpty(); } /** * Sets the data external property. * @param ignored is data external */ @SuppressWarnings("EmptyMethod") public void setDataExternal(final boolean ignored) { } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); dataMetadata = deserializeObjectNode(in); definitionMetadata = deserializeObjectNode(in); } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); serializeObjectNode(out, dataMetadata); serializeObjectNode(out, definitionMetadata); } }
1,731
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/ResolveByUriResponseDto.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.common.dto; import com.netflix.metacat.common.QualifiedName; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; /** * ResolveByUriResponseDto. * * @author zhenl * @since 1.0.0 */ @Data @EqualsAndHashCode(callSuper = false) public class ResolveByUriResponseDto extends BaseDto { private static final long serialVersionUID = -4505346090786555046L; private List<QualifiedName> tables; private List<QualifiedName> partitions; }
1,732
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/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. * */ /** * Package containing the common DTOs used between the Metacat client and server. * * @author amajumdar */ package com.netflix.metacat.common.dto;
1,733
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/CatalogMappingDto.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.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * The name and type of a catalog. */ @ApiModel(description = "The name and type of a catalog") @SuppressWarnings("unused") @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = false) public class CatalogMappingDto extends BaseDto { private static final long serialVersionUID = -1223516438943164936L; @ApiModelProperty(value = "The name of the catalog", required = true) private String catalogName; @ApiModelProperty(value = "The connector type of the catalog", required = true) private String connectorName; @ApiModelProperty(value = "Cluster information referred by this catalog", required = true) @JsonProperty private ClusterDto clusterDto; }
1,734
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/TagCreateRequestDto.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.common.dto; import com.netflix.metacat.common.QualifiedName; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.util.List; /** * Tag Create Request Dto. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) public class TagCreateRequestDto extends BaseDto { private static final long serialVersionUID = -990374882621118670L; @ApiModelProperty(value = "The qualified name", required = true) private QualifiedName name; @ApiModelProperty(value = "Tags to insert") private List<String> tags; }
1,735
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/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. * */ /** * Data transfer objects related to notification events. * * @author tgianos * @since 0.1.47 */ package com.netflix.metacat.common.dto.notifications;
1,736
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/SNSMessageFactory.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.common.dto.notifications.sns; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.metacat.common.dto.notifications.sns.messages.AddPartitionMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.CreateTableMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.DeletePartitionMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.DeleteTableMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.RenameTableMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.UpdateTableMessage; import com.netflix.metacat.common.dto.notifications.sns.messages.UpdateTablePartitionsMessage; import lombok.NonNull; import java.io.IOException; /** * Create SNSMessage object based on the JSON passed in. * * @author tgianos * @since 0.1.47 */ public class SNSMessageFactory { private static final String TYPE_FIELD = "type"; private final ObjectMapper mapper; /** * Constructor. * * @param mapper The object mapper to use for deserialization */ public SNSMessageFactory(@NonNull final ObjectMapper mapper) { this.mapper = mapper; } /** * Convert a JSON String into a message if possible. * * @param json The body of the message to convert back to the original message object from JSON string * @return The message bound back into a POJO * @throws IOException When the input isn't valid JSON */ public SNSMessage<?> getMessage(@NonNull final String json) throws IOException { final JsonNode object = this.mapper.readTree(json); if (object.has(TYPE_FIELD)) { final SNSMessageType messageType = SNSMessageType.valueOf(object.get(TYPE_FIELD).asText()); switch (messageType) { case TABLE_CREATE: return this.mapper.readValue(json, CreateTableMessage.class); case TABLE_DELETE: return this.mapper.readValue(json, DeleteTableMessage.class); case TABLE_UPDATE: return this.mapper.readValue(json, UpdateTableMessage.class); case TABLE_RENAME: return this.mapper.readValue(json, RenameTableMessage.class); case TABLE_PARTITIONS_UPDATE: return this.mapper.readValue(json, UpdateTablePartitionsMessage.class); case PARTITION_ADD: return this.mapper.readValue(json, AddPartitionMessage.class); case PARTITION_DELETE: return this.mapper.readValue(json, DeletePartitionMessage.class); default: throw new UnsupportedOperationException("Unknown type " + messageType); } } else { // won't know how to bind throw new IOException("Invalid content. No field type field found"); } } }
1,737
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/SNSMessageType.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.common.dto.notifications.sns; /** * Enumeration of the various types of SNS events there can be. * * @author tgianos * @since 0.1.47 */ public enum SNSMessageType { /** * When a table is created. */ TABLE_CREATE, /** * When a table is deleted. */ TABLE_DELETE, /** * When the metadata about a table is updated somehow. */ TABLE_UPDATE, /** * When a table is renamed. */ TABLE_RENAME, /** * When the partitions for a table are either created or deleted. */ TABLE_PARTITIONS_UPDATE, /** * When a partition is added. */ PARTITION_ADD, /** * When a partition is deleted. */ PARTITION_DELETE, /** * When a partition metadata is saved only. */ PARTITION_METADATAONLY_SAVE }
1,738
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/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. * */ /** * Data Transfer Objects (DTO) for AWS SNS notifications from Metacat. * * @author tgianos * @since 0.1.47 */ @ParametersAreNonnullByDefault package com.netflix.metacat.common.dto.notifications.sns; import javax.annotation.ParametersAreNonnullByDefault;
1,739
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/SNSMessage.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.common.dto.notifications.sns; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.BaseDto; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.ToString; import javax.annotation.Nullable; /** * Base SNS notification DTO with shared fields. * * @param <P> The type of payload this notification has * @author tgianos * @since 0.1.47 */ @Getter @ToString @EqualsAndHashCode(callSuper = false) @SuppressFBWarnings public class SNSMessage<P> extends BaseDto { private final String source = "metacat"; private final String id; private final long timestamp; private final String requestId; private final String name; private final SNSMessageType type; private final P payload; /** * Create a new SNSMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param type The type of notification * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public SNSMessage( @JsonProperty("id") @NonNull final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") @NonNull final String requestId, @JsonProperty("type") @NonNull final SNSMessageType type, @JsonProperty("name") @NonNull final String name, @JsonProperty("payload") @Nullable final P payload ) { this.id = id; this.timestamp = timestamp; this.requestId = requestId; this.type = type; this.name = name; this.payload = payload; } }
1,740
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/DeletePartitionMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a partition is deleted. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class DeletePartitionMessage extends SNSMessage<String> { /** * Create a new DeletePartitionMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public DeletePartitionMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final String payload ) { super(id, timestamp, requestId, SNSMessageType.PARTITION_DELETE, name, payload); } }
1,741
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/UpdateTableMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import com.netflix.metacat.common.dto.notifications.sns.payloads.UpdatePayload; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a table is updated. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class UpdateTableMessage extends UpdateOrRenameTableMessageBase { /** * Create a new UpdateTableMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public UpdateTableMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final UpdatePayload<TableDto> payload ) { super(id, timestamp, requestId, name, payload, SNSMessageType.TABLE_UPDATE); } }
1,742
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/UpdateTablePartitionsMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import com.netflix.metacat.common.dto.notifications.sns.payloads.TablePartitionsUpdatePayload; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * Message sent when the partitions for a table are updated. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class UpdateTablePartitionsMessage extends SNSMessage<TablePartitionsUpdatePayload> { /** * Create a new UpdateTablePartitionsMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ public UpdateTablePartitionsMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final TablePartitionsUpdatePayload payload ) { super(id, timestamp, requestId, SNSMessageType.TABLE_PARTITIONS_UPDATE, name, payload); } }
1,743
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/UpdateOrRenameTableMessageBase.java
/* * * Copyright 2020 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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import com.netflix.metacat.common.dto.notifications.sns.payloads.UpdatePayload; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * Base message type for Update and Rename messages. * * @author rveeramacheneni */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public abstract class UpdateOrRenameTableMessageBase extends SNSMessage<UpdatePayload<TableDto>> { /** * Ctor for this base class. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification * @param messageType Whether this is an Update or Rename message */ @JsonCreator public UpdateOrRenameTableMessageBase( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final UpdatePayload<TableDto> payload, final SNSMessageType messageType ) { super(id, timestamp, requestId, messageType, name, payload); } }
1,744
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/CreateTableMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a table is created. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class CreateTableMessage extends SNSMessage<TableDto> { /** * Create a new CreateTableMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public CreateTableMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final TableDto payload ) { super(id, timestamp, requestId, SNSMessageType.TABLE_CREATE, name, payload); } }
1,745
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/AddPartitionMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.PartitionDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a partition is created. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class AddPartitionMessage extends SNSMessage<PartitionDto> { /** * Create a new AddPartitionMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public AddPartitionMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final PartitionDto payload ) { super(id, timestamp, requestId, SNSMessageType.PARTITION_ADD, name, payload); } }
1,746
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/RenameTableMessage.java
/* * * Copyright 2020 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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import com.netflix.metacat.common.dto.notifications.sns.payloads.UpdatePayload; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a table is renamed. * * @author rveeramacheneni */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class RenameTableMessage extends UpdateOrRenameTableMessageBase { /** * Create a new RenameTableMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public RenameTableMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final UpdatePayload<TableDto> payload ) { super(id, timestamp, requestId, name, payload, SNSMessageType.TABLE_RENAME); } }
1,747
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/DeleteTableMessage.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.common.dto.notifications.sns.messages; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.notifications.sns.SNSMessage; import com.netflix.metacat.common.dto.notifications.sns.SNSMessageType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A message sent when a table is deleted. * * @author tgianos * @since 0.1.47 */ @Getter @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class DeleteTableMessage extends SNSMessage<TableDto> { /** * Create a new DeleteTableMessage. * * @param id The unique id of the message * @param timestamp The number of milliseconds since epoch that this message occurred * @param requestId The id of the API request that generated this and possibly other messages. Used for grouping * @param name The qualified name of the resource that this notification is being generated for * @param payload The payload of the notification */ @JsonCreator public DeleteTableMessage( @JsonProperty("id") final String id, @JsonProperty("timestamp") final long timestamp, @JsonProperty("requestId") final String requestId, @JsonProperty("name") final String name, @JsonProperty("payload") final TableDto payload ) { super(id, timestamp, requestId, SNSMessageType.TABLE_DELETE, name, payload); } }
1,748
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/messages/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. * */ /** * Specific notification messages which extend SNSMessage. * * @author tgianos * @since 0.1.46 */ @ParametersAreNonnullByDefault package com.netflix.metacat.common.dto.notifications.sns.messages; import javax.annotation.ParametersAreNonnullByDefault;
1,749
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/payloads/UpdatePayload.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.common.dto.notifications.sns.payloads; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.fge.jsonpatch.JsonPatch; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * Represents the contents of an update payload. * * @param <T> The DTO type that was update. e.g. com.netflix.metacat.common.dto.TableDto * @author tgianos * @since 0.1.47 */ @Getter @ToString @EqualsAndHashCode public class UpdatePayload<T> { private T previous; private JsonPatch patch; /** * Create a new update payload. * * @param previous The previous version of the object that was updated * @param patch The JSON patch to go from previous to current */ @JsonCreator public UpdatePayload( @JsonProperty("previous") final T previous, @JsonProperty("patch") final JsonPatch patch ) { this.previous = previous; this.patch = patch; } }
1,750
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/payloads/TablePartitionsUpdatePayload.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.common.dto.notifications.sns.payloads; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.List; /** * Information about how the partitions have changed when a table was updated. * * @author tgianos * @since 0.1.47 */ @Getter @ToString @EqualsAndHashCode public class TablePartitionsUpdatePayload { private final String latestDeleteColumnValue; private final int numCreatedPartitions; private final int numDeletedPartitions; private final String message; private final List<String> partitionsUpdated; /** * Constructor. * @param latestDeleteColumnValue The latest DeleteColumn value processed by microbot * @param numCreatedPartitions The number of partitions that were created for the table * @param numDeletedPartitions The number of partitions that were deleted from the table * @param message The message about the partition ids. * @param partitionsUpdated The list of ids of the partitions that were updated */ @JsonCreator public TablePartitionsUpdatePayload( @Nullable @JsonProperty("latestDeleteColumnValue") final String latestDeleteColumnValue, @JsonProperty("numCreatedPartitions") final int numCreatedPartitions, @JsonProperty("numDeletedPartitions") final int numDeletedPartitions, @JsonProperty("message") final String message, @JsonProperty("partitionsUpdated") final List<String> partitionsUpdated) { this.latestDeleteColumnValue = latestDeleteColumnValue; this.numCreatedPartitions = numCreatedPartitions; this.numDeletedPartitions = numDeletedPartitions; this.message = message; this.partitionsUpdated = partitionsUpdated; } }
1,751
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/dto/notifications/sns/payloads/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. * */ /** * Various payload representations for SNS Notifications. * * @author tgianos * @since 0.1.47 */ @ParametersAreNonnullByDefault package com.netflix.metacat.common.dto.notifications.sns.payloads; import javax.annotation.ParametersAreNonnullByDefault;
1,752
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/json/MetacatJsonLocator.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.common.json; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.AllArgsConstructor; import lombok.Getter; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import java.util.Map; /** * MetacatJson implementation. */ @AllArgsConstructor @Getter public class MetacatJsonLocator implements MetacatJson { private final ObjectMapper objectMapper; private final ObjectMapper prettyObjectMapper; /** * Constructor. */ public MetacatJsonLocator() { objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setSerializationInclusion(JsonInclude.Include.ALWAYS); prettyObjectMapper = objectMapper.copy().configure(SerializationFeature.INDENT_OUTPUT, true); } @Override public <T> T convertValue(final Object fromValue, final Class<T> toValueType) throws IllegalArgumentException { return objectMapper.convertValue(fromValue, toValueType); } @Override @Nullable public ObjectNode deserializeObjectNode( @Nonnull final ObjectInputStream inputStream) throws IOException { final boolean exists = inputStream.readBoolean(); ObjectNode json = null; if (exists) { final String s = inputStream.readUTF(); json = (ObjectNode) objectMapper.readTree(s); } return json; } @Override public ObjectNode emptyObjectNode() { return objectMapper.createObjectNode(); } @Override public void mergeIntoPrimary( @Nonnull final ObjectNode primary, @Nonnull final ObjectNode additional) { try { recursiveMerge(primary, additional); } catch (MetacatJsonException e) { throw new IllegalArgumentException("Unable to merge '" + additional + "' into '" + primary + "'"); } } @Nullable @Override public ObjectNode parseJsonObject(final String s) { final JsonNode node; try { node = objectMapper.readTree(s); } catch (Exception e) { throw new MetacatJsonException(s, "Cannot convert '" + s + "' to a json object", e); } return node.isObject() ? (ObjectNode) node : null; } @Override public <T> T parseJsonValue(final String s, final Class<T> clazz) { try { return objectMapper.readValue(s, clazz); } catch (IOException e) { throw new MetacatJsonException("Unable to convert '" + s + "' into " + clazz, e); } } @Override public <T> T parseJsonValue(final byte[] s, final Class<T> clazz) { try { return objectMapper.readValue(s, clazz); } catch (IOException e) { throw new MetacatJsonException("Unable to convert bytes into " + clazz, e); } } private void recursiveMerge(final JsonNode primary, final JsonNode additional) { if (!primary.isObject()) { throw new MetacatJsonException("This should not be reachable"); } final ObjectNode node = (ObjectNode) primary; final Iterator<Map.Entry<String, JsonNode>> fields = additional.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> entry = fields.next(); final String name = entry.getKey(); final JsonNode value = entry.getValue(); // Easiest case, if the primary node doesn't have the current field set the field on the primary if (!node.has(name)) { node.set(name, value); } else if (!value.isObject()) { // If the primary has the field but the incoming value is not an object set the field on the primary node.set(name, value); } else if (!node.get(name).isObject()) { // If the primary is currently not an object, just overwrite it with the incoming value node.set(name, value); } else { // Otherwise recursively merge the new fields from the incoming object into the primary object recursiveMerge(node.get(name), value); } } } @Override public void serializeObjectNode( @Nonnull final ObjectOutputStream outputStream, @Nullable final ObjectNode json) throws IOException { final boolean exists = json != null; outputStream.writeBoolean(exists); if (exists) { outputStream.writeUTF(json.toString()); } } @Override public byte[] toJsonAsBytes(final Object o) { try { return objectMapper.writeValueAsBytes(o); } catch (JsonProcessingException e) { throw new MetacatJsonException(e); } } @Override public ObjectNode toJsonObject(final Object o) { return objectMapper.valueToTree(o); } @Override public String toJsonString(final Object o) { try { return objectMapper.writeValueAsString(o); } catch (JsonProcessingException e) { throw new MetacatJsonException(e); } } }
1,753
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/json/MetacatJsonException.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.common.json; import lombok.Getter; /** * Metacat JSON utility related exception. */ @Getter public class MetacatJsonException extends RuntimeException { /** * Input json string if any. */ private String inputJson; /** * Constructor. * * @param message exception message */ public MetacatJsonException(final String message) { super(message); } /** * Constructor. * * @param inputJson input json string * @param message details of the message * @param cause exception cause */ public MetacatJsonException(final String inputJson, final String message, final Throwable cause) { super(message, cause); this.inputJson = inputJson; } /** * Constructor. * * @param cause exception cause */ public MetacatJsonException(final Throwable cause) { super(cause); } /** * Constructor. * * @param message exception message * @param cause exception cause */ public MetacatJsonException(final String message, final Throwable cause) { super(message, cause); } /** * Default constructor. */ public MetacatJsonException() { super(); } }
1,754
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/json/MetacatJson.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.common.json; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * JSON utility. */ public interface MetacatJson { /** * Convenience method for doing two-step conversion from given value, into * instance of given value type. This is functionality equivalent to first * serializing given value into JSON, then binding JSON data into value * of given type, but may be executed without fully serializing into * JSON. Same converters (serializers, deserializers) will be used as for * data binding, meaning same object mapper configuration works. * * @param fromValue object to be converted * @param toValueType POJO class to be converted to * @param <T> POJO class * @return Returns the converted POJO * @throws MetacatJsonException If conversion fails due to incompatible type; * if so, root cause will contain underlying checked exception data binding * functionality threw */ <T> T convertValue(Object fromValue, Class<T> toValueType); /** * A helper for implementing Serializable. Reads a boolean to from the inputStream to determine of the next * object is a json object and if it is it reads it and returns an object node. * * @param inputStream the serilization input stream * @return a json object if one is the next object otherwise null * @throws IOException on an error reading from the stream or a json serilization error. */ @Nullable ObjectNode deserializeObjectNode( @Nonnull ObjectInputStream inputStream) throws IOException; /** * Returns an empty object node. * * @return an empty object node */ ObjectNode emptyObjectNode(); /** * Returns default ObjectMapper used by this instance. * * @return The default ObjectMapper used by this instance. */ ObjectMapper getObjectMapper(); /** * Returns default ObjectMapper used by this instance configured to pretty print. * * @return The default ObjectMapper used by this instance configured to pretty print. */ ObjectMapper getPrettyObjectMapper(); /** * Merge primary and additional json nodes. * * @param primary first json node * @param additional second json node */ void mergeIntoPrimary( @Nonnull ObjectNode primary, @Nonnull ObjectNode additional); /** * Parses the given string as json and returns an ObjectNode representing the json. Assumes the json is of a * json object * * @param s a string representing a json object * @return an object node representation of the string * @throws MetacatJsonException if unable to convert the string to json or the json isn't a json object. */ ObjectNode parseJsonObject(String s); /** * Parses the given JSON value. * * @param s json string * @param clazz class * @param <T> type of the class * @return object */ <T> T parseJsonValue(String s, Class<T> clazz); /** * Parses the given JSON value. * * @param s json byte array * @param clazz class * @param <T> type of the class * @return object */ <T> T parseJsonValue(byte[] s, Class<T> clazz); /** * Serializes the JSON. * * @param outputStream output stream * @param json json node * @throws IOException exception */ void serializeObjectNode( @Nonnull ObjectOutputStream outputStream, @Nullable ObjectNode json) throws IOException; /** * Converts JSON as bytes. * * @param o object * @return byte array */ byte[] toJsonAsBytes(Object o); /** * Converts an object to JSON. * * @param o object * @return JSON node */ ObjectNode toJsonObject(Object o); /** * Converts an object to JSON string. * * @param o object * @return JSON string */ String toJsonString(Object o); }
1,755
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/json/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. * */ /** * Contains the utilities for JSON serialization/deserialization. * * @author amajumdar */ package com.netflix.metacat.common.json;
1,756
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/AbstractType.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.common.type; import lombok.EqualsAndHashCode; import lombok.Getter; /** * Abstract type class. * * @author zhenl */ @Getter @EqualsAndHashCode public abstract class AbstractType implements Type { private final TypeSignature typeSignature; AbstractType(final TypeSignature typeSignature) { this.typeSignature = typeSignature; } /** * get display name. * * @return name */ public String getDisplayName() { return typeSignature.toString(); } }
1,757
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/Type.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.common.type; /** * Canonical type interface. * * @author zhenl */ public interface Type { /** * Returns the signature of this type that should be displayed to end-users. * * @return signature */ TypeSignature getTypeSignature(); /** * get display name. * * @return name */ String getDisplayName(); }
1,758
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/TypeUtils.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.common.type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.Collection; /** * Type util class. * * @author zhenl */ public final class TypeUtils { private TypeUtils() { } /** * parameterizedTypeName. * * @param baseType baseType * @param argumentNames args * @return type signature */ public static TypeSignature parameterizedTypeSignature( final TypeEnum baseType, final TypeSignature... argumentNames ) { return new TypeSignature(baseType, ImmutableList.copyOf(argumentNames), ImmutableList.of()); } /** * Check if the collection is null or empty. * * @param collection collection * @return boolean */ public static boolean isNullOrEmpty(final Collection<?> collection) { return collection == null || collection.isEmpty(); } /** * CheckType. * * @param value value * @param target type * @param name name * @param <A> A * @param <B> B * @return B */ public static <A, B extends A> B checkType(final A value, final Class<B> target, final String name) { Preconditions.checkNotNull(value, "%s is null", name); Preconditions.checkArgument(target.isInstance(value), "%s must be of type %s, not %s", name, target.getName(), value.getClass().getName()); return target.cast(value); } }
1,759
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/TypeManager.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.common.type; import java.util.List; /** * Type manager interface. * * @author zhenl */ public interface TypeManager { /** * Gets the type with the signature, or null if not found. * * @param signature type signature * @return Type */ Type getType(TypeSignature signature); /** * Get the type with the specified paramenters, or null if not found. * * @param baseType baseType * @param typeParameters typeParameters * @param literalParameters literalParameters * @return Type */ Type getParameterizedType(TypeEnum baseType, List<TypeSignature> typeParameters, List<Object> literalParameters); /** * Gets a list of all registered types. * * @return list types. */ List<Type> getTypes(); }
1,760
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/TypeEnum.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.common.type; import lombok.Getter; import lombok.NonNull; import javax.annotation.Nonnull; /** * Canonical base type class. * * @author zhenl */ @Getter public enum TypeEnum { /** * Numeric Types. * small int 2-byte signed integer from -32,768 to 32,767. */ SMALLINT("smallint", false), /** * tinyint 1-byte signed integer, from -128 to 127. */ TINYINT("tinyint", false), /** * int 4-byte signed integer, from -2,147,483,648 to 2,147,483,647. */ INT("int", false), /** * bigint 8-byte signed integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. */ BIGINT("bigint", false), /** * float 4-byte single precision floating point number. */ FLOAT("float", false), /** * double 8-byte double precision floating point number. */ DOUBLE("double", false), /** * decimal type user definable precision and scale. */ DECIMAL("decimal", true), /** * char fixed length less than or equals to 255. */ CHAR("char", true), /** * varchar created with a length specifier (between 1 and 65355). */ VARCHAR("varchar", true), /** * string type. */ STRING("string", false), /** * json json string. */ JSON("json", false), /** * boolean type. */ BOOLEAN("boolean", false), /** * varbinary type. */ VARBINARY("varbinary", true), /** * date year/month/day in the form YYYY-­MM-­DD. */ DATE("date", false), /** * time traditional UNIX timestamp with optional nanosecond precision. */ TIME("time", false), /** * time with time zone. */ TIME_WITH_TIME_ZONE("time with time zone", false), /** * timestamp type. */ TIMESTAMP("timestamp", false), /** * timestamp with time zone type. */ TIMESTAMP_WITH_TIME_ZONE("timestamp with time zone", false), /** * Year to month intervals, format: SY-M * S: optional sign (+/-) * Y: year count * M: month count * example INTERVAL '1-2' YEAR TO MONTH. **/ INTERVAL_YEAR_TO_MONTH("interval year to month", false), /** * Day to second intervals, format: SD H:M:S.nnnnnn * S: optional sign (+/-) * D: day countH: hours * M: minutes * S: seconds * nnnnnn: optional nanotime * example INTERVAL '1 2:3:4.000005' DAY. */ INTERVAL_DAY_TO_SECOND("interval day to second", false), /** * unknown type. */ UNKNOWN("unknown", false), /** * array type. */ ARRAY("array", true), /** * row type. */ ROW("row", true), /** * map type. */ MAP("map", true); private final String type; private final boolean isParametricType; TypeEnum(@Nonnull @NonNull final String type, final boolean isParametricType) { this.type = type; this.isParametricType = isParametricType; } /** * Return name of the base type. * * @param name name * @return TypeEnum type */ public static TypeEnum fromName(final String name) { try { final String typeName = name.trim().toUpperCase().replace(' ', '_'); return TypeEnum.valueOf(typeName); } catch (final Exception e) { return UNKNOWN; } } }
1,761
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/ParametricType.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.common.type; import java.util.List; /** * Parametric type. * * @author zhenl */ public interface ParametricType extends Type { /** * Get type name. * * @return string */ TypeEnum getBaseType(); /** * Create type. * * @param types types * @param literals literals * @return type */ Type createType(List<Type> types, List<Object> literals); /** * Returns the list of parameters. * * @return List of paramenters */ List<Type> getParameters(); }
1,762
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/DecimalType.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.common.type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.ArrayList; import java.util.List; /** * Decimal type class. * * @author zhenl */ @Getter @EqualsAndHashCode(callSuper = true) public final class DecimalType extends AbstractType implements ParametricType { /** * Default decimal type. */ public static final DecimalType DECIMAL = createDecimalType(); /** * If scale is not specified, it defaults to 0 (no fractional digits). */ private static final int DEFAULT_SCALE = 0; /** * If no precision is specified, it defaults to 10. */ private static final int DEFAULT_PRECISION = 10; private final int precision; private final int scale; private DecimalType(final int precision, final int scale) { super( new TypeSignature( TypeEnum.DECIMAL, new ArrayList<TypeSignature>(), Lists.<Object>newArrayList( (long) precision, (long) scale ) ) ); Preconditions.checkArgument(precision >= 0, "Invalid decimal precision " + precision); Preconditions.checkArgument(scale >= 0 && scale <= precision, "Invalid decimal scale " + scale); this.precision = precision; this.scale = scale; } /** * Constructor. * * @param precision precision * @param scale scale * @return DecimalType */ public static DecimalType createDecimalType(final int precision, final int scale) { return new DecimalType(precision, scale); } /** * Constructor. * * @param precision precision * @return DecimalType */ public static DecimalType createDecimalType(final int precision) { return createDecimalType(precision, DEFAULT_SCALE); } /** * Constructor. * * @return DecimalType */ public static DecimalType createDecimalType() { return createDecimalType(DEFAULT_PRECISION, DEFAULT_SCALE); } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.DECIMAL; } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { switch (literals.size()) { case 0: return DecimalType.createDecimalType(); case 1: try { return DecimalType.createDecimalType(Integer.parseInt(String.valueOf(literals.get(0)))); } catch (NumberFormatException e) { throw new IllegalArgumentException("Decimal precision must be a number"); } case 2: try { return DecimalType.createDecimalType(Integer.parseInt(String.valueOf(literals.get(0))), Integer.parseInt(String.valueOf(literals.get(1)))); } catch (NumberFormatException e) { throw new IllegalArgumentException("Decimal parameters must be a number"); } default: throw new IllegalArgumentException("Expected 0, 1 or 2 parameters for DECIMAL type constructor."); } } }
1,763
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/RowType.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.common.type; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; /** * Row type. * * @author tgianos * @author zhenl * @since 1.0.0 */ @Getter public class RowType extends AbstractType implements ParametricType { /** * default type. */ static final RowType ROW = new RowType(Collections.<RowField>emptyList()); private final List<RowField> fields; /** * Constructor. * * @param fields The fields of this row */ public RowType(@Nonnull @NonNull final List<RowField> fields) { super( new TypeSignature( TypeEnum.ROW, Lists.transform( Lists.transform( fields, new Function<RowField, Type>() { public Type apply(@Nullable final RowField input) { return input == null ? null : input.getType(); } } ), new Function<Type, TypeSignature>() { public TypeSignature apply(@Nullable final Type input) { return input == null ? null : input.getTypeSignature(); } }), Lists.transform(fields, new Function<RowField, Object>() { public Object apply(@Nullable final RowField input) { return input == null ? null : input.getName(); } } ) ) ); this.fields = ImmutableList.copyOf(fields); } /** * Create a new Row Type. * * @param types The types to create can not be empty * @param names The literals to use. Can be null but if not must be the same length as types. * @return a new RowType */ public static RowType createRowType( @Nonnull @NonNull final List<Type> types, @Nonnull @NonNull final List<String> names ) { Preconditions.checkArgument(!types.isEmpty(), "types is empty"); final ImmutableList.Builder<RowField> builder = ImmutableList.builder(); Preconditions.checkArgument( types.size() == names.size(), "types and names must be matched in size" ); for (int i = 0; i < types.size(); i++) { builder.add(new RowField(types.get(i), names.get(i))); } return new RowType(builder.build()); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.ROW; } /** * {@inheritDoc} */ @Override public RowType createType(@Nonnull @NonNull final List<Type> types, @Nonnull @NonNull final List<Object> literals) { final ImmutableList.Builder<String> builder = ImmutableList.builder(); for (final Object literal : literals) { builder.add(TypeUtils.checkType(literal, String.class, "literal")); } return RowType.createRowType(types, builder.build()); } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { final ImmutableList.Builder<Type> result = ImmutableList.builder(); for (final RowField field : this.fields) { result.add(field.getType()); } return result.build(); } /** * Row field. */ @Getter @EqualsAndHashCode public static class RowField { private final Type type; private final String name; /** * constructor. * * @param type type * @param name name */ public RowField(@Nonnull @NonNull final Type type, @Nonnull @NonNull final String name) { this.type = type; this.name = name; } } }
1,764
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/TypeRegistry.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.common.type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Type mapping between canonical and connector types. * * @author zhenl */ public final class TypeRegistry implements TypeManager { //initailzed during class loading private static final TypeRegistry INSTANCE = new TypeRegistry(); private final ConcurrentMap<TypeSignature, Type> types = new ConcurrentHashMap<>(); private final ConcurrentMap<TypeEnum, ParametricType> parametricTypes = new ConcurrentHashMap<>(); /** * Constructor. */ private TypeRegistry() { Preconditions.checkNotNull(types, "types is null"); addType(BaseType.UNKNOWN); addType(BaseType.BIGINT); addType(BaseType.BOOLEAN); addType(BaseType.FLOAT); addType(BaseType.DOUBLE); addType(BaseType.DATE); addType(BaseType.INT); addType(BaseType.SMALLINT); addType(BaseType.TINYINT); addType(BaseType.JSON); addType(BaseType.TIME); addType(BaseType.TIME_WITH_TIME_ZONE); addType(BaseType.INTERVAL_DAY_TO_SECOND); addType(BaseType.INTERVAL_YEAR_TO_MONTH); addType(BaseType.STRING); addType(BaseType.TIMESTAMP); addType(BaseType.TIMESTAMP_WITH_TIME_ZONE); addParametricType(DecimalType.DECIMAL); addParametricType(CharType.CHAR); addParametricType(MapType.MAP); addParametricType(RowType.ROW); addParametricType(ArrayType.ARRAY); addParametricType(VarbinaryType.VARBINARY); addParametricType(VarcharType.VARCHAR); } public static TypeRegistry getTypeRegistry() { return INSTANCE; } /** * Verify type class isn't null. * * @param type parameter */ public static void verifyTypeClass(final Type type) { Preconditions.checkNotNull(type, "type is null"); } /** * {@inheritDoc} */ @Override public Type getType(final TypeSignature signature) { final Type type = types.get(signature); if (type == null) { return instantiateParametricType(signature); } return type; } /** * {@inheritDoc} */ @Override public Type getParameterizedType(final TypeEnum baseType, final List<TypeSignature> typeParameters, final List<Object> literalParameters) { return getType(new TypeSignature(baseType, typeParameters, literalParameters)); } private Type instantiateParametricType(final TypeSignature signature) { final ImmutableList.Builder<Type> parameterTypes = ImmutableList.builder(); for (TypeSignature parameter : signature.getParameters()) { final Type parameterType = getType(parameter); if (parameterType == null) { return null; } parameterTypes.add(parameterType); } final ParametricType parametricType = parametricTypes.get(signature.getBase()); if (parametricType == null) { return null; } final Type instantiatedType = parametricType.createType(parameterTypes.build(), signature.getLiteralParameters()); Preconditions.checkState(instantiatedType.getTypeSignature().equals(signature), "Instantiated parametric type name (%s) does not match expected name (%s)", instantiatedType, signature); return instantiatedType; } /** * Add valid type to registry. * * @param type type */ public void addType(final Type type) { verifyTypeClass(type); final Type existingType = types.putIfAbsent(type.getTypeSignature(), type); Preconditions.checkState(existingType == null || existingType.equals(type), "Type %s is already registered", type); } /** * Add complex type to regiestry. * * @param parametricType Type */ public void addParametricType(final ParametricType parametricType) { final TypeEnum baseType = parametricType.getBaseType(); Preconditions.checkArgument(!parametricTypes.containsKey(baseType), "Parametric type already registered: %s", baseType); parametricTypes.putIfAbsent(baseType, parametricType); } /** * {@inheritDoc} */ @Override public List<Type> getTypes() { return null; } }
1,765
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/CharType.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.common.type; import com.google.common.collect.ImmutableList; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Char type class. * * @author zhenl */ @Getter @EqualsAndHashCode(callSuper = true) public class CharType extends AbstractType implements ParametricType { /** * Default character type. */ public static final CharType CHAR = new CharType(1); private final int length; /** * Constructor. * * @param length length */ public CharType(final int length) { super( new TypeSignature( TypeEnum.CHAR, new ArrayList<TypeSignature>(), Collections.<Object>singletonList((long) length))); if (length < 0) { throw new IllegalArgumentException("Invalid VARCHAR length " + length); } this.length = length; } /** * Creates the character type. * * @param length legnth of the type * @return CharType */ public static CharType createCharType(final int length) { return new CharType(length); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.CHAR; } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { if (literals.isEmpty()) { return createCharType(1); } if (literals.size() != 1) { throw new IllegalArgumentException("Expected at most one parameter for CHAR"); } try { return createCharType(Integer.parseInt(String.valueOf(literals.get(0)))); } catch (NumberFormatException e) { throw new IllegalArgumentException("CHAR length must be a number"); } } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(); } }
1,766
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/VarcharType.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.common.type; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import lombok.Getter; import java.util.ArrayList; import java.util.List; /** * Varchar type. * * @author zhenl */ @Getter public final class VarcharType extends AbstractType implements ParametricType { /** * Default varchar type. */ public static final VarcharType VARCHAR = new VarcharType(1); private final int length; private VarcharType(final int length) { super( new TypeSignature( TypeEnum.VARCHAR, new ArrayList<TypeSignature>(), Lists.<Object>newArrayList((long) length))); if (length < 0) { throw new IllegalArgumentException("Invalid VARCHAR length " + length); } this.length = length; } /** * Cretes varchar type. * * @param length length * @return VarcharType */ public static VarcharType createVarcharType(final int length) { return new VarcharType(length); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.VARCHAR; } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(); } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { if (literals.isEmpty()) { return createVarcharType(1); } if (literals.size() != 1) { throw new IllegalArgumentException("Expected at most one parameter for VARCHAR"); } try { return createVarcharType(Integer.parseInt(String.valueOf(literals.get(0)))); } catch (NumberFormatException e) { throw new IllegalArgumentException("VARCHAR length must be a number"); } } }
1,767
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/MapType.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.common.type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import lombok.EqualsAndHashCode; import lombok.Getter; import java.util.List; /** * Map type class. * * @author zhenl */ @Getter @EqualsAndHashCode(callSuper = true) public class MapType extends AbstractType implements ParametricType { /** * default. */ public static final MapType MAP = new MapType(BaseType.UNKNOWN, BaseType.UNKNOWN); private final Type keyType; private final Type valueType; /** * Constructor. * * @param keyType keytype * @param valueType valuetype */ public MapType(final Type keyType, final Type valueType) { super(TypeUtils.parameterizedTypeSignature(TypeEnum.MAP, keyType.getTypeSignature(), valueType.getTypeSignature())); this.keyType = keyType; this.valueType = valueType; } /** * {@inheritDoc} */ @Override public String getDisplayName() { return "map<" + keyType.getDisplayName() + ", " + valueType.getDisplayName() + ">"; } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(getKeyType(), getValueType()); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.MAP; } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { Preconditions.checkArgument(types.size() == 2, "Expected two types"); Preconditions.checkArgument(literals.isEmpty(), "Unexpected literals: %s", literals); return new MapType(types.get(0), types.get(1)); } }
1,768
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/VarbinaryType.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.common.type; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import lombok.Getter; import java.util.ArrayList; import java.util.List; /** * VarbinaryType type. * * @author zhenl */ @Getter public final class VarbinaryType extends AbstractType implements ParametricType { /** * Default VarbinaryType type. */ public static final VarbinaryType VARBINARY = new VarbinaryType(Integer.MAX_VALUE); private final int length; private VarbinaryType(final int length) { super(new TypeSignature( TypeEnum.VARBINARY, new ArrayList<TypeSignature>(), Lists.<Object>newArrayList((long) length))); if (length < 0) { throw new IllegalArgumentException("Invalid VARBINARY length " + length); } this.length = length; } /** * Creates VarbinaryType. * * @param length length * @return VarcharType */ public static VarbinaryType createVarbinaryType(final int length) { return new VarbinaryType(length); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.VARBINARY; } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(); } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { if (literals.isEmpty()) { return createVarbinaryType(Integer.MAX_VALUE); } if (literals.size() != 1) { throw new IllegalArgumentException("Expected at most one parameter for VARBINARY"); } try { return createVarbinaryType(Integer.parseInt(String.valueOf(literals.get(0)))); } catch (NumberFormatException e) { throw new IllegalArgumentException("VARBINARY length must be a number"); } } }
1,769
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/BaseType.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.common.type; import lombok.EqualsAndHashCode; /** * TypeEnum class implements the type interface. * * @author zhenl */ @EqualsAndHashCode(callSuper = true) public class BaseType extends AbstractType { /** * BOOLEAN type. */ public static final Type BOOLEAN = createBaseType(TypeEnum.BOOLEAN); /** * TINYINT type. */ public static final Type TINYINT = createBaseType(TypeEnum.TINYINT); /** * SMALLINT type. */ public static final Type SMALLINT = createBaseType(TypeEnum.SMALLINT); /** * INT type. */ public static final Type INT = createBaseType(TypeEnum.INT); /** * BIGINT type. */ public static final Type BIGINT = createBaseType(TypeEnum.BIGINT); /** * FLOAT type. */ public static final Type FLOAT = createBaseType(TypeEnum.FLOAT); /** * DOUBLE type. */ public static final Type DOUBLE = createBaseType(TypeEnum.DOUBLE); /** * STRING type. */ public static final Type STRING = createBaseType(TypeEnum.STRING); /** * JSON type. */ public static final Type JSON = createBaseType(TypeEnum.JSON); /** * DATE type. */ public static final Type DATE = createBaseType(TypeEnum.DATE); /** * TIME type. */ public static final Type TIME = createBaseType(TypeEnum.TIME); /** * TIME_WITH_TIME_ZONE type. */ public static final Type TIME_WITH_TIME_ZONE = createBaseType(TypeEnum.TIME_WITH_TIME_ZONE); /** * TIMESTAMP type. */ public static final Type TIMESTAMP = createBaseType(TypeEnum.TIMESTAMP); /** * TIMESTAMP_WITH_TIME_ZONE type. */ public static final Type TIMESTAMP_WITH_TIME_ZONE = createBaseType(TypeEnum.TIMESTAMP_WITH_TIME_ZONE); /** * INTERVAL_YEAR_TO_MONTH type. */ public static final Type INTERVAL_YEAR_TO_MONTH = createBaseType(TypeEnum.INTERVAL_YEAR_TO_MONTH); /** * INTERVAL_DAY_TO_SECOND type. */ public static final Type INTERVAL_DAY_TO_SECOND = createBaseType(TypeEnum.INTERVAL_DAY_TO_SECOND); /** * UNKNOWN. */ public static final Type UNKNOWN = createBaseType(TypeEnum.UNKNOWN); /** * BaseType constructor. * * @param signature base type */ public BaseType(final TypeSignature signature) { super(signature); } private static BaseType createBaseType(final TypeEnum baseType) { return new BaseType(new TypeSignature(baseType)); } }
1,770
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/TypeSignature.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.common.type; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Type signature class. * * @author zhenl */ @Getter @EqualsAndHashCode public class TypeSignature { protected final TypeEnum base; protected final List<TypeSignature> parameters; protected final List<Object> literalParameters; /** * Type signature constructor. * * @param base base type */ public TypeSignature(@Nonnull @NonNull final TypeEnum base) { this.base = base; this.parameters = Lists.newArrayList(); this.literalParameters = Lists.newArrayList(); } /** * Type signature constructor. * * @param base base type * @param parameters type parameter * @param literalParameters literal parameter */ public TypeSignature( @Nonnull @NonNull final TypeEnum base, @Nonnull @NonNull final List<TypeSignature> parameters, @Nullable final List<Object> literalParameters ) { if (literalParameters != null) { for (final Object literal : literalParameters) { Preconditions.checkArgument( literal instanceof String || literal instanceof Long, "Unsupported literal type: %s", literal.getClass()); } this.literalParameters = ImmutableList.copyOf(literalParameters); } else { this.literalParameters = ImmutableList.copyOf(Lists.newArrayList()); } this.base = base; this.parameters = Collections.unmodifiableList(new ArrayList<>(parameters)); } /** * Type signature constructor. * * @param base base type * @param parameters type parameter * @param literalParameters literal parameter */ private TypeSignature( @Nonnull @NonNull final String base, @Nonnull @NonNull final List<TypeSignature> parameters, @Nullable final List<Object> literalParameters ) { this(TypeEnum.fromName(base), parameters, literalParameters); } /** * Parse Type Signature. * * @param signature signature string * @return TypeSignature */ @JsonCreator public static TypeSignature parseTypeSignature(final String signature) { if (!signature.contains("<") && !signature.contains("(")) { return new TypeSignature(signature, new ArrayList<TypeSignature>(), new ArrayList<>()); } String baseName = null; final List<TypeSignature> parameters = new ArrayList<>(); final List<Object> literalParameters = new ArrayList<>(); int parameterStart = -1; int bracketCount = 0; boolean inLiteralParameters = false; for (int i = 0; i < signature.length(); i++) { final char c = signature.charAt(i); if (c == '<') { if (bracketCount == 0) { Preconditions.checkArgument(baseName == null, "Expected baseName to be null"); Preconditions.checkArgument(parameterStart == -1, "Expected parameter start to be -1"); baseName = signature.substring(0, i); parameterStart = i + 1; } bracketCount++; } else if (c == '>') { bracketCount--; Preconditions.checkArgument(bracketCount >= 0, "Bad type signature: '%s'", signature); if (bracketCount == 0) { Preconditions.checkArgument(parameterStart >= 0, "Bad type signature: '%s'", signature); parameters.add(parseTypeSignature(signature.substring(parameterStart, i))); parameterStart = i + 1; if (i == signature.length() - 1) { return new TypeSignature(baseName, parameters, literalParameters); } } } else if (c == ',') { if (bracketCount == 1 && !inLiteralParameters) { Preconditions.checkArgument(parameterStart >= 0, "Bad type signature: '%s'", signature); parameters.add(parseTypeSignature(signature.substring(parameterStart, i))); parameterStart = i + 1; } else if (bracketCount == 0 && inLiteralParameters) { Preconditions.checkArgument(parameterStart >= 0, "Bad type signature: '%s'", signature); literalParameters.add(parseLiteral(signature.substring(parameterStart, i))); parameterStart = i + 1; } } else if (c == '(') { Preconditions.checkArgument(!inLiteralParameters, "Bad type signature: '%s'", signature); inLiteralParameters = true; if (bracketCount == 0) { if (baseName == null) { Preconditions.checkArgument(parameters.isEmpty(), "Expected no parameters"); Preconditions.checkArgument(parameterStart == -1, "Expected parameter start to be -1"); baseName = signature.substring(0, i); } parameterStart = i + 1; } } else if (c == ')') { Preconditions.checkArgument(inLiteralParameters, "Bad type signature: '%s'", signature); inLiteralParameters = false; if (bracketCount == 0) { Preconditions.checkArgument(i == signature.length() - 1, "Bad type signature: '%s'", signature); Preconditions.checkArgument(parameterStart >= 0, "Bad type signature: '%s'", signature); literalParameters.add(parseLiteral(signature.substring(parameterStart, i))); return new TypeSignature(baseName, parameters, literalParameters); } } } throw new IllegalArgumentException(String.format("Bad type signature: '%s'", signature)); } private static Object parseLiteral(final String literal) { if (literal.startsWith("'") || literal.endsWith("'")) { Preconditions.checkArgument(literal.startsWith("'") && literal.endsWith("'"), "Bad literal: '%s'", literal); return literal.substring(1, literal.length() - 1); } else { return Long.parseLong(literal); } } /** * {@inheritDoc} */ @Override @JsonValue public String toString() { final StringBuilder typeName = new StringBuilder(base.getType()); if (!parameters.isEmpty()) { typeName.append("<"); boolean first = true; for (TypeSignature parameter : parameters) { if (!first) { typeName.append(","); } first = false; typeName.append(parameter.toString()); } typeName.append(">"); } if (!literalParameters.isEmpty()) { typeName.append("("); boolean first = true; for (Object parameter : literalParameters) { if (!first) { typeName.append(","); } first = false; if (parameter instanceof String) { typeName.append("'").append(parameter).append("'"); } else { typeName.append(parameter.toString()); } } typeName.append(")"); } return typeName.toString(); } }
1,771
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/ArrayType.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.common.type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import lombok.Getter; import java.util.List; /** * Array type class. * * @author zhenl */ @Getter public class ArrayType extends AbstractType implements ParametricType { /** * default. */ static final ArrayType ARRAY = new ArrayType(BaseType.UNKNOWN); private final Type elementType; /** * Constructor. * * @param elementType elementtype */ public ArrayType(final Type elementType) { super(TypeUtils.parameterizedTypeSignature(TypeEnum.ARRAY, elementType.getTypeSignature())); this.elementType = Preconditions.checkNotNull(elementType, "elementType is null"); } /** * {@inheritDoc} */ @Override public TypeEnum getBaseType() { return TypeEnum.ARRAY; } /** * {@inheritDoc} */ @Override public Type createType(final List<Type> types, final List<Object> literals) { Preconditions.checkArgument(types.size() == 1, "Expected only one type, got %s", types); Preconditions.checkArgument(literals.isEmpty(), "Unexpected literals: %s", literals); return new ArrayType(types.get(0)); } /** * {@inheritDoc} */ @Override public List<Type> getParameters() { return ImmutableList.of(getElementType()); } }
1,772
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/type/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. * */ /** * Canonical type classes. * * @author zhenl */ package com.netflix.metacat.common.type;
1,773
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatUserMetadataException.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.common.exception; /** * Exception from user metadata service. * TODO: This should be replaced by a BadRequestException from JAX-RS 2.x once we support the newer JAX-RS version. */ public class MetacatUserMetadataException extends MetacatException { /** * Constructor. * * @param message exception message */ public MetacatUserMetadataException(final String message) { super(message); } }
1,774
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatTooManyRequestsException.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.common.exception; /** * Exception for too many RDS connections or pool empty. * * @author zhenl */ public class MetacatTooManyRequestsException extends MetacatException { /** * Constructor. * * @param reason exception message */ public MetacatTooManyRequestsException(final String reason) { super(reason); } }
1,775
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatPreconditionFailedException.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.common.exception; /** * Exception when operation failed precondition. Ex. if a locked table is updated, this exception will be thrown. * * @since 1.2.0 * @author amajumdar */ public class MetacatPreconditionFailedException extends MetacatException { /** * Constructor. * * @param reason exception message */ public MetacatPreconditionFailedException(final String reason) { super(reason); } }
1,776
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatNotSupportedException.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.common.exception; /** * Metacat not supported exception. */ public class MetacatNotSupportedException extends MetacatException { /** * Constructor. * * @param message exception message */ public MetacatNotSupportedException(final String message) { super(message); } }
1,777
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatNotFoundException.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.common.exception; /** * TODO: This should be replaced by a NotFoundException from JAX-RS 2.x once we support the newer JAX-RS version. */ public class MetacatNotFoundException extends MetacatException { /** * Constructor. * * @param message exception message */ public MetacatNotFoundException(final String message) { super(message); } }
1,778
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatException.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.common.exception; /** * Base exception for Metacat errors exposed externally. * * @author amajumdar * @author tgianos */ public class MetacatException extends RuntimeException { /** * Constructor. */ public MetacatException() { super(); } /** * Constructor. * * @param msg The error message to pass along */ public MetacatException(final String msg) { super(msg); } /** * Constructor. * * @param msg The error message to pass along * @param cause The cause of the error */ public MetacatException(final String msg, final Throwable cause) { super(msg, cause); } }
1,779
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatBadRequestException.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.common.exception; /** * TODO: This should be replaced by a BadRequestException from JAX-RS 2.x once we support the newer JAX-RS version. */ public class MetacatBadRequestException extends MetacatException { /** * Constructor. * * @param reason exception message */ public MetacatBadRequestException(final String reason) { super(reason); } }
1,780
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatAlreadyExistsException.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.common.exception; /** * Metacat exception for already exists entities. */ public class MetacatAlreadyExistsException extends MetacatException { /** * Constructor. * * @param message exception message */ public MetacatAlreadyExistsException(final String message) { super(message); } }
1,781
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/MetacatUnAuthorizedException.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.common.exception; /** * MetacatUnAuthorizedException Exception. * @author zhenl * @since 1.2.0 */ public class MetacatUnAuthorizedException extends MetacatException { /** * Constructor. * * @param message message */ public MetacatUnAuthorizedException(final String message) { super(message); } }
1,782
0
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common
Create_ds/metacat/metacat-common/src/main/java/com/netflix/metacat/common/exception/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. * */ /** * Package containing the Metacat exceptions. * * @author amajumdar */ @ParametersAreNonnullByDefault package com.netflix.metacat.common.exception; import javax.annotation.ParametersAreNonnullByDefault;
1,783
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/AbstractThriftServer.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.thrift; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.metacat.common.server.properties.Config; import com.netflix.metacat.common.server.util.RegistryUtil; import com.netflix.spectator.api.Registry; import lombok.Getter; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.thrift.TProcessor; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TServerEventHandler; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Base implementation for thrift server. */ @Slf4j public abstract class AbstractThriftServer { protected final Config config; protected final Registry registry; @Getter private final int portNumber; private final String threadPoolNameFormat; private final AtomicBoolean stopping = new AtomicBoolean(false); private final AtomicInteger serverThreadCount = new AtomicInteger(0); @Getter private TServer server; protected AbstractThriftServer( @NonNull final Config config, @NonNull final Registry registry, final int portNumber, @NonNull final String threadPoolNameFormat ) { this.config = config; this.registry = registry; this.portNumber = portNumber; this.threadPoolNameFormat = threadPoolNameFormat; } /** * Returns the thrift processor. * * @return thrift processor */ public abstract TProcessor getProcessor(); /** * Returns the server event handler. * * @return server event handler */ public abstract TServerEventHandler getServerEventHandler(); /** * Returns the server name. * * @return server name */ public abstract String getServerName(); /** * Returns true, if the server event handler exists. * * @return true, if the server event handler exists */ public abstract boolean hasServerEventHandler(); /** * Server initialization. * * @throws Exception error */ public void start() throws Exception { log.info("initializing thrift server {}", getServerName()); final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(threadPoolNameFormat) .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception in thread: {}", t.getName(), e)) .build(); final ExecutorService executorService = new ThreadPoolExecutor( Math.min(2, config.getThriftServerMaxWorkerThreads()), config.getThriftServerMaxWorkerThreads(), 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory ); RegistryUtil.registerThreadPool(registry, threadPoolNameFormat, (ThreadPoolExecutor) executorService); final int timeout = config.getThriftServerSocketClientTimeoutInSeconds() * 1000; final TServerTransport serverTransport = new TServerSocket(portNumber, timeout); startServing(executorService, serverTransport); } private void startServing(final ExecutorService executorService, final TServerTransport serverTransport) { if (!stopping.get()) { final TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport) .processor(getProcessor()) .executorService(executorService); server = new TThreadPoolServer(serverArgs); if (hasServerEventHandler()) { server.setServerEventHandler(getServerEventHandler()); } final String threadName = getServerName() + "-thread-#" + serverThreadCount.incrementAndGet(); new Thread(threadName) { @Override public void run() { log.debug("starting serving"); try { server.serve(); } catch (Throwable t) { if (!stopping.get()) { log.error("Unexpected exception in {}. This probably " + "means that the worker pool was exhausted. " + "Increase 'metacat.thrift.server_max_worker_threads' " + "from {} or throttle the number of requests. " + "This server thread is not in a bad state so starting a new one.", getServerName(), config.getThriftServerMaxWorkerThreads(), t); startServing(executorService, serverTransport); } else { log.debug("stopping serving"); } } log.debug("started serving"); } }.start(); } } /** * Server shutdown. * * @throws Exception error */ public void stop() throws Exception { log.info("stopping thrift server {}", getServerName()); if (stopping.compareAndSet(false, true) && server != null) { log.debug("stopping serving"); server.stop(); log.debug("stopped serving"); } } }
1,784
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/CatalogThriftService.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.thrift; 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.spectator.api.Registry; import org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore; import org.apache.thrift.TProcessor; import org.apache.thrift.server.TServerEventHandler; /** * Thrift service. */ public class CatalogThriftService extends AbstractThriftServer { private final String catalogName; private final HiveConverters hiveConverters; private final MetacatV1 metacatV1; private final PartitionV1 partitionV1; /** * Constructor. * * @param config config * @param hiveConverters hive converter * @param metacatV1 Metacat V1 resource * @param partitionV1 Partition V1 resource * @param catalogName catalog name * @param portNumber port * @param registry registry for spectator */ public CatalogThriftService( final Config config, final HiveConverters hiveConverters, final MetacatV1 metacatV1, final PartitionV1 partitionV1, final String catalogName, final int portNumber, final Registry registry ) { super(config, registry, portNumber, "thrift-pool-" + catalogName + "-" + portNumber + "-%d"); this.hiveConverters = hiveConverters; this.metacatV1 = metacatV1; this.partitionV1 = partitionV1; this.catalogName = catalogName; } /** * {@inheritDoc} */ @Override public TProcessor getProcessor() { return new ThriftHiveMetastore.Processor<>( new CatalogThriftHiveMetastore(config, hiveConverters, metacatV1, partitionV1, catalogName, registry) ); } /** * {@inheritDoc} */ @Override public TServerEventHandler getServerEventHandler() { return new CatalogThriftEventHandler(); } /** * {@inheritDoc} */ @Override public String getServerName() { return "thrift server for " + catalogName + " on port " + this.getPortNumber(); } /** * {@inheritDoc} */ @Override public boolean hasServerEventHandler() { return true; } }
1,785
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/CatalogThriftHiveMetastore.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.thrift; import com.facebook.fb303.FacebookBase; import com.facebook.fb303.FacebookService; import com.facebook.fb303.fb_status; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.metacat.common.MetacatRequestContext; import com.netflix.metacat.common.QualifiedName; import com.netflix.metacat.common.dto.DatabaseCreateRequestDto; import com.netflix.metacat.common.dto.DatabaseDto; import com.netflix.metacat.common.dto.FieldDto; import com.netflix.metacat.common.dto.GetPartitionsRequestDto; import com.netflix.metacat.common.dto.PartitionDto; import com.netflix.metacat.common.dto.PartitionsSaveRequestDto; import com.netflix.metacat.common.dto.StorageDto; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.exception.MetacatAlreadyExistsException; import com.netflix.metacat.common.exception.MetacatNotFoundException; import com.netflix.metacat.common.exception.MetacatPreconditionFailedException; import com.netflix.metacat.common.server.api.v1.MetacatV1; import com.netflix.metacat.common.server.api.v1.PartitionV1; 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.extern.slf4j.Slf4j; import org.apache.hadoop.hive.common.FileUtils; import org.apache.hadoop.hive.metastore.MetaStoreUtils; import org.apache.hadoop.hive.metastore.Warehouse; import org.apache.hadoop.hive.metastore.api.AbortTxnRequest; import org.apache.hadoop.hive.metastore.api.AddDynamicPartitions; import org.apache.hadoop.hive.metastore.api.AddPartitionsRequest; import org.apache.hadoop.hive.metastore.api.AddPartitionsResult; import org.apache.hadoop.hive.metastore.api.AggrStats; import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; import org.apache.hadoop.hive.metastore.api.CheckLockRequest; import org.apache.hadoop.hive.metastore.api.ColumnStatistics; import org.apache.hadoop.hive.metastore.api.CommitTxnRequest; import org.apache.hadoop.hive.metastore.api.CompactionRequest; import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.DropPartitionsExpr; import org.apache.hadoop.hive.metastore.api.DropPartitionsRequest; import org.apache.hadoop.hive.metastore.api.DropPartitionsResult; import org.apache.hadoop.hive.metastore.api.EnvironmentContext; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.FireEventRequest; import org.apache.hadoop.hive.metastore.api.FireEventResponse; import org.apache.hadoop.hive.metastore.api.Function; import org.apache.hadoop.hive.metastore.api.GetOpenTxnsInfoResponse; import org.apache.hadoop.hive.metastore.api.GetOpenTxnsResponse; import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleRequest; import org.apache.hadoop.hive.metastore.api.GetPrincipalsInRoleResponse; import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalRequest; import org.apache.hadoop.hive.metastore.api.GetRoleGrantsForPrincipalResponse; import org.apache.hadoop.hive.metastore.api.GrantRevokePrivilegeRequest; import org.apache.hadoop.hive.metastore.api.GrantRevokePrivilegeResponse; import org.apache.hadoop.hive.metastore.api.GrantRevokeRoleRequest; import org.apache.hadoop.hive.metastore.api.GrantRevokeRoleResponse; import org.apache.hadoop.hive.metastore.api.HeartbeatRequest; import org.apache.hadoop.hive.metastore.api.HeartbeatTxnRangeRequest; import org.apache.hadoop.hive.metastore.api.HeartbeatTxnRangeResponse; import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege; import org.apache.hadoop.hive.metastore.api.HiveObjectRef; import org.apache.hadoop.hive.metastore.api.Index; import org.apache.hadoop.hive.metastore.api.InvalidInputException; import org.apache.hadoop.hive.metastore.api.InvalidObjectException; import org.apache.hadoop.hive.metastore.api.InvalidOperationException; import org.apache.hadoop.hive.metastore.api.LockRequest; import org.apache.hadoop.hive.metastore.api.LockResponse; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.NotificationEventRequest; import org.apache.hadoop.hive.metastore.api.NotificationEventResponse; import org.apache.hadoop.hive.metastore.api.OpenTxnRequest; import org.apache.hadoop.hive.metastore.api.OpenTxnsResponse; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.PartitionEventType; import org.apache.hadoop.hive.metastore.api.PartitionListComposingSpec; import org.apache.hadoop.hive.metastore.api.PartitionSpec; import org.apache.hadoop.hive.metastore.api.PartitionsByExprRequest; import org.apache.hadoop.hive.metastore.api.PartitionsByExprResult; import org.apache.hadoop.hive.metastore.api.PartitionsStatsRequest; import org.apache.hadoop.hive.metastore.api.PartitionsStatsResult; import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet; import org.apache.hadoop.hive.metastore.api.PrincipalType; import org.apache.hadoop.hive.metastore.api.PrivilegeBag; import org.apache.hadoop.hive.metastore.api.PrivilegeGrantInfo; import org.apache.hadoop.hive.metastore.api.RequestPartsSpec; import org.apache.hadoop.hive.metastore.api.Role; import org.apache.hadoop.hive.metastore.api.SetPartitionsStatsRequest; import org.apache.hadoop.hive.metastore.api.ShowCompactRequest; import org.apache.hadoop.hive.metastore.api.ShowCompactResponse; import org.apache.hadoop.hive.metastore.api.ShowLocksRequest; import org.apache.hadoop.hive.metastore.api.ShowLocksResponse; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.metastore.api.TableStatsRequest; import org.apache.hadoop.hive.metastore.api.TableStatsResult; import org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore; import org.apache.hadoop.hive.metastore.api.Type; import org.apache.hadoop.hive.metastore.api.UnlockRequest; import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.optimizer.ppr.PartitionExpressionForMetastore; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.thrift.TException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Metacat Hive thrift implementation. This uses the Metacat Resource classes. */ @Slf4j public class CatalogThriftHiveMetastore extends FacebookBase implements FacebookService.Iface, ThriftHiveMetastore.Iface { private static final Joiner AND_JOINER = Joiner.on(" and "); private static final LoadingCache<String, Pattern> PATTERNS = CacheBuilder.newBuilder() .build(new CacheLoader<String, Pattern>() { public Pattern load( @Nonnull final String regex) { return Pattern.compile(regex); } }); private final String catalogName; private final Config config; private final HiveConverters hiveConverters; private final PartitionV1 partV1; private final MetacatV1 v1; private final Map<String, List<PrivilegeGrantInfo>> defaultRolesPrivilegeSet = Maps.newHashMap(ImmutableMap.of("users", Lists.newArrayList(new PrivilegeGrantInfo("ALL", 0, "hadoop", PrincipalType.ROLE, true)))); private final Registry registry; /** * Constructor. * * @param config config * @param hiveConverters hive converter * @param metacatV1 Metacat V1 resource * @param partitionV1 Partition V1 resource * @param catalogName catalog name * @param registry registry of spectator */ public CatalogThriftHiveMetastore( final Config config, final HiveConverters hiveConverters, final MetacatV1 metacatV1, final PartitionV1 partitionV1, final String catalogName, final Registry registry ) { super("CatalogThriftHiveMetastore"); this.config = Preconditions.checkNotNull(config, "config is null"); this.hiveConverters = Preconditions.checkNotNull(hiveConverters, "hive converters is null"); this.v1 = Preconditions.checkNotNull(metacatV1, "metacat api is null"); this.partV1 = Preconditions.checkNotNull(partitionV1, "partition api is null"); this.catalogName = normalizeIdentifier(Preconditions.checkNotNull(catalogName, "catalog name is required")); this.registry = registry; } private static String normalizeIdentifier(@Nullable final String s) { if (s == null) { return null; } else { return s.trim().toLowerCase(Locale.ENGLISH); } } /** * {@inheritDoc} */ @Override public void abort_txn(final AbortTxnRequest rqst) throws TException { throw unimplemented("abort_txn", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void add_dynamic_partitions(final AddDynamicPartitions rqst) throws TException { throw unimplemented("add_dynamic_partitions", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public Index add_index(final Index newIndex, final Table indexTable) throws TException { throw unimplemented("add_index", new Object[]{newIndex, indexTable}); } /** * {@inheritDoc} */ @Override public Partition add_partition(final Partition newPart) throws TException { return add_partition_with_environment_context(newPart, null); } /** * {@inheritDoc} */ @Override public Partition add_partition_with_environment_context( final Partition newPart, @Nullable final EnvironmentContext ec ) throws TException { final String dbName = normalizeIdentifier(newPart.getDbName()); final String tableName = normalizeIdentifier(newPart.getTableName()); return requestWrapper("add_partition_with_environment_context", new Object[]{dbName, tableName, ec}, () -> { addPartitionsCore(dbName, tableName, ImmutableList.of(newPart), false); return newPart; }); } /** * {@inheritDoc} */ @Override public int add_partitions(final List<Partition> newParts) throws TException { if (newParts == null || newParts.size() == 0) { return 0; } final String dbName = normalizeIdentifier(newParts.get(0).getDbName()); final String tableName = normalizeIdentifier(newParts.get(0).getTableName()); return requestWrapper("add_partition", new Object[]{dbName, tableName}, () -> { addPartitionsCore(dbName, tableName, newParts, false); return newParts.size(); }); } /** * {@inheritDoc} */ @Override public int add_partitions_pspec(final List<PartitionSpec> newParts) throws TException { if (newParts == null || newParts.isEmpty()) { return 0; } final String dbName = newParts.get(0).getDbName(); final String tableName = newParts.get(0).getTableName(); return requestWrapper("add_partition", new Object[]{dbName, tableName}, () -> { final PartitionSpecProxy partitionSpecProxy = PartitionSpecProxy.Factory.get(newParts); final PartitionSpecProxy.PartitionIterator partitionIterator = partitionSpecProxy.getPartitionIterator(); final List<Partition> partitions = addPartitionsCore(dbName, tableName, Lists.newArrayList(partitionIterator), false); return partitions.size(); }); } /** * {@inheritDoc} */ @Override public AddPartitionsResult add_partitions_req(final AddPartitionsRequest request) throws TException { final String dbName = normalizeIdentifier(request.getDbName()); final String tableName = normalizeIdentifier(request.getTblName()); return requestWrapper("add_partition", new Object[]{dbName, tableName}, () -> { final List<Partition> partitions = addPartitionsCore(dbName, tableName, request.getParts(), request.isIfNotExists()); final AddPartitionsResult result = new AddPartitionsResult(); result.setPartitions(partitions); return result; }); } private List<Partition> addPartitionsCore(final String dbName, final String tblName, final List<Partition> parts, final boolean ifNotExists) throws TException { log.debug("Ignoring {} since metacat save partitions will do an update if it already exists", ifNotExists); final TableDto tableDto = v1.getTable(catalogName, dbName, tblName, true, false, false); final List<String> partitionKeys = tableDto.getPartition_keys(); if (partitionKeys == null || partitionKeys.isEmpty()) { throw new MetaException("Unable to add partition to unpartitioned table: " + tableDto.getName()); } final PartitionsSaveRequestDto partitionsSaveRequestDto = new PartitionsSaveRequestDto(); final List<PartitionDto> converted = Lists.newArrayListWithCapacity(parts.size()); for (Partition partition : parts) { converted.add(hiveConverters.hiveToMetacatPartition(tableDto, partition)); } partitionsSaveRequestDto.setPartitions(converted); partV1.savePartitions(catalogName, dbName, tblName, partitionsSaveRequestDto); return parts; } /** * {@inheritDoc} */ @Override public void alter_database(final String dbname, final Database db) throws TException { requestWrapper("update_database", new Object[]{db}, () -> { if (dbname == null || db == null) { throw new InvalidInputException("Invalid database request"); } v1.updateDatabase(catalogName, normalizeIdentifier(dbname), DatabaseCreateRequestDto.builder().metadata(db.getParameters()).uri(db.getLocationUri()).build()); return null; }); } /** * {@inheritDoc} */ @Override public void alter_function(final String dbName, final String funcName, final Function newFunc) throws TException { throw unimplemented("alter_function", new Object[]{dbName, funcName, newFunc}); } /** * {@inheritDoc} */ @Override public void alter_index(final String dbname, final String baseTblName, final String idxName, final Index newIdx) throws TException { throw unimplemented("alter_index", new Object[]{dbname, baseTblName, idxName, newIdx}); } /** * {@inheritDoc} */ @Override public void alter_partition(final String dbName, final String tblName, final Partition newPart) throws TException { alter_partition_with_environment_context(dbName, tblName, newPart, null); } /** * {@inheritDoc} */ @Override public void alter_partition_with_environment_context( final String dbName, final String tblName, final Partition newPart, @Nullable final EnvironmentContext ec ) throws TException { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); requestWrapper("alter_partition_with_environment_context", new Object[]{databaseName, tableName, ec}, () -> { addPartitionsCore(dbName, tableName, ImmutableList.of(newPart), false); return null; }); } /** * {@inheritDoc} */ @Override public void alter_partitions(final String dbName, final String tblName, final List<Partition> newParts) throws TException { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); requestWrapper("add_partition", new Object[]{databaseName, tableName}, () -> { addPartitionsCore(dbName, tableName, newParts, false); return null; }); } /** * {@inheritDoc} */ @Override public void alter_table(final String dbname, final String tblName, final Table newTbl) throws TException { alter_table_with_environment_context(dbname, tblName, newTbl, null); } /** * {@inheritDoc} */ @Override public void alter_table_with_cascade( final String dbname, final String tblName, final Table newTbl, final boolean cascade ) throws TException { //TODO: Add logic to cascade the changes to the partitions alter_table_with_environment_context(dbname, tblName, newTbl, null); } /** * {@inheritDoc} */ @Override public void alter_table_with_environment_context( final String dbname, final String tblName, final Table newTbl, @Nullable final EnvironmentContext environmentContext ) throws TException { requestWrapper("alter_table_with_environment_context", new Object[]{dbname, tblName, newTbl, environmentContext}, () -> { final String databaseName = normalizeIdentifier(dbname); final String tableName = normalizeIdentifier(tblName); final QualifiedName oldName = QualifiedName.ofTable(catalogName, databaseName, tableName); final QualifiedName newName = QualifiedName .ofTable(catalogName, newTbl.getDbName(), newTbl.getTableName()); final TableDto dto = hiveConverters.hiveToMetacatTable(newName, newTbl); if (!oldName.equals(newName)) { v1.renameTable(catalogName, oldName.getDatabaseName(), oldName.getTableName(), newName.getTableName()); } v1.updateTable(catalogName, dbname, newName.getTableName(), dto); return null; }); } /** * {@inheritDoc} */ @Override public Partition append_partition(final String dbName, final String tblName, final List<String> partVals) throws TException { return append_partition_with_environment_context(dbName, tblName, partVals, null); } /** * {@inheritDoc} */ @Override public Partition append_partition_by_name(final String dbName, final String tblName, final String partName) throws TException { return append_partition_by_name_with_environment_context(dbName, tblName, partName, null); } /** * {@inheritDoc} */ @Override public Partition append_partition_by_name_with_environment_context( final String dbName, final String tblName, final String partName, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("append_partition_by_name_with_environment_context", new Object[]{dbName, tblName, partName}, () -> appendPartitionsCoreAndReturn(dbName, tblName, partName)); } /** * {@inheritDoc} */ @Override public Partition append_partition_with_environment_context( final String dbName, final String tblName, final List<String> partVals, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("append_partition_by_name_with_environment_context", new Object[]{dbName, tblName, partVals}, () -> { final TableDto tableDto = getTableDto(dbName, tblName); final String partName = hiveConverters.getNameFromPartVals(tableDto, partVals); appendPartitionsCore(dbName, tblName, partName); return hiveConverters.metacatToHivePartition(getPartitionDtoByName(tableDto, partName), tableDto); }); } private void appendPartitionsCore(final String dbName, final String tblName, final String partName) throws TException { final PartitionsSaveRequestDto partitionsSaveRequestDto = new PartitionsSaveRequestDto(); final PartitionDto partitionDto = new PartitionDto(); partitionDto.setName(QualifiedName.ofPartition(catalogName, dbName, tblName, partName)); partitionDto.setSerde(new StorageDto()); partitionsSaveRequestDto.setPartitions(Lists.newArrayList(partitionDto)); partV1.savePartitions(catalogName, dbName, tblName, partitionsSaveRequestDto); } private Partition appendPartitionsCoreAndReturn(final String dbName, final String tblName, final String partName) throws TException { appendPartitionsCore(dbName, tblName, partName); return getPartitionByName(dbName, tblName, partName); } /** * {@inheritDoc} */ @Override public void cancel_delegation_token(final String tokenStrForm) throws TException { throw unimplemented("cancel_delegation_token", new Object[]{tokenStrForm}); } /** * {@inheritDoc} */ @Override public LockResponse check_lock(final CheckLockRequest rqst) throws TException { throw unimplemented("check_lock", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void commit_txn(final CommitTxnRequest rqst) throws TException { throw unimplemented("commit_txn", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void compact(final CompactionRequest rqst) throws TException { throw unimplemented("compact", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void create_database(final Database database) throws TException { requestWrapper("create_database", new Object[]{database}, () -> { final String dbName = normalizeIdentifier(database.getName()); v1.createDatabase(catalogName, dbName, DatabaseCreateRequestDto.builder().metadata(database.getParameters()).uri(database.getLocationUri()) .build()); return null; }); } /** * {@inheritDoc} */ @Override public void create_function(final Function func) throws TException { throw unimplemented("create_function", new Object[]{func}); } /** * {@inheritDoc} */ @Override public boolean create_role(final Role role) throws TException { throw unimplemented("create_role", new Object[]{role}); } /** * {@inheritDoc} */ @Override public void create_table(final Table tbl) throws TException { create_table_with_environment_context(tbl, null); } /** * {@inheritDoc} */ @Override public void create_table_with_environment_context( final Table tbl, @Nullable final EnvironmentContext environmentContext ) throws TException { requestWrapper("create_table_with_environment_context", new Object[]{tbl, environmentContext}, () -> { final String dbname = normalizeIdentifier(tbl.getDbName()); final String tblName = normalizeIdentifier(tbl.getTableName()); final QualifiedName name = QualifiedName.ofTable(catalogName, dbname, tblName); final TableDto dto = hiveConverters.hiveToMetacatTable(name, tbl); v1.createTable(catalogName, dbname, tblName, dto); return null; }); } /** * {@inheritDoc} */ @Override public boolean create_type(final Type type) throws TException { throw unimplemented("create_type", new Object[]{type}); } /** * {@inheritDoc} */ @Override public boolean delete_partition_column_statistics(final String dbName, final String tblName, final String partName, final String colName) throws TException { throw unimplemented("delete_partition_column_statistics", new Object[]{dbName, tblName, partName, colName}); } /** * {@inheritDoc} */ @Override public boolean delete_table_column_statistics(final String dbName, final String tblName, final String colName) throws TException { throw unimplemented("delete_table_column_statistics", new Object[]{dbName, tblName, colName}); } /** * {@inheritDoc} */ @Override public void drop_database(final String name, final boolean deleteData, final boolean cascade) throws TException { requestWrapper("drop_database", new Object[]{name}, () -> { v1.deleteDatabase(catalogName, name); return null; }); } /** * {@inheritDoc} */ @Override public void drop_function(final String dbName, final String funcName) throws TException { throw unimplemented("drop_function", new Object[]{dbName, funcName}); } /** * {@inheritDoc} */ @Override public boolean drop_index_by_name(final String dbName, final String tblName, final String indexName, final boolean deleteData) throws TException { throw unimplemented("drop_index_by_name", new Object[]{dbName, tblName, indexName, deleteData}); } /** * {@inheritDoc} */ @Override public boolean drop_partition(final String dbName, final String tblName, final List<String> partVals, final boolean deleteData) throws TException { return drop_partition_with_environment_context(dbName, tblName, partVals, deleteData, null); } /** * {@inheritDoc} */ @Override public boolean drop_partition_by_name(final String dbName, final String tblName, final String partName, final boolean deleteData) throws TException { return drop_partition_by_name_with_environment_context(dbName, tblName, partName, deleteData, null); } /** * {@inheritDoc} */ @Override public boolean drop_partition_by_name_with_environment_context( final String dbName, final String tblName, final String partName, final boolean deleteData, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("drop_partition_by_name_with_environment_context", new Object[]{dbName, tblName, partName, deleteData, environmentContext}, () -> { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); if (deleteData) { log.warn("Ignoring command to delete data for {}/{}/{}/{}", catalogName, databaseName, tableName, partName); } partV1.deletePartitions(catalogName, databaseName, tableName, ImmutableList.of(partName)); return true; }); } /** * {@inheritDoc} */ @Override public boolean drop_partition_with_environment_context( final String dbName, final String tblName, final List<String> partVals, final boolean deleteData, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("drop_partition_with_environment_context", new Object[]{dbName, tblName, partVals, deleteData, environmentContext}, () -> { final TableDto tableDto = getTableDto(dbName, tblName); final String partName = hiveConverters.getNameFromPartVals(tableDto, partVals); final QualifiedName partitionName = getPartitionDtoByName(tableDto, partName).getName(); if (deleteData) { log.warn("Ignoring command to delete data for {}/{}/{}/{}", catalogName, tableDto.getName().getDatabaseName(), tableDto.getName().getTableName(), partitionName.getPartitionName()); } partV1.deletePartitions( catalogName, tableDto.getName().getDatabaseName(), tableDto.getName().getTableName(), ImmutableList.of(partitionName.getPartitionName())); return true; }); } /** * {@inheritDoc} */ @Override public DropPartitionsResult drop_partitions_req(final DropPartitionsRequest request) throws TException { return requestWrapper("drop_partitions_req", new Object[]{request}, () -> { final String databaseName = request.getDbName(); final String tableName = request.getTblName(); final boolean ifExists = request.isSetIfExists() && request.isIfExists(); final boolean needResult = !request.isSetNeedResult() || request.isNeedResult(); final List<Partition> parts = Lists.newArrayList(); final List<String> partNames = Lists.newArrayList(); int minCount = 0; final RequestPartsSpec spec = request.getParts(); if (spec.isSetExprs()) { final Table table = get_table(databaseName, tableName); // Dropping by expressions. for (DropPartitionsExpr expr : spec.getExprs()) { ++minCount; // At least one partition per expression, if not ifExists final PartitionsByExprResult partitionsByExprResult = get_partitions_by_expr( new PartitionsByExprRequest(databaseName, tableName, expr.bufferForExpr())); if (partitionsByExprResult.isHasUnknownPartitions()) { // Expr is built by DDLSA, it should only contain part cols and simple ops throw new MetaException("Unexpected unknown partitions to drop"); } parts.addAll(partitionsByExprResult.getPartitions()); } final List<String> colNames = new ArrayList<>(table.getPartitionKeys().size()); for (FieldSchema col : table.getPartitionKeys()) { colNames.add(col.getName()); } if (!colNames.isEmpty()) { parts.forEach( partition -> partNames.add(FileUtils.makePartName(colNames, partition.getValues()))); } } else if (spec.isSetNames()) { partNames.addAll(spec.getNames()); minCount = partNames.size(); parts.addAll(get_partitions_by_names(databaseName, tableName, partNames)); } else { throw new MetaException("Partition spec is not set"); } if ((parts.size() < minCount) && !ifExists) { throw new NoSuchObjectException("Some partitions to drop are missing"); } partV1.deletePartitions(catalogName, databaseName, tableName, partNames); final DropPartitionsResult result = new DropPartitionsResult(); if (needResult) { result.setPartitions(parts); } return result; }); } /** * {@inheritDoc} */ @Override public boolean drop_role(final String roleName) throws TException { throw unimplemented("drop_role", new Object[]{roleName}); } /** * {@inheritDoc} */ @Override public void drop_table(final String dbname, final String name, final boolean deleteData) throws TException { drop_table_with_environment_context(dbname, name, deleteData, null); } /** * {@inheritDoc} */ @Override public void drop_table_with_environment_context(final String dbname, final String name, final boolean deleteData, @Nullable final EnvironmentContext ec) throws TException { requestWrapper("drop_table_with_environment_context", new Object[]{dbname, name, deleteData, ec}, () -> { final String databaseName = normalizeIdentifier(dbname); final String tableName = normalizeIdentifier(name); if (deleteData) { log.warn("Ignoring command to delete data for {}/{}/{}", catalogName, databaseName, tableName); } return v1.deleteTable(catalogName, databaseName, tableName); }); } /** * {@inheritDoc} */ @Override public boolean drop_type(final String type) throws TException { throw unimplemented("drop_type", new Object[]{type}); } /** * {@inheritDoc} */ @Override public Partition exchange_partition(final Map<String, String> partitionSpecs, final String sourceDb, final String sourceTableName, final String destDb, final String destTableName) throws TException { throw unimplemented("exchange_partition", new Object[]{partitionSpecs, sourceDb, sourceTableName, destDb, destTableName}); } /** * {@inheritDoc} */ @Override public FireEventResponse fire_listener_event(final FireEventRequest rqst) throws TException { throw unimplemented("fire_listener_event", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public String getCpuProfile(final int i) throws TException { return ""; } /** * {@inheritDoc} */ @Override public String getMetaConf(final String key) throws TException { throw unimplemented("getMetaConf", new Object[]{key}); } /** * {@inheritDoc} */ @Override public fb_status getStatus() { log.info("Thrift({}): Called getStatus", catalogName); return fb_status.ALIVE; } /** * {@inheritDoc} */ @Override public String getVersion() throws TException { log.info("Thrift({}): Called getVersion", catalogName); return "3.0"; } /** * {@inheritDoc} */ @Override public AggrStats get_aggr_stats_for(final PartitionsStatsRequest request) throws TException { throw unimplemented("get_aggr_stats_for", new Object[]{request}); } /** * {@inheritDoc} */ @Override public List<String> get_all_databases() throws TException { return requestWrapper("get_all_databases", new Object[]{}, () -> v1.getCatalog(catalogName, true, false).getDatabases()); } /** * {@inheritDoc} */ @Override public List<String> get_all_tables(final String dbName) throws TException { final String databaseName = normalizeIdentifier(dbName); return requestWrapper("get_all_tables", new Object[]{dbName}, () -> v1.getDatabase(catalogName, databaseName, false, true).getTables()); } /** * {@inheritDoc} */ @Override public String get_config_value(final String name, final String defaultValue) throws TException { throw unimplemented("get_config_value", new Object[]{name, defaultValue}); } /** * {@inheritDoc} */ @Override public CurrentNotificationEventId get_current_notificationEventId() throws TException { throw unimplemented("get_current_notificationEventId", new Object[]{}); } /** * {@inheritDoc} */ @Override public Database get_database(final String name) throws TException { return requestWrapper("get_database", new Object[]{name}, () -> { final String databaseName = normalizeIdentifier(name); final DatabaseDto dto = v1.getDatabase(catalogName, databaseName, true, false); return hiveConverters.metacatToHiveDatabase(dto); }); } /** * {@inheritDoc} */ @Override public List<String> get_databases(final String hivePattern) throws TException { return requestWrapper("get_databases", new Object[]{hivePattern}, () -> { List<String> result = v1.getCatalog(catalogName, true, false).getDatabases(); if (hivePattern != null) { // Unsure about the pattern format. I couldn't find any tests. Assuming it is regex. final Pattern pattern = PATTERNS.getUnchecked("(?i)" + hivePattern.replaceAll("\\*", ".*")); result = result.stream().filter(name -> pattern.matcher(name).matches()) .collect(Collectors.toList()); } return result; }); } /** * {@inheritDoc} */ @Override public String get_delegation_token(final String tokenOwner, final String renewerKerberosPrincipalName) throws TException { throw unimplemented("get_delegation_token", new Object[]{tokenOwner, renewerKerberosPrincipalName}); } /** * {@inheritDoc} */ @Override public List<FieldSchema> get_fields(final String dbName, final String tableName) throws TException { return get_fields_with_environment_context(dbName, tableName, null); } /** * {@inheritDoc} */ @Override public List<FieldSchema> get_fields_with_environment_context( final String dbName, final String tableName, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("get_fields_with_environment_context", new Object[]{dbName, tableName, environmentContext}, () -> { final Table table = get_table(dbName, tableName); if (table == null || table.getSd() == null || table.getSd().getCols() == null) { throw new MetaException("Unable to get fields for " + dbName + "." + tableName); } return table.getSd().getCols(); }); } /** * {@inheritDoc} */ @Override public Function get_function(final String dbName, final String funcName) throws TException { throw unimplemented("get_function", new Object[]{dbName, funcName}); } /** * {@inheritDoc} */ @Override public List<String> get_functions(final String dbName, final String pattern) throws TException { return Collections.emptyList(); } /** * {@inheritDoc} */ @Override public Index get_index_by_name(final String dbName, final String tblName, final String indexName) throws TException { throw unimplemented("get_index_by_name", new Object[]{dbName, tblName, indexName}); } /** * {@inheritDoc} */ @Override public List<String> get_index_names(final String dbName, final String tblName, final short maxIndexes) throws TException { throw unimplemented("get_index_names", new Object[]{dbName, tblName, maxIndexes}); } /** * {@inheritDoc} */ @Override public List<Index> get_indexes(final String dbName, final String tblName, final short maxIndexes) throws TException { throw unimplemented("get_indexes", new Object[]{dbName, tblName, maxIndexes}); } /** * {@inheritDoc} */ @Override public NotificationEventResponse get_next_notification(final NotificationEventRequest rqst) throws TException { throw unimplemented("get_next_notification", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public GetOpenTxnsResponse get_open_txns() throws TException { throw unimplemented("get_open_txns", new Object[]{}); } /** * {@inheritDoc} */ @Override public GetOpenTxnsInfoResponse get_open_txns_info() throws TException { throw unimplemented("get_open_txns_info", new Object[]{}); } /** * {@inheritDoc} */ @Override public List<PartitionSpec> get_part_specs_by_filter(final String dbName, final String tblName, final String filter, final int maxParts) throws TException { //TODO: Handle the use case of grouping return requestWrapper("get_partitions_pspec", new Object[]{dbName, tblName, filter, maxParts}, () -> { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final TableDto tableDto = v1.getTable(catalogName, databaseName, tableName, true, false, false); final GetPartitionsRequestDto dto = new GetPartitionsRequestDto(filter, null, true, false); final List<PartitionDto> metacatPartitions = partV1.getPartitionsForRequest(catalogName, dbName, tblName, null, null, null, maxParts, false, dto); final List<Partition> partitions = Lists.newArrayListWithCapacity(metacatPartitions.size()); for (PartitionDto partition : metacatPartitions) { partitions.add(hiveConverters.metacatToHivePartition(partition, tableDto)); } final PartitionSpec pSpec = new PartitionSpec(); pSpec.setPartitionList(new PartitionListComposingSpec(partitions)); pSpec.setDbName(dbName); pSpec.setTableName(tblName); if (tableDto != null && tableDto.getSerde() != null) { pSpec.setRootPath(tableDto.getSerde().getUri()); } return Arrays.asList(pSpec); }); } /** * {@inheritDoc} */ @Override public Partition get_partition(final String dbName, final String tblName, final List<String> partVals) throws TException { return requestWrapper("get_partition", new Object[]{dbName, tblName, partVals}, () -> { final TableDto tableDto = getTableDto(dbName, tblName); final String partName = hiveConverters.getNameFromPartVals(tableDto, partVals); return hiveConverters.metacatToHivePartition(getPartitionDtoByName(tableDto, partName), tableDto); }); } /** * {@inheritDoc} */ @Override public Partition get_partition_by_name(final String dbName, final String tblName, final String partName) throws TException { return requestWrapper("get_partition_by_name", new Object[]{dbName, tblName, partName}, () -> getPartitionByName(dbName, tblName, partName)); } private TableDto getTableDto(final String dbName, final String tblName) { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); return v1.getTable(catalogName, databaseName, tableName, true, false, false); } private Partition getPartitionByName(final String dbName, final String tblName, final String partName ) throws TException { final TableDto tableDto = getTableDto(dbName, tblName); return hiveConverters.metacatToHivePartition(getPartitionDtoByName(tableDto, partName), tableDto); } private PartitionDto getPartitionDtoByName(final TableDto tableDto, final String partName) throws TException { final GetPartitionsRequestDto dto = new GetPartitionsRequestDto(null, ImmutableList.of(partName), true, false); final List<PartitionDto> partitionDtos = partV1.getPartitionsForRequest( catalogName, tableDto.getName().getDatabaseName(), tableDto.getName().getTableName(), null, null, null, null, false, dto); if (partitionDtos == null || partitionDtos.isEmpty()) { throw new NoSuchObjectException("Partition (" + partName + ") not found on " + tableDto.getName()); } else if (partitionDtos.size() != 1) { // I don't think this is even possible throw new NoSuchObjectException("Partition (" + partName + ") matched extra on " + tableDto.getName()); } return partitionDtos.get(0); } /** * {@inheritDoc} */ @Override public ColumnStatistics get_partition_column_statistics( final String dbName, final String tblName, final String partName, final String colName ) throws TException { throw unimplemented("get_partition_column_statistics", new Object[]{dbName, tblName, partName, colName}); } /** * {@inheritDoc} */ @Override public List<String> get_partition_names(final String dbName, final String tblName, final short maxParts) throws TException { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final Integer maxValues = maxParts > 0 ? Short.toUnsignedInt(maxParts) : null; return requestWrapper("get_partition_names", new Object[]{databaseName, tableName, maxParts}, () -> partV1 .getPartitionKeys(catalogName, databaseName, tableName, null, null, null, null, maxValues)); } /** * {@inheritDoc} */ @Override public List<String> get_partition_names_ps(final String dbName, final String tblName, final List<String> partVals, final short maxParts) throws TException { return requestWrapper("get_partition_names_ps", new Object[]{dbName, tblName, partVals, maxParts}, () -> { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final String partFilter = partition_values_to_partition_filter(databaseName, tableName, partVals); final Integer maxValues = maxParts > 0 ? Short.toUnsignedInt(maxParts) : null; return partV1.getPartitionKeys(catalogName, databaseName, tableName, partFilter, null, null, null, maxValues); }); } /** * {@inheritDoc} */ @Override public Partition get_partition_with_auth( final String dbName, final String tblName, final List<String> partVals, final String userName, final List<String> groupNames ) throws TException { //TODO: Handle setting the privileges MetacatContextManager.getContext().setUserName(userName); return get_partition(dbName, tblName, partVals); } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions(final String dbName, final String tblName, final short maxParts) throws TException { return requestWrapper("get_partitions", new Object[]{dbName, tblName, maxParts}, () -> { return getPartitionsByFilter(dbName, tblName, null, maxParts); }); } /** * {@inheritDoc} */ @Override public PartitionsByExprResult get_partitions_by_expr(final PartitionsByExprRequest req) throws TException { return requestWrapper("get_partitions_by_expr", new Object[]{req}, () -> { try { String filter = null; if (req.getExpr() != null) { filter = Utilities.deserializeExpressionFromKryo(req.getExpr()).getExprString(); if (filter == null) { throw new MetaException("Failed to deserialize expression - ExprNodeDesc not present"); } } //TODO: We need to handle the case for 'hasUnknownPartitions' return new PartitionsByExprResult( getPartitionsByFilter(req.getDbName(), req.getTblName(), filter, req.getMaxParts()), false); } catch (Exception e) { // // If there is an exception with filtering, fallback to getting all partition names and then // apply the filter. // final List<String> partitionNames = Lists.newArrayList( get_partition_names(req.getDbName(), req.getTblName(), (short) -1)); final Table table = get_table(req.getDbName(), req.getTblName()); final List<String> columnNames = new ArrayList<>(); final List<PrimitiveTypeInfo> typeInfos = new ArrayList<>(); for (FieldSchema fs : table.getPartitionKeys()) { columnNames.add(fs.getName()); typeInfos.add(TypeInfoFactory.getPrimitiveTypeInfo(fs.getType())); } final boolean hasUnknownPartitions = new PartitionExpressionForMetastore().filterPartitionsByExpr( columnNames, typeInfos, req.getExpr(), req.getDefaultPartitionName(), partitionNames); return new PartitionsByExprResult(get_partitions_by_names( req.getDbName(), req.getTblName(), partitionNames), hasUnknownPartitions); } }); } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions_by_filter(final String dbName, final String tblName, final String filter, final short maxParts) throws TException { return requestWrapper("get_partitions_by_filter", new Object[]{dbName, tblName, filter, maxParts}, () -> getPartitionsByFilter(dbName, tblName, filter, maxParts)); } private List<Partition> getPartitionsByFilter(final String dbName, final String tblName, @Nullable final String filter, final short maxParts) { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final TableDto tableDto = v1.getTable(catalogName, databaseName, tableName, true, false, false); final Integer maxValues = maxParts > 0 ? Short.toUnsignedInt(maxParts) : null; final GetPartitionsRequestDto dto = new GetPartitionsRequestDto(filter, null, true, false); final List<PartitionDto> metacatPartitions = partV1.getPartitionsForRequest(catalogName, dbName, tblName, null, null, null, maxValues, false, dto); final List<Partition> result = Lists.newArrayListWithCapacity(metacatPartitions.size()); for (PartitionDto partition : metacatPartitions) { result.add(hiveConverters.metacatToHivePartition(partition, tableDto)); } return result; } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions_by_names(final String dbName, final String tblName, final List<String> names) throws TException { return requestWrapper("get_partitions_by_names", new Object[]{dbName, tblName, names}, () -> { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final TableDto tableDto = v1.getTable(catalogName, databaseName, tableName, true, false, false); final GetPartitionsRequestDto dto = new GetPartitionsRequestDto(null, names, true, false); final List<PartitionDto> metacatPartitions = partV1.getPartitionsForRequest(catalogName, databaseName, tableName, null, null, null, null, false, dto); final List<Partition> result = Lists.newArrayListWithCapacity(metacatPartitions.size()); for (PartitionDto partition : metacatPartitions) { result.add(hiveConverters.metacatToHivePartition(partition, tableDto)); } return result; }); } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions_ps(final String dbName, final String tblName, final List<String> partVals, final short maxParts) throws TException { return requestWrapper("get_partitions_ps", new Object[]{dbName, tblName, partVals, maxParts}, () -> { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final TableDto tableDto = v1.getTable(catalogName, databaseName, tableName, true, false, false); final String partFilter = partition_values_to_partition_filter(tableDto, partVals); final Integer maxValues = maxParts > 0 ? Short.toUnsignedInt(maxParts) : null; final GetPartitionsRequestDto dto = new GetPartitionsRequestDto(partFilter, null, true, false); final List<PartitionDto> metacatPartitions = partV1.getPartitionsForRequest(catalogName, dbName, tblName, null, null, null, maxValues, false, dto); final List<Partition> result = Lists.newArrayListWithCapacity(metacatPartitions.size()); for (PartitionDto partition : metacatPartitions) { result.add(hiveConverters.metacatToHivePartition(partition, tableDto)); } return result; }); } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions_ps_with_auth( final String dbName, final String tblName, final List<String> partVals, final short maxParts, final String userName, final List<String> groupNames ) throws TException { //TODO: Handle setting the privileges MetacatContextManager.getContext().setUserName(userName); return get_partitions_ps(dbName, tblName, partVals, maxParts); } /** * {@inheritDoc} */ @Override public List<PartitionSpec> get_partitions_pspec(final String dbName, final String tblName, final int maxParts) throws TException { return get_part_specs_by_filter(dbName, tblName, null, maxParts); } /** * {@inheritDoc} */ @Override public PartitionsStatsResult get_partitions_statistics_req(final PartitionsStatsRequest request) throws TException { throw unimplemented("get_partitions_statistics_req", new Object[]{request}); } /** * {@inheritDoc} */ @Override public List<Partition> get_partitions_with_auth( final String dbName, final String tblName, final short maxParts, final String userName, final List<String> groupNames ) throws TException { //TODO: Handle setting the privileges MetacatContextManager.getContext().setUserName(userName); return get_partitions(dbName, tblName, maxParts); } /** * {@inheritDoc} */ @Override public GetPrincipalsInRoleResponse get_principals_in_role(final GetPrincipalsInRoleRequest request) throws TException { throw unimplemented("get_principals_in_role", new Object[]{request}); } /** * {@inheritDoc} */ @Override public PrincipalPrivilegeSet get_privilege_set(final HiveObjectRef hiveObject, final String userName, final List<String> groupNames) throws TException { MetacatContextManager.getContext().setUserName(userName); return requestWrapper("get_privilege_set", new Object[]{hiveObject, userName, groupNames}, () -> { Map<String, List<PrivilegeGrantInfo>> groupPrivilegeSet = null; Map<String, List<PrivilegeGrantInfo>> userPrivilegeSet = null; if (groupNames != null) { groupPrivilegeSet = groupNames.stream() .collect(Collectors.toMap(p -> p, p -> Lists.newArrayList())); } if (userName != null) { userPrivilegeSet = ImmutableMap.of(userName, Lists.newArrayList()); } return new PrincipalPrivilegeSet(userPrivilegeSet, groupPrivilegeSet, defaultRolesPrivilegeSet); }); } /** * {@inheritDoc} */ @Override public GetRoleGrantsForPrincipalResponse get_role_grants_for_principal( final GetRoleGrantsForPrincipalRequest request) throws TException { throw unimplemented("get_role_grants_for_principal", new Object[]{request}); } /** * {@inheritDoc} */ @Override public List<String> get_role_names() throws TException { throw unimplemented("get_role_names", new Object[]{}); } /** * {@inheritDoc} */ @Override public List<FieldSchema> get_schema(final String dbName, final String tableName) throws TException { return get_schema_with_environment_context(dbName, tableName, null); } /** * {@inheritDoc} */ @Override public List<FieldSchema> get_schema_with_environment_context( final String dbName, final String tableName, @Nullable final EnvironmentContext environmentContext ) throws TException { return requestWrapper("get_schema_with_environment_context", new Object[]{dbName, tableName, environmentContext}, () -> { final Table table = get_table(dbName, tableName); List<FieldSchema> partitionKeys = Collections.emptyList(); List<FieldSchema> columns = Collections.emptyList(); if (table != null && table.getSd() != null && table.getSd().getCols() != null) { columns = table.getSd().getCols(); } if (table != null && table.getPartitionKeys() != null) { partitionKeys = table.getPartitionKeys(); } if (partitionKeys.isEmpty() && columns.isEmpty()) { throw new MetaException( "Table does not have any partition keys or cols: " + dbName + "." + tableName); } final List<FieldSchema> result = Lists.newArrayListWithCapacity(partitionKeys.size() + columns.size()); result.addAll(columns); result.addAll(partitionKeys); return result; }); } /** * {@inheritDoc} */ @Override public Table get_table(final String dbname, final String tblName) throws TException { return requestWrapper("get_table", new Object[]{dbname, tblName}, () -> { final String databaseName = normalizeIdentifier(dbname); final String tableName = normalizeIdentifier(tblName); final TableDto dto = v1.getTable(catalogName, databaseName, tableName, true, true, true); return hiveConverters.metacatToHiveTable(dto); }); } /** * {@inheritDoc} */ @Override public ColumnStatistics get_table_column_statistics(final String dbName, final String tblName, final String colName) throws TException { throw unimplemented("get_table_column_statistics", new Object[]{dbName, tblName, colName}); } /** * {@inheritDoc} */ @Override public List<String> get_table_names_by_filter(final String dbname, final String filter, final short maxTables) throws TException { return requestWrapper("get_table_names_by_filter", new Object[]{dbname, filter, maxTables}, () -> { final String databaseName = normalizeIdentifier(dbname); return v1.getTableNames(catalogName, databaseName, filter, (int) maxTables).stream() .map(QualifiedName::getTableName).collect(Collectors.toList()); }); } /** * {@inheritDoc} */ @Override public List<Table> get_table_objects_by_name(final String dbname, final List<String> tblNames) throws TException { return requestWrapper("get_table_objects_by_name", new Object[]{dbname, tblNames}, () -> { final String databaseName = normalizeIdentifier(dbname); return tblNames.stream() .map(CatalogThriftHiveMetastore::normalizeIdentifier) .map(name -> v1.getTable(catalogName, databaseName, name, true, true, true)) .map(this.hiveConverters::metacatToHiveTable) .collect(Collectors.toList()); }); } /** * {@inheritDoc} */ @Override public TableStatsResult get_table_statistics_req(final TableStatsRequest request) throws TException { throw unimplemented("get_table_statistics_req", new Object[]{request}); } /** * {@inheritDoc} */ @Override public List<String> get_tables(final String dbName, final String hivePattern) throws TException { return requestWrapper("get_tables", new Object[]{dbName, hivePattern}, () -> { List<String> result = v1.getDatabase(catalogName, dbName, false, true).getTables(); if (hivePattern != null) { final Pattern pattern = PATTERNS.getUnchecked("(?i)" + hivePattern.replaceAll("\\*", ".*")); result = result.stream().filter(name -> pattern.matcher(name).matches()).collect(Collectors.toList()); } return result; }); } /** * {@inheritDoc} */ @Override public Type get_type(final String name) throws TException { throw unimplemented("get_type", new Object[]{name}); } /** * {@inheritDoc} */ @Override public Map<String, Type> get_type_all(final String name) throws TException { throw unimplemented("get_type_all", new Object[]{name}); } /** * {@inheritDoc} */ @Override public boolean grant_privileges(final PrivilegeBag privileges) throws TException { throw unimplemented("grant_privileges", new Object[]{privileges}); } /** * {@inheritDoc} */ @Override public GrantRevokePrivilegeResponse grant_revoke_privileges(final GrantRevokePrivilegeRequest request) throws TException { throw unimplemented("grant_revoke_privileges", new Object[]{request}); } /** * {@inheritDoc} */ @Override public GrantRevokeRoleResponse grant_revoke_role(final GrantRevokeRoleRequest request) throws TException { throw unimplemented("grant_revoke_role", new Object[]{request}); } /** * {@inheritDoc} */ @Override public boolean grant_role( final String roleName, final String principalName, final PrincipalType principalType, final String grantor, final PrincipalType grantorType, final boolean grantOption ) throws TException { throw unimplemented("grant_role", new Object[]{roleName, principalName, principalType, grantor, grantorType}); } /** * {@inheritDoc} */ @Override public void heartbeat(final HeartbeatRequest ids) throws TException { throw unimplemented("heartbeat", new Object[]{ids}); } /** * {@inheritDoc} */ @Override public HeartbeatTxnRangeResponse heartbeat_txn_range(final HeartbeatTxnRangeRequest txns) throws TException { throw unimplemented("heartbeat_txn_range", new Object[]{txns}); } /** * {@inheritDoc} */ @Override public boolean isPartitionMarkedForEvent( final String dbName, final String tblName, final Map<String, String> partVals, final PartitionEventType eventType ) throws TException { throw unimplemented("isPartitionMarkedForEvent", new Object[]{dbName, tblName, partVals, eventType}); } /** * {@inheritDoc} */ @Override public List<HiveObjectPrivilege> list_privileges(final String principalName, final PrincipalType principalType, final HiveObjectRef hiveObject) throws TException { throw unimplemented("list_privileges", new Object[]{principalName, principalType, hiveObject}); } /** * {@inheritDoc} */ @Override public List<Role> list_roles(final String principalName, final PrincipalType principalType) throws TException { throw unimplemented("list_roles", new Object[]{principalName, principalType}); } /** * {@inheritDoc} */ @Override public LockResponse lock(final LockRequest rqst) throws TException { throw unimplemented("lock", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void markPartitionForEvent(final String dbName, final String tblName, final Map<String, String> partVals, final PartitionEventType eventType) throws TException { throw unimplemented("markPartitionForEvent", new Object[]{dbName, tblName, partVals, eventType}); } /** * {@inheritDoc} */ @Override public OpenTxnsResponse open_txns(final OpenTxnRequest rqst) throws TException { throw unimplemented("open_txns", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public boolean partition_name_has_valid_characters(final List<String> partVals, final boolean throwException) throws TException { return requestWrapper("partition_name_has_valid_characters", new Object[]{partVals, throwException}, () -> { Pattern pattern = null; final String partitionPattern = config.getHivePartitionWhitelistPattern(); if (!Strings.isNullOrEmpty(partitionPattern)) { pattern = PATTERNS.getUnchecked(partitionPattern); } if (throwException) { MetaStoreUtils.validatePartitionNameCharacters(partVals, pattern); return true; } else { return MetaStoreUtils.partitionNameHasValidCharacters(partVals, pattern); } }); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Map<String, String> partition_name_to_spec(final String partName) throws TException { return requestWrapper("partition_name_to_spec", new Object[]{partName}, () -> { if (Strings.isNullOrEmpty(partName)) { return (Map<String, String>) Collections.EMPTY_MAP; } return Warehouse.makeSpecFromName(partName); }); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> partition_name_to_vals(final String partName) throws TException { return requestWrapper("partition_name_to_vals", new Object[]{partName}, () -> { if (Strings.isNullOrEmpty(partName)) { return (List<String>) Collections.EMPTY_LIST; } final Map<String, String> spec = Warehouse.makeSpecFromName(partName); final List<String> vals = Lists.newArrayListWithCapacity(spec.size()); vals.addAll(spec.values()); return vals; }); } /** * Converts the partial specification given by the part_vals to a Metacat filter statement. * * @param dbName the name of the database * @param tblName the name of the table * @param partVals the partial specification values * @return A Meta * cat filter expression suitable for selecting out the partitions matching the specification * @throws MetaException if there are more part_vals specified than partition columns on the table. */ @SuppressWarnings("checkstyle:methodname") String partition_values_to_partition_filter(final String dbName, final String tblName, final List<String> partVals) throws MetaException { final String databaseName = normalizeIdentifier(dbName); final String tableName = normalizeIdentifier(tblName); final TableDto tableDto = v1.getTable(catalogName, databaseName, tableName, true, false, false); return partition_values_to_partition_filter(tableDto, partVals); } /** * Converts the partial specification given by the part_vals to a Metacat filter statement. * * @param tableDto the Metacat representation of the table * @param partVals the partial specification values * @return A Metacat filter expression suitable for selecting out the partitions matching the specification * @throws MetaException if there are more part_vals specified than partition columns on the table. */ @SuppressWarnings("checkstyle:methodname") String partition_values_to_partition_filter(final TableDto tableDto, final List<String> partVals) throws MetaException { if (partVals.size() > tableDto.getPartition_keys().size()) { throw new MetaException("Too many partition values for " + tableDto.getName()); } final List<FieldDto> fields = tableDto.getFields(); final List<String> partitionFilters = Lists.newArrayListWithCapacity(fields.size()); for (int i = 0, partitionIdx = 0; i < fields.size(); i++) { final FieldDto fieldDto = fields.get(i); if (!fieldDto.isPartition_key() || partitionIdx >= partVals.size()) { continue; } final String partitionValueFilter = partVals.get(partitionIdx++); // We only filter on partitions with values if (!Strings.isNullOrEmpty(partitionValueFilter)) { String filter = "(" + fieldDto.getName() + "="; try { filter += Long.parseLong(partitionValueFilter) + ")"; } catch (NumberFormatException ignored) { filter += "'" + partitionValueFilter + "')"; } partitionFilters.add(filter); } } return partitionFilters.isEmpty() ? null : AND_JOINER.join(partitionFilters); } /** * {@inheritDoc} */ @Override public void rename_partition(final String dbName, final String tblName, final List<String> partVals, final Partition newPart) throws TException { requestWrapper("rename_partition", new Object[]{dbName, tblName, partVals}, () -> { final TableDto tableDto = getTableDto(dbName, tblName); final String partName = hiveConverters.getNameFromPartVals(tableDto, partVals); final PartitionsSaveRequestDto partitionsSaveRequestDto = new PartitionsSaveRequestDto(); final PartitionDto partitionDto = hiveConverters.hiveToMetacatPartition(tableDto, newPart); partitionsSaveRequestDto.setPartitions(Lists.newArrayList(partitionDto)); partitionsSaveRequestDto.setPartitionIdsForDeletes(Lists.newArrayList(partName)); partV1.savePartitions(catalogName, dbName, tblName, partitionsSaveRequestDto); return null; }); } /** * {@inheritDoc} */ @Override public long renew_delegation_token(final String tokenStrForm) throws TException { throw unimplemented("renew_delegation_token", new Object[]{tokenStrForm}); } private TException unimplemented(final String methodName, final Object[] args) throws TException { log.info("+++ Thrift({}): Calling {}({})", catalogName, methodName, args); throw new InvalidOperationException("Not implemented yet: " + methodName); } private <R> R requestWrapper(final String methodName, final Object[] args, final ThriftSupplier<R> supplier) throws TException { final long start = registry.clock().wallTime(); registry.counter(registry.createId(Metrics.CounterThrift.getMetricName() + "." + methodName)).increment(); try { final MetacatRequestContext requestContext = MetacatContextManager.getContext(); requestContext.clearTableTypeMap(); log.info("+++ Thrift({}): Calling {}({}). Request Context: {}", catalogName, methodName, args, requestContext); return supplier.get(); } catch (MetacatAlreadyExistsException e) { log.error(e.getMessage(), e); throw new AlreadyExistsException(e.getMessage()); } catch (MetacatNotFoundException e) { log.error(e.getMessage(), e); throw new NoSuchObjectException(e.getMessage()); } catch (MetacatPreconditionFailedException e) { log.error(e.getMessage(), e); throw new InvalidObjectException(e.getMessage()); } catch (TException e) { log.error(e.getMessage(), e); throw e; } catch (Exception e) { registry.counter(registry.createId(Metrics.CounterThrift.getMetricName() + "." + methodName) .withTags(Metrics.tagStatusFailureMap)).increment(); final String message = String.format("%s -- %s failed", e.getMessage(), methodName); log.error(message, e); final MetaException me = new MetaException(message); me.initCause(e); throw me; } finally { final long duration = registry.clock().wallTime() - start; this.registry.timer(Metrics.TimerThriftRequest.getMetricName() + "." + methodName).record(duration, TimeUnit.MILLISECONDS); log.info("+++ Thrift({}): Time taken to complete {} is {} ms", catalogName, methodName, duration); } } /** * {@inheritDoc} */ @Override public boolean revoke_privileges(final PrivilegeBag privileges) throws TException { throw unimplemented("revoke_privileges", new Object[]{privileges}); } /** * {@inheritDoc} */ @Override public boolean revoke_role(final String roleName, final String principalName, final PrincipalType principalType) throws TException { throw unimplemented("revoke_role", new Object[]{roleName, principalName, principalType}); } /** * {@inheritDoc} */ @Override public void setMetaConf(final String key, final String value) throws TException { throw unimplemented("setMetaConf", new Object[]{key, value}); } /** * {@inheritDoc} */ @Override public boolean set_aggr_stats_for(final SetPartitionsStatsRequest request) throws TException { throw unimplemented("set_aggr_stats_for", new Object[]{request}); } /** * {@inheritDoc} */ @Override public List<String> set_ugi(final String userName, final List<String> groupNames) throws TException { MetacatContextManager.getContext().setUserName(userName); return requestWrapper("set_ugi", new Object[]{userName, groupNames}, () -> { Collections.addAll(groupNames, userName); return groupNames; }); } /** * {@inheritDoc} */ @Override public ShowCompactResponse show_compact(final ShowCompactRequest rqst) throws TException { throw unimplemented("show_compact", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public ShowLocksResponse show_locks(final ShowLocksRequest rqst) throws TException { throw unimplemented("show_locks", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public void unlock(final UnlockRequest rqst) throws TException { throw unimplemented("unlock", new Object[]{rqst}); } /** * {@inheritDoc} */ @Override public boolean update_partition_column_statistics(final ColumnStatistics statsObj) throws TException { throw unimplemented("update_partition_column_statistics", new Object[]{statsObj}); } /** * {@inheritDoc} */ @Override public boolean update_table_column_statistics(final ColumnStatistics statsObj) throws TException { throw unimplemented("update_table_column_statistics", new Object[]{statsObj}); } @FunctionalInterface interface ThriftSupplier<T> { T get() throws TException; } }
1,786
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/CatalogThriftEventHandler.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.thrift; import com.google.common.base.Objects; import com.netflix.metacat.common.MetacatRequestContext; import com.netflix.metacat.common.server.util.MetacatContextManager; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.server.ServerContext; import org.apache.thrift.server.TServerEventHandler; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import javax.annotation.Nullable; /** * Server event handler. */ public class CatalogThriftEventHandler implements TServerEventHandler { /** * {@inheritDoc} */ @Override public ServerContext createContext(final TProtocol input, final TProtocol output) { final String userName = "metacat-thrift-interface"; String clientHost = null; //requestContext.getHeaderString("X-Forwarded-For"); final long requestThreadId = Thread.currentThread().getId(); final TTransport transport = input.getTransport(); if (transport instanceof TSocket) { final TSocket thriftSocket = (TSocket) transport; clientHost = thriftSocket.getSocket().getInetAddress().getHostAddress(); } final CatalogServerRequestContext context = new CatalogServerRequestContext( userName, null, clientHost, null, "hive", requestThreadId ); MetacatContextManager.setContext(context); return context; } /** * {@inheritDoc} */ @Override public void deleteContext(final ServerContext serverContext, final TProtocol input, final TProtocol output) { validateRequest((CatalogServerRequestContext) serverContext); MetacatContextManager.removeContext(); } /** * {@inheritDoc} */ @Override public void preServe() { // nothing to do } /** * {@inheritDoc} */ @Override public void processContext(final ServerContext serverContext, final TTransport inputTransport, final TTransport outputTransport) { validateRequest((CatalogServerRequestContext) serverContext); } private void validateRequest(final CatalogServerRequestContext serverContext) { final long requestThreadId = serverContext.requestThreadId; if (requestThreadId != Thread.currentThread().getId()) { throw new IllegalStateException("Expect all processing to happen on the same thread as the request thread"); } } /** * request context. */ public static class CatalogServerRequestContext extends MetacatRequestContext implements ServerContext { private final long requestThreadId; CatalogServerRequestContext( @Nullable final String userName, @Nullable final String clientAppName, @Nullable final String clientId, @Nullable final String jobId, @Nullable final String dataTypeContext, final long requestThreadId ) { super(userName, clientAppName, clientId, jobId, dataTypeContext, MetacatRequestContext.UNKNOWN, "thrift"); this.requestThreadId = requestThreadId; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final CatalogServerRequestContext that = (CatalogServerRequestContext) o; return requestThreadId == that.requestThreadId; } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hashCode(super.hashCode(), requestThreadId); } } }
1,787
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/DateConverters.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.thrift; import com.netflix.metacat.common.server.properties.Config; import lombok.NonNull; import javax.annotation.Nullable; import java.time.Instant; import java.util.Date; /** * Date converter. * * @author amajumdar * @since 1.0.0 */ public class DateConverters { private final Config config; /** * Constructor. * * @param config The application config. */ public DateConverters(@NonNull final Config config) { this.config = config; } /** * Converts date to epoch. * * @param d date * @return epoch time */ public Long fromDateToLong(@Nullable final Date d) { if (d == null) { return null; } final Instant instant = d.toInstant(); return config.isEpochInSeconds() ? instant.getEpochSecond() : instant.toEpochMilli(); } /** * Converts epoch to date. * * @param l epoch time * @return date */ public Date fromLongToDate(@Nullable final Long l) { if (l == null) { return null; } final Instant instant = config.isEpochInSeconds() ? Instant.ofEpochSecond(l) : Instant.ofEpochMilli(l); return Date.from(instant); } }
1,788
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/CatalogThriftServiceFactory.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.thrift; /** * Thrift service factory. */ public interface CatalogThriftServiceFactory { /** * Create service. * * @param catalogName catalog name * @param portNumber port * @return service */ CatalogThriftService create(String catalogName, int portNumber); }
1,789
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/CatalogThriftServiceFactoryImpl.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.thrift; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; 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.spectator.api.Registry; import java.util.Objects; /** * Thrift service factory. */ public class CatalogThriftServiceFactoryImpl implements CatalogThriftServiceFactory { private final LoadingCache<CacheKey, CatalogThriftService> cache; /** * Constructor. * * @param config config * @param hiveConverters hive converter * @param metacatV1 Metacat V1 * @param partitionV1 Partition V1 * @param registry registry for spectator */ public CatalogThriftServiceFactoryImpl( final Config config, final HiveConverters hiveConverters, final MetacatV1 metacatV1, final PartitionV1 partitionV1, final Registry registry ) { this.cache = CacheBuilder.newBuilder() .build(new CacheLoader<CacheKey, CatalogThriftService>() { public CatalogThriftService load(final CacheKey key) { return new CatalogThriftService(config, hiveConverters, metacatV1, partitionV1, key.catalogName, key.portNumber, registry); } }); } /** * {@inheritDoc} */ @Override public CatalogThriftService create(final String catalogName, final int portNumber) { return cache.getUnchecked(new CacheKey(catalogName, portNumber)); } private static final class CacheKey { private final String catalogName; private final int portNumber; private CacheKey(final String catalogName, final int portNumber) { this.catalogName = catalogName; this.portNumber = portNumber; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof CacheKey)) { return false; } final CacheKey cacheKey = (CacheKey) o; return Objects.equals(portNumber, cacheKey.portNumber) && Objects.equals(catalogName, cacheKey.catalogName); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(catalogName, portNumber); } } }
1,790
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/HiveConverters.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.thrift; import com.netflix.metacat.common.QualifiedName; import com.netflix.metacat.common.dto.DatabaseDto; import com.netflix.metacat.common.dto.PartitionDto; import com.netflix.metacat.common.dto.TableDto; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.Table; import java.util.List; /** * Hive converter interface. */ public interface HiveConverters { /** * Converts from hive table to metacat table info. * * @param name name * @param table table * @return table info */ TableDto hiveToMetacatTable(QualifiedName name, Table table); /** * Converts from metacat database info to hive database info. * * @param databaseDto database * @return database */ Database metacatToHiveDatabase(DatabaseDto databaseDto); /** * Converts from metacat table info to hive table info. * * @param dto table * @return table */ Table metacatToHiveTable(TableDto dto); /** * Converts from hive partition info to metacat partition info. * * @param tableDto table * @param partition partition * @return partition info */ PartitionDto hiveToMetacatPartition(TableDto tableDto, Partition partition); /** * Gets the partition values from the partition name. * * @param tableDto table * @param partName partition name * @return partition info */ List<String> getPartValsFromName(TableDto tableDto, String partName); /** * Gets the partition name from partition values. * * @param tableDto table * @param partVals partition values * @return partition name */ String getNameFromPartVals(TableDto tableDto, List<String> partVals); /** * Converts from metacat partition info to hive partition info. * * @param tableDto table * @param partitionDto partition * @return partition info */ Partition metacatToHivePartition(PartitionDto partitionDto, TableDto tableDto); }
1,791
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/HiveConvertersImpl.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.thrift; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.annotations.VisibleForTesting; 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.AuditDto; import com.netflix.metacat.common.dto.DatabaseDto; import com.netflix.metacat.common.dto.FieldDto; import com.netflix.metacat.common.dto.PartitionDto; import com.netflix.metacat.common.dto.StorageDto; import com.netflix.metacat.common.dto.TableDto; import com.netflix.metacat.common.dto.ViewDto; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.common.FileUtils; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.Warehouse; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.SerDeInfo; import org.apache.hadoop.hive.metastore.api.SkewedInfo; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.metastore.api.Table; import javax.annotation.Nullable; import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Hive converter. */ public class HiveConvertersImpl implements HiveConverters { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @VisibleForTesting Integer dateToEpochSeconds(@Nullable final Date date) { if (date == null) { return null; } final Instant instant = date.toInstant(); final long seconds = instant.getEpochSecond(); if (seconds <= Integer.MAX_VALUE) { return (int) seconds; } throw new IllegalStateException("Unable to convert date " + date + " to an integer seconds value"); } private Date epochSecondsToDate(final long seconds) { final Instant instant = Instant.ofEpochSecond(seconds); return Date.from(instant); } private FieldDto hiveToMetacatField(final FieldSchema field, final boolean isPartitionKey) { final FieldDto dto = new FieldDto(); dto.setName(field.getName()); dto.setType(field.getType()); dto.setSource_type(field.getType()); dto.setComment(field.getComment()); dto.setPartition_key(isPartitionKey); return dto; } private FieldSchema metacatToHiveField(final FieldDto fieldDto) { final FieldSchema result = new FieldSchema(); result.setName(fieldDto.getName()); result.setType(fieldDto.getType()); result.setComment(fieldDto.getComment()); return result; } /** * {@inheritDoc} */ @Override public TableDto hiveToMetacatTable(final QualifiedName name, final Table table) { final TableDto dto = new TableDto(); dto.setSerde(toStorageDto(table.getSd(), table.getOwner())); dto.setAudit(new AuditDto()); dto.setName(name); if (table.isSetCreateTime()) { dto.getAudit().setCreatedDate(epochSecondsToDate(table.getCreateTime())); } dto.setMetadata(table.getParameters()); final List<FieldSchema> nonPartitionColumns = table.getSd().getCols(); final List<FieldSchema> partitionColumns = table.getPartitionKeys(); final List<FieldDto> allFields = Lists.newArrayListWithCapacity(nonPartitionColumns.size() + partitionColumns.size()); nonPartitionColumns.stream() .map(field -> this.hiveToMetacatField(field, false)) .forEachOrdered(allFields::add); partitionColumns.stream() .map(field -> this.hiveToMetacatField(field, true)) .forEachOrdered(allFields::add); dto.setFields(allFields); dto.setView(new ViewDto(table.getViewOriginalText(), table.getViewExpandedText())); if (StringUtils.isNotBlank(table.getOwner())) { final ObjectNode definitionMetadata = OBJECT_MAPPER.createObjectNode(); final ObjectNode ownerNode = definitionMetadata.with("owner"); ownerNode.put("userId", table.getOwner()); dto.setDefinitionMetadata(definitionMetadata); } return dto; } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Database metacatToHiveDatabase(final DatabaseDto dto) { final Database database = new Database(); String name = ""; String description = ""; final QualifiedName databaseName = dto.getName(); if (databaseName != null) { name = databaseName.getDatabaseName(); // Since this is required setting it to the same as the DB name for now description = databaseName.getDatabaseName(); } database.setName(name); database.setDescription(description); String dbUri = dto.getUri(); if (Strings.isNullOrEmpty(dbUri)) { dbUri = ""; } database.setLocationUri(dbUri); Map<String, String> metadata = dto.getMetadata(); if (metadata == null) { metadata = Collections.EMPTY_MAP; } database.setParameters(metadata); return database; } /** * {@inheritDoc} */ @Override public Table metacatToHiveTable(final TableDto dto) { final Table table = new Table(); final QualifiedName name = dto.getName(); if (name != null) { table.setTableName(name.getTableName()); table.setDbName(name.getDatabaseName()); } final StorageDto storageDto = dto.getSerde(); if (storageDto != null) { table.setOwner(storageDto.getOwner()); } final AuditDto auditDto = dto.getAudit(); if (auditDto != null && auditDto.getCreatedDate() != null) { table.setCreateTime(dateToEpochSeconds(auditDto.getCreatedDate())); } Map<String, String> params = new HashMap<>(); if (dto.getMetadata() != null) { params = dto.getMetadata(); } table.setParameters(params); updateTableTypeAndViewInfo(dto, table); table.setSd(fromStorageDto(storageDto, table.getTableName())); final List<FieldDto> fields = dto.getFields(); if (fields == null) { table.setPartitionKeys(Collections.emptyList()); table.getSd().setCols(Collections.emptyList()); } else { final List<FieldSchema> nonPartitionFields = Lists.newArrayListWithCapacity(fields.size()); final List<FieldSchema> partitionFields = Lists.newArrayListWithCapacity(fields.size()); for (FieldDto fieldDto : fields) { final FieldSchema f = metacatToHiveField(fieldDto); if (fieldDto.isPartition_key()) { partitionFields.add(f); } else { nonPartitionFields.add(f); } } table.setPartitionKeys(partitionFields); table.getSd().setCols(nonPartitionFields); } dto.getTableOwner().ifPresent(table::setOwner); return table; } private void updateTableTypeAndViewInfo(final TableDto dto, final Table table) { final ViewDto viewDto = dto.getView(); if (null == dto.getView() || Strings.isNullOrEmpty(viewDto.getViewOriginalText())) { table.setTableType(TableType.EXTERNAL_TABLE.name()); return; } table.setTableType(TableType.VIRTUAL_VIEW.name()); table.setViewOriginalText(viewDto.getViewOriginalText()); table.setViewExpandedText(viewDto.getViewExpandedText()); } private StorageDto toStorageDto(@Nullable final StorageDescriptor sd, final String owner) { final StorageDto result = new StorageDto(); if (sd != null) { result.setOwner(owner); result.setUri(sd.getLocation()); result.setInputFormat(sd.getInputFormat()); result.setOutputFormat(sd.getOutputFormat()); result.setParameters(sd.getParameters()); final SerDeInfo serde = sd.getSerdeInfo(); if (serde != null) { result.setSerializationLib(serde.getSerializationLib()); result.setSerdeInfoParameters(serde.getParameters()); } } return result; } private StorageDescriptor fromStorageDto(@Nullable final StorageDto storageDto, @Nullable final String serdeName) { // // Set all required fields to null. This is to simulate Hive behavior. // Setting it to empty string failed certain hive operations. // final StorageDescriptor result = new StorageDescriptor(); String inputFormat = null; String location = null; String outputFormat = null; String serializationLib = null; Map<String, String> sdParams = Maps.newHashMap(); Map<String, String> serdeParams = Maps.newHashMap(); if (storageDto != null) { if (storageDto.getInputFormat() != null) { inputFormat = storageDto.getInputFormat(); } if (storageDto.getUri() != null) { location = storageDto.getUri(); } if (storageDto.getOutputFormat() != null) { outputFormat = storageDto.getOutputFormat(); } if (storageDto.getSerializationLib() != null) { serializationLib = storageDto.getSerializationLib(); } if (storageDto.getParameters() != null) { sdParams = storageDto.getParameters(); } if (storageDto.getSerdeInfoParameters() != null) { serdeParams = storageDto.getSerdeInfoParameters(); } } result.setSerdeInfo(new SerDeInfo(serdeName, serializationLib, serdeParams)); result.setBucketCols(Collections.emptyList()); result.setSortCols(Collections.emptyList()); result.setInputFormat(inputFormat); result.setLocation(location); result.setOutputFormat(outputFormat); result.setCols(Collections.emptyList()); // Setting an empty skewed info. result.setSkewedInfo(new SkewedInfo(Collections.emptyList(), Collections.emptyList(), Collections.emptyMap())); result.setParameters(sdParams); return result; } /** * {@inheritDoc} */ @Override public PartitionDto hiveToMetacatPartition(final TableDto tableDto, final Partition partition) { final QualifiedName tableName = tableDto.getName(); final QualifiedName partitionName = QualifiedName.ofPartition(tableName.getCatalogName(), tableName.getDatabaseName(), tableName.getTableName(), getNameFromPartVals(tableDto, partition.getValues())); final PartitionDto result = new PartitionDto(); String owner = ""; if (tableDto.getSerde() != null) { owner = tableDto.getSerde().getOwner(); } //not setting Serde to view if (null == tableDto.getView() || Strings.isNullOrEmpty(tableDto.getView().getViewOriginalText())) { result.setSerde(toStorageDto(partition.getSd(), owner)); } result.setMetadata(partition.getParameters()); final AuditDto auditDto = new AuditDto(); auditDto.setCreatedDate(epochSecondsToDate(partition.getCreateTime())); auditDto.setLastModifiedDate(epochSecondsToDate(partition.getLastAccessTime())); result.setAudit(auditDto); result.setName(partitionName); return result; } /** * {@inheritDoc} */ @Override public List<String> getPartValsFromName(@Nullable final TableDto tableDto, final String partName) { // Unescape the partition name final LinkedHashMap<String, String> hm; try { hm = Warehouse.makeSpecFromName(partName); } catch (MetaException e) { throw new IllegalArgumentException("Invalid partition name", e); } // Get the partition keys. List<String> partitionKeys = null; if (tableDto != null) { partitionKeys = tableDto.getPartition_keys(); } // If table has not been provided, return the values without validating. if (partitionKeys != null) { final List<String> partVals = Lists.newArrayListWithCapacity(partitionKeys.size()); for (String key : partitionKeys) { final String val = hm.get(key); if (val == null) { throw new IllegalArgumentException("Invalid partition name - missing " + key); } partVals.add(val); } return partVals; } else { return Lists.newArrayList(hm.values()); } } /** * {@inheritDoc} */ @Override public String getNameFromPartVals(final TableDto tableDto, final List<String> partVals) { final List<String> partitionKeys = tableDto.getPartition_keys(); if (partitionKeys.size() != partVals.size()) { throw new IllegalArgumentException("Not the same number of partition columns and partition values"); } return FileUtils.makePartName(partitionKeys, partVals, ""); } /** * {@inheritDoc} */ @Override public Partition metacatToHivePartition(final PartitionDto partitionDto, @Nullable final TableDto tableDto) { final Partition result = new Partition(); final QualifiedName name = partitionDto.getName(); List<String> values = Lists.newArrayListWithCapacity(16); String databaseName = null; String tableName = null; if (name != null) { if (name.getPartitionName() != null) { // // Unescape the partition name to get the right partition values. // Partition name always are escaped where as the parition values are not. // values = getPartValsFromName(tableDto, name.getPartitionName()); } if (name.getDatabaseName() != null) { databaseName = name.getDatabaseName(); } if (name.getTableName() != null) { tableName = name.getTableName(); } } result.setValues(values); result.setDbName(databaseName); result.setTableName(tableName); Map<String, String> metadata = partitionDto.getMetadata(); if (metadata == null) { metadata = Maps.newHashMap(); } result.setParameters(metadata); result.setSd(fromStorageDto(partitionDto.getSerde(), tableName)); final StorageDescriptor sd = result.getSd(); if (tableDto != null) { if (sd.getSerdeInfo() != null && tableDto.getSerde() != null && Strings.isNullOrEmpty( sd.getSerdeInfo().getSerializationLib())) { sd.getSerdeInfo().setSerializationLib(tableDto.getSerde().getSerializationLib()); } final List<FieldDto> fields = tableDto.getFields(); if (fields == null) { sd.setCols(Collections.emptyList()); } else { sd.setCols(fields.stream() .filter(field -> !field.isPartition_key()) .map(this::metacatToHiveField) .collect(Collectors.toList())); } } final AuditDto auditDto = partitionDto.getAudit(); if (auditDto != null) { if (auditDto.getCreatedDate() != null) { result.setCreateTime(dateToEpochSeconds(auditDto.getCreatedDate())); } if (auditDto.getLastModifiedDate() != null) { result.setLastAccessTime(dateToEpochSeconds(auditDto.getLastModifiedDate())); } } return result; } }
1,792
0
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat
Create_ds/metacat/metacat-thrift/src/main/java/com/netflix/metacat/thrift/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 thrift implementation classes. * * @author amajumdar */ @ParametersAreNonnullByDefault package com.netflix.metacat.thrift; import javax.annotation.ParametersAreNonnullByDefault;
1,793
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlConnectorDatabaseService.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.postgresql; import com.netflix.metacat.common.QualifiedName; import com.netflix.metacat.common.server.connectors.ConnectorRequestContext; import com.netflix.metacat.common.server.connectors.model.DatabaseInfo; import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper; import com.netflix.metacat.connector.jdbc.services.JdbcConnectorDatabaseService; import lombok.NonNull; import javax.annotation.Nonnull; import javax.inject.Inject; import javax.sql.DataSource; /** * Specific overrides of the JdbcDatabaseService implementation for PostgreSQL. * * @author tgianos * @see JdbcConnectorDatabaseService * @since 1.0.0 */ public class PostgreSqlConnectorDatabaseService extends JdbcConnectorDatabaseService { /** * Constructor. * * @param dataSource The PostgreSQL datasource to use * @param exceptionMapper The exception mapper to use to convert from SQLException's to ConnectorException's */ @Inject public PostgreSqlConnectorDatabaseService( @Nonnull @NonNull final DataSource dataSource, @Nonnull @NonNull final JdbcExceptionMapper exceptionMapper ) { super(dataSource, exceptionMapper); } /** * {@inheritDoc} */ @Override public void create(@Nonnull final ConnectorRequestContext context, @Nonnull final DatabaseInfo resource) { throw new UnsupportedOperationException(UNSUPPORTED_MESSAGE); } /** * {@inheritDoc} */ @Override public void delete(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) { throw new UnsupportedOperationException(UNSUPPORTED_MESSAGE); } }
1,794
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlTypeConverter.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.postgresql; 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.Type; import com.netflix.metacat.common.type.VarbinaryType; import com.netflix.metacat.common.type.VarcharType; import com.netflix.metacat.connector.jdbc.JdbcTypeConverter; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nonnull; /** * Type converter for PostgreSql. * * @author tgianos * @since 1.0.0 */ @Slf4j public class PostgreSqlTypeConverter extends JdbcTypeConverter { private static final String ARRAY = "array"; private static final String SINGLE_ARRAY = "[]"; private static final String MULTI_ARRAY = "[][]"; /** * {@inheritDoc} * * @see <a href="https://www.postgresql.org/docs/current/static/datatype.html">PosgreSQL Data Types</a> */ @Override public Type toMetacatType(@Nonnull @NonNull 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); final Type elementType; switch (splitType[0]) { case "smallint": case "int2": elementType = BaseType.SMALLINT; break; case "int": case "integer": case "int4": elementType = BaseType.INT; break; case "int8": case "bigint": elementType = BaseType.BIGINT; break; case "decimal": case "numeric": elementType = this.toMetacatDecimalType(splitType); break; case "real": case "float4": elementType = BaseType.FLOAT; break; case "double precision": case "float8": elementType = BaseType.DOUBLE; break; case "character varying": case "varchar": elementType = this.toMetacatVarcharType(splitType); break; case "character": case "char": elementType = this.toMetacatCharType(splitType); break; case "text": elementType = BaseType.STRING; break; case "bytea": elementType = VarbinaryType.createVarbinaryType(Integer.MAX_VALUE); break; case "timestamp": elementType = this.toMetacatTimestampType(splitType); break; case "timestampz": elementType = BaseType.TIMESTAMP_WITH_TIME_ZONE; break; case "date": elementType = BaseType.DATE; break; case "time": elementType = this.toMetacatTimeType(splitType); break; case "timez": elementType = BaseType.TIME_WITH_TIME_ZONE; break; case "boolean": case "bool": elementType = BaseType.BOOLEAN; break; case "bit": case "bit varying": case "varbit": elementType = this.toMetacatBitType(splitType); break; case "json": elementType = BaseType.JSON; break; case "smallserial": case "serial2": case "serial": case "serial4": case "bigserial": case "serial8": case "money": case "interval": case "enum": case "point": case "line": case "lseg": case "box": case "path": case "polygon": case "circle": case "cidr": case "inet": case "macaddr": case "tsvector": case "tsquery": case "uuid": case "xml": case "int4range": case "int8range": case "numrange": case "tsrange": case "tstzrange": case "daterange": case "oid": case "regproc": case "regprocedure": case "regoper": case "regoperator": case "regclass": case "regtype": case "regrole": case "regnamespace": case "regconfig": case "regdictionary": case "pg_lsn": case "jsonb": case "txid_snapshot": default: // TODO: Will catch complex types but not sure how to parse beyond that right now, may be recursive? // https://www.postgresql.org/docs/current/static/rowtypes.html log.info("Encountered {} type. Returning unknown type", splitType[0]); return BaseType.UNKNOWN; } return this.checkForArray(splitType, elementType); } /** * {@inheritDoc} */ @Override public String fromMetacatType(@Nonnull @NonNull final Type type) { switch (type.getTypeSignature().getBase()) { case ARRAY: if (!(type instanceof ArrayType)) { throw new IllegalArgumentException("Expected an ARRAY type but was " + type.getClass().getName()); } final ArrayType arrayType = (ArrayType) type; final String array; final Type elementType; // Check for nested arrays if (arrayType.getElementType() instanceof ArrayType) { array = MULTI_ARRAY; elementType = ((ArrayType) arrayType.getElementType()).getElementType(); } else { array = SINGLE_ARRAY; elementType = arrayType.getElementType(); } // Recursively determine the type of the array return this.fromMetacatType(elementType) + array; 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 "NUMERIC(" + decimalType.getPrecision() + ", " + decimalType.getScale() + ")"; case DOUBLE: return "DOUBLE PRECISION"; case FLOAT: return "REAL"; case INT: return "INT"; case INTERVAL_DAY_TO_SECOND: // TODO: It does but not sure how best to represent now throw new UnsupportedOperationException("PostgreSQL doesn't support interval types"); case INTERVAL_YEAR_TO_MONTH: // TODO: It does but not sure how best to represent now throw new UnsupportedOperationException("PostgreSQL doesn't support interval types"); case JSON: return "JSON"; case MAP: throw new UnsupportedOperationException("PostgreSQL doesn't support map types"); case ROW: // TODO: Well it does but how do we know what the internal type is? throw new UnsupportedOperationException("PostgreSQL doesn't support row types"); case SMALLINT: return "SMALLINT"; case STRING: return "TEXT"; case TIME: return "TIME"; case TIME_WITH_TIME_ZONE: return "TIME WITH TIME ZONE"; case TIMESTAMP: return "TIMESTAMP"; case TIMESTAMP_WITH_TIME_ZONE: return "TIMESTAMP WITH TIME ZONE"; case TINYINT: // NOTE: There is no tiny int type in PostgreSQL so using slightly larger SMALLINT return "SMALLINT"; case UNKNOWN: throw new IllegalArgumentException("Can't map an unknown type"); case VARBINARY: return "BYTEA"; 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 "CHARACTER VARYING(" + varcharType.getLength() + ")"; default: throw new IllegalArgumentException("Unknown type " + type.getTypeSignature().getBase()); } } private Type checkForArray(@Nonnull @NonNull final String[] splitType, @Nonnull @NonNull final Type elementType) { if (SINGLE_ARRAY.equals(splitType[3]) || ARRAY.equals(splitType[4])) { return new ArrayType(elementType); } else if (MULTI_ARRAY.equals(splitType[3])) { return new ArrayType(new ArrayType(elementType)); } else { return elementType; } } }
1,795
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlExceptionMapper.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.postgresql; 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 lombok.NonNull; import javax.annotation.Nonnull; import java.sql.SQLException; /** * Exception mapper for PostgreSQL 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 PostgreSqlExceptionMapper implements JdbcExceptionMapper { /** * {@inheritDoc} */ @Override public ConnectorException toConnectorException( @Nonnull @NonNull final SQLException se, @Nonnull @NonNull final QualifiedName name ) { 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); } } }
1,796
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlConnectorModule.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.postgresql; 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.JdbcConnectorPartitionService; import com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService; import lombok.NonNull; import javax.annotation.Nonnull; import javax.sql.DataSource; import java.util.Map; /** * A Guice Module for the MySqlConnector. * * @author tgianos * @since 1.0.0 */ public class PostgreSqlConnectorModule extends AbstractModule { private final String catalogShardName; private final Map<String, String> configuration; /** * Constructor. * * @param catalogShardName catalog shard name * @param configuration connector configuration */ PostgreSqlConnectorModule( @Nonnull @NonNull final String catalogShardName, @Nonnull @NonNull 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(PostgreSqlTypeConverter.class).in(Scopes.SINGLETON); this.bind(JdbcExceptionMapper.class).to(PostgreSqlExceptionMapper.class).in(Scopes.SINGLETON); this.bind(ConnectorDatabaseService.class) .to(ConnectorUtils.getDatabaseServiceClass(this.configuration, PostgreSqlConnectorDatabaseService.class)) .in(Scopes.SINGLETON); this.bind(ConnectorTableService.class) .to(ConnectorUtils.getTableServiceClass(this.configuration, JdbcConnectorTableService.class)) .in(Scopes.SINGLETON); this.bind(ConnectorPartitionService.class) .to(ConnectorUtils.getPartitionServiceClass(this.configuration, JdbcConnectorPartitionService.class)) .in(Scopes.SINGLETON); } }
1,797
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlConnectorFactory.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.postgresql; import com.google.common.collect.Lists; import com.netflix.metacat.common.server.connectors.DefaultConnectorFactory; import lombok.NonNull; import javax.annotation.Nonnull; import java.util.Map; /** * PostgreSQL implementation of a connector factory. * * @author tgianos * @since 1.0.0 */ class PostgreSqlConnectorFactory extends DefaultConnectorFactory { /** * Constructor. * * @param name catalog name * @param catalogShardName catalog shard name * @param configuration catalog configuration */ PostgreSqlConnectorFactory( @Nonnull @NonNull final String name, @Nonnull @NonNull final String catalogShardName, @Nonnull @NonNull final Map<String, String> configuration ) { super(name, catalogShardName, Lists.newArrayList(new PostgreSqlConnectorModule(catalogShardName, configuration))); } }
1,798
0
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector
Create_ds/metacat/metacat-connector-postgresql/src/main/java/com/netflix/metacat/connector/postgresql/PostgreSqlConnectorPlugin.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.postgresql; 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; /** * Implementation of the ConnectorPlugin interface for PostgreSQL. * * @author tgianos * @since 1.0.0 */ public class PostgreSqlConnectorPlugin implements ConnectorPlugin { private static final String CONNECTOR_TYPE = "postgresql"; private static final PostgreSqlTypeConverter TYPE_CONVERTER = new PostgreSqlTypeConverter(); /** * {@inheritDoc} */ @Override public String getType() { return CONNECTOR_TYPE; } /** * {@inheritDoc} */ @Override public ConnectorFactory create(@Nonnull @NonNull final ConnectorContext connectorContext) { return new PostgreSqlConnectorFactory(connectorContext.getCatalogName(), connectorContext.getCatalogShardName(), connectorContext.getConfiguration()); } /** * {@inheritDoc} */ @Override public ConnectorTypeConverter getTypeConverter() { return TYPE_CONVERTER; } }
1,799