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/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/SharedResourceFactoryResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
/**
* An empty interface for responses from a {@link SharedResourceFactory}.
*/
public interface SharedResourceFactoryResponse<T> {
}
| 2,000 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/ScopeInstance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
/**
* A specific scope for a {@link ScopeType}. For example, each task in a process could be a different scope.
*
* <p>
* Note: {@link ScopeInstance}s will be rendered using {@link #toString()}, and will be compared using
* {@link #equals(Object)}. It is important to implement appropriate {@link #equals(Object)} and {@link #hashCode()}
* for correct functionality of {@link SharedResourcesBroker}. For example, if a scope for the same task is created
* in two different locations, they should still be equal under {@link #equals(Object)}.
* </p>
*
* @param <S> the {@link ScopeType} tree that this scope belongs to.
*/
public interface ScopeInstance<S extends ScopeType<S>> {
/**
* @return type of {@link ScopeType}.
*/
S getType();
/**
* @return a String identifying this scope.
*/
String getScopeId();
}
| 2,001 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/ScopeType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Represents a DAG of scope types.
*
* For example, the topology of a distributed application might have scopes as follows:
* <pre>
* GLOBAL -> INSTANCE --> JOB --> TASK
* \-> CONTAINER -/
* </pre>
*
* Where global represents multiple separate instances or even other applications, the instance creates containers
* and process jobs, and each task of a job is run in a container. As seen in the graph, instance is a child of
* global, job and container are children of instance, and task is a child of both job and container.
*
* @param <S> itself.
*/
public interface ScopeType<S extends ScopeType<S>> {
/**
* The name of this {@link ScopeType}.
*/
String name();
/**
* @return Whether this _scopeInstance is process-local or shared across different processes.
*/
boolean isLocal();
/**
* @return Collection of parent scopes in the DAG.
*/
@Nullable
Collection<S> parentScopes();
/**
* @return a default {@link ScopeInstance} for this {@link ScopeType}, or null if no such default exists.
*/
@Nullable ScopeInstance<S> defaultScopeInstance();
/**
* @return the root {@link ScopeType} in the DAG.
*/
S rootScope();
}
| 2,002 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/SharedResourceKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
/**
* A key to differentiate objects generated by the same factory for a {@link SharedResourcesBroker}. The
* {@link SharedResourcesBroker} is guaranteed to return the same object for the same factory, {@link ScopeInstance},
* and {@link SharedResourceKey}, but different objects if any of this differ. The key can contain information relevant
* to the factory.
*
* Note: keys are compared using {@link #equals(Object)}. It is important for implementations to override this method.
*
* Example: for a file handle factory, the key could specify the path of the file for which the handle is needed.
*/
public interface SharedResourceKey {
/**
* @return A serialization of the {@link SharedResourceKey} into a short, sanitized string. Users configure a
* shared resource using the value of this method.
*/
String toConfigurationKey();
}
| 2,003 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/ConfigView.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
import com.typesafe.config.Config;
/**
* Provides a view of a {@link Config} specific to a {@link SharedResourceKey} and factory.
*/
public interface ConfigView<S extends ScopeType<S>, K extends SharedResourceKey> {
/**
* @return The name of the factory this {@link ConfigView} was created for.
*/
String getFactoryName();
/**
* @return The {@link SharedResourceKey} this {@link ConfigView} was created for.
*/
K getKey();
/**
* @return the {@link Config} to use for creation of the new resource.
*/
Config getConfig();
/**
* @return get a view of this {@link ConfigView} at a specific {@link ScopeType}.
*/
ScopedConfigView<S, K> getScopedView(S scopeType);
}
| 2,004 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/SharedResourceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
/**
* A factory that creates {@link ScopeInstance} specific objects.
* @param <T> type of objects this factory creates.
* @param <K> type of {@link SharedResourceKey} this factory uses.
*/
public interface SharedResourceFactory<T, K extends SharedResourceKey, S extends ScopeType<S>> {
/**
* @return An identifier for this factory. Users will configure shared resources using this name.
*/
String getName();
/**
* Requests an object for the provided {@link SharedResourceKey}, with the provided configuration.
* The factory can return a variety of responses:
* * {@link org.apache.gobblin.broker.ResourceEntry}: a newly built resource of type T for the input key and scope.
* * {@link org.apache.gobblin.broker.ResourceCoordinate}: the coordinates (factory, key, scope) of another resource of type T that
* should be used instead (this allows, for example, to use a different factory, or always return a global scoped object.)
*/
SharedResourceFactoryResponse<T>
createResource(SharedResourcesBroker<S> broker, ScopedConfigView<S, K> config) throws NotConfiguredException;
/**
* @return The {@link ScopeType} at which an auto scoped resource should be created. A good default is to return
* broker.selfScope()
*/
S getAutoScope(SharedResourcesBroker<S> broker, ConfigView<S, K> config);
}
| 2,005 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/iface/ScopedConfigView.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.iface;
import com.typesafe.config.Config;
/**
* Provides a view of a {@link Config} specific to a factory, {@link SharedResourceKey} and {@link ScopeInstance}.
*/
public interface ScopedConfigView<S extends ScopeType<S>, K extends SharedResourceKey>
extends ConfigView<S, K> {
/**
* @return The {@link ScopeInstance} this {@link ScopedConfigView} was created for.
*/
S getScope();
}
| 2,006 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/gobblin_scopes/JobScopeInstance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.gobblin_scopes;
import lombok.Getter;
/**
* A {@link org.apache.gobblin.broker.iface.ScopeInstance} for a Gobblin job.
*/
@Getter
public class JobScopeInstance extends GobblinScopeInstance {
private final String jobName;
private final String jobId;
public JobScopeInstance(String jobName, String jobId) {
super(GobblinScopeTypes.JOB, jobName + ", id=" + jobId);
this.jobName = jobName;
this.jobId = jobId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
JobScopeInstance that = (JobScopeInstance) o;
if (!jobName.equals(that.jobName)) {
return false;
}
return jobId.equals(that.jobId);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + jobName.hashCode();
result = 31 * result + jobId.hashCode();
return result;
}
}
| 2,007 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/gobblin_scopes/GobblinScopeInstance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.gobblin_scopes;
import org.apache.gobblin.broker.SimpleScope;
/**
* {@link org.apache.gobblin.broker.iface.ScopeInstance} superclass for scopes used in Gobblin ingestion jobs.
*/
public class GobblinScopeInstance extends SimpleScope<GobblinScopeTypes> {
public GobblinScopeInstance(GobblinScopeTypes type, String scopeId) {
super(type, scopeId);
if (!type.getBaseInstanceClass().isAssignableFrom(this.getClass())) {
throw new IllegalArgumentException(String.format("A scope with type %s must be a subclass of %s.", type,
type.getBaseInstanceClass()));
}
}
}
| 2,008 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/gobblin_scopes/TaskScopeInstance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.gobblin_scopes;
import lombok.Getter;
/**
* A {@link org.apache.gobblin.broker.iface.ScopeInstance} for a Gobblin task.
*/
public class TaskScopeInstance extends GobblinScopeInstance {
@Getter
private final String taskId;
public TaskScopeInstance(String taskId) {
super(GobblinScopeTypes.TASK, taskId);
this.taskId = taskId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
TaskScopeInstance that = (TaskScopeInstance) o;
return taskId.equals(that.taskId);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + taskId.hashCode();
return result;
}
}
| 2,009 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/broker/gobblin_scopes/GobblinScopeTypes.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.broker.gobblin_scopes;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.gobblin.broker.iface.ScopeInstance;
import org.apache.gobblin.broker.iface.ScopeType;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.Getter;
/**
* Scope topology for Gobblin ingestion applications.
*/
public enum GobblinScopeTypes implements ScopeType<GobblinScopeTypes> {
GLOBAL("global", GobblinScopeInstance.class),
INSTANCE("instance", GobblinScopeInstance.class, GLOBAL),
JOB(null, JobScopeInstance.class, INSTANCE),
CONTAINER("container", GobblinScopeInstance.class, INSTANCE),
MULTI_TASK_ATTEMPT("multiTask", GobblinScopeInstance.class, JOB, CONTAINER),
TASK(null, TaskScopeInstance.class, MULTI_TASK_ATTEMPT);
private static final Set<GobblinScopeTypes> LOCAL_SCOPES = Sets.newHashSet(CONTAINER, TASK, MULTI_TASK_ATTEMPT);
private final List<GobblinScopeTypes> parentScopes;
private final String defaultId;
@Getter(AccessLevel.PACKAGE)
private final Class<?> baseInstanceClass;
GobblinScopeTypes(String defaultId, Class<?> baseInstanceClass, GobblinScopeTypes... parentScopes) {
this.defaultId = defaultId;
this.parentScopes = Lists.newArrayList(parentScopes);
this.baseInstanceClass = baseInstanceClass;
}
@Override
public boolean isLocal() {
return LOCAL_SCOPES.contains(this);
}
@Override
public Collection<GobblinScopeTypes> parentScopes() {
return this.parentScopes;
}
@Nullable
@Override
public ScopeInstance<GobblinScopeTypes> defaultScopeInstance() {
return this.defaultId == null ? null : new GobblinScopeInstance(this, this.defaultId);
}
@Override
public GobblinScopeTypes rootScope() {
return GLOBAL;
}
}
| 2,010 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter/DataConversionException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.converter;
/**
* A type of {@link Exception} thrown when there's anything wrong
* with data conversion.
*
* @author Yinan Li
*/
public class DataConversionException extends Exception {
private static final long serialVersionUID = 1L;
public DataConversionException(Throwable cause) {
super(cause);
}
public DataConversionException(String message, Throwable cause) {
super(message, cause);
}
public DataConversionException(String message) {
super(message);
}
}
| 2,011 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter/Converter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.converter;
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.converter.initializer.ConverterInitializer;
import org.apache.gobblin.converter.initializer.NoopConverterInitializer;
import org.apache.gobblin.metadata.GlobalMetadata;
import org.apache.gobblin.stream.ControlMessage;
import org.apache.gobblin.records.ControlMessageHandler;
import org.apache.gobblin.records.RecordStreamProcessor;
import org.apache.gobblin.records.RecordStreamWithMetadata;
import org.apache.gobblin.stream.MetadataUpdateControlMessage;
import org.apache.gobblin.stream.RecordEnvelope;
import org.apache.gobblin.source.workunit.WorkUnitStream;
import org.apache.gobblin.stream.StreamEntity;
import org.apache.gobblin.util.FinalState;
import com.google.common.base.Optional;
import io.reactivex.Flowable;
/**
* An interface for classes that implement data transformations, e.g., data type
* conversions, schema projections, data manipulations, data filtering, etc.
*
* <p>
* This interface is responsible for converting both schema and data records. Classes
* implementing this interface are composible and can be chained together to achieve
* more complex data transformations.
* </p>
*
* @author kgoodhop
*
* @param <SI> input schema type
* @param <SO> output schema type
* @param <DI> input data type
* @param <DO> output data type
*/
public abstract class Converter<SI, SO, DI, DO> implements Closeable, FinalState, RecordStreamProcessor<SI, SO, DI, DO> {
// Metadata containing the output schema. This may be changed when a MetadataUpdateControlMessage is received.
private GlobalMetadata<SO> outputGlobalMetadata;
/**
* Initialize this {@link Converter}.
*
* @param workUnit a {@link WorkUnitState} object carrying configuration properties
* @return an initialized {@link Converter} instance
*/
public Converter<SI, SO, DI, DO> init(WorkUnitState workUnit) {
return this;
}
@Override
public void close() throws IOException {
}
/**
* Convert an input schema to an output schema.
*
* <p>
* Schema conversion is limited to have a 1-to-1 mapping between the input and output schema.
* When try to convert avro schema, please call {@link AvroUtils.addSchemaCreationTime to preserve schame creationTime}
* </p>
*
* @param inputSchema input schema to be converted
* @param workUnit a {@link WorkUnitState} object carrying configuration properties
* @return converted output schema
* @throws SchemaConversionException if it fails to convert the input schema
*/
public abstract SO convertSchema(SI inputSchema, WorkUnitState workUnit)
throws SchemaConversionException;
/**
* Convert an input data record to an {@link java.lang.Iterable} of output records
* conforming to the output schema of {@link Converter#convertSchema}.
*
* <p>
* Record conversion can have a 1-to-0 mapping, 1-to-1 mapping, or 1-to-many mapping between the
* input and output records as long as all the output records conforms to the same converted schema.
* </p>
*
* <p>Converter for data record, both record type conversion, and record manipulation conversion.</p>
* @param outputSchema output schema converted using the {@link Converter#convertSchema} method
* @param inputRecord input data record to be converted
* @param workUnit a {@link WorkUnitState} object carrying configuration properties
* @return converted data record
* @throws DataConversionException if it fails to convert the input data record
*/
public abstract Iterable<DO> convertRecord(SO outputSchema, DI inputRecord, WorkUnitState workUnit)
throws DataConversionException;
/**
* Converts a {@link RecordEnvelope}. This method can be overridden by implementations that need to manipulate the
* {@link RecordEnvelope}, such as to set watermarks or metadata.
* @param outputSchema output schema converted using the {@link Converter#convertSchema} method
* @param inputRecordEnvelope input record envelope with data record to be converted
* @param workUnitState a {@link WorkUnitState} object carrying configuration properties
* @return a {@link Flowable} emitting the converted {@link RecordEnvelope}s
* @throws DataConversionException
*/
protected Flowable<RecordEnvelope<DO>> convertRecordEnvelope(SO outputSchema, RecordEnvelope<DI> inputRecordEnvelope,
WorkUnitState workUnitState) throws DataConversionException {
Iterator<DO> convertedIterable = convertRecord(outputSchema,
inputRecordEnvelope.getRecord(), workUnitState).iterator();
if (!convertedIterable.hasNext()) {
inputRecordEnvelope.ack();
// if the iterable is empty, ack the record, return an empty flowable
return Flowable.empty();
}
DO firstRecord = convertedIterable.next();
if (!convertedIterable.hasNext()) {
// if the iterable has only one element, use RecordEnvelope.withRecord, which is more efficient
return Flowable.just(inputRecordEnvelope.withRecord(firstRecord));
} else {
// if the iterable has multiple records, use a ForkRecordBuilder
RecordEnvelope<DI>.ForkRecordBuilder<DO> forkRecordBuilder = inputRecordEnvelope.forkRecordBuilder();
return Flowable.just(firstRecord).concatWith(Flowable.fromIterable(() -> convertedIterable))
.map(forkRecordBuilder::childRecord).doOnComplete(forkRecordBuilder::close);
}
}
/**
* Get final state for this object. By default this returns an empty {@link org.apache.gobblin.configuration.State}, but
* concrete subclasses can add information that will be added to the task state.
* @return Empty {@link org.apache.gobblin.configuration.State}.
*/
@Override
public State getFinalState() {
return new State();
}
/**
* Apply conversions to the input {@link RecordStreamWithMetadata}.
*/
@Override
public RecordStreamWithMetadata<DO, SO> processStream(RecordStreamWithMetadata<DI, SI> inputStream,
WorkUnitState workUnitState) throws SchemaConversionException {
init(workUnitState);
this.outputGlobalMetadata = GlobalMetadata.<SI, SO>builderWithInput(inputStream.getGlobalMetadata(),
Optional.fromNullable(convertSchema(inputStream.getGlobalMetadata().getSchema(), workUnitState))).build();
Flowable<StreamEntity<DO>> outputStream =
inputStream.getRecordStream()
.flatMap(in -> {
if (in instanceof ControlMessage) {
ControlMessage out = (ControlMessage) in;
getMessageHandler().handleMessage((ControlMessage) in);
// update the output schema with the new input schema from the MetadataUpdateControlMessage
if (in instanceof MetadataUpdateControlMessage) {
this.outputGlobalMetadata = GlobalMetadata.<SI, SO>builderWithInput(
((MetadataUpdateControlMessage) in).getGlobalMetadata(),
Optional.fromNullable(convertSchema((SI)((MetadataUpdateControlMessage) in).getGlobalMetadata()
.getSchema(), workUnitState))).build();
out = new MetadataUpdateControlMessage<SO, DO>(this.outputGlobalMetadata);
}
return Flowable.just(((ControlMessage<DO>) out));
} else if (in instanceof RecordEnvelope) {
RecordEnvelope<DI> recordEnvelope = (RecordEnvelope<DI>) in;
return convertRecordEnvelope(this.outputGlobalMetadata.getSchema(), recordEnvelope, workUnitState);
} else {
throw new UnsupportedOperationException();
}
}, 1);
outputStream = outputStream.doOnComplete(this::close);
return inputStream.withRecordStream(outputStream, this.outputGlobalMetadata);
}
/**
* @return {@link ControlMessageHandler} to call for each {@link ControlMessage} received.
*/
public ControlMessageHandler getMessageHandler() {
return ControlMessageHandler.NOOP;
}
public ConverterInitializer getInitializer(State state, WorkUnitStream workUnits, int branches, int branchId) {
return NoopConverterInitializer.INSTANCE;
}
}
| 2,012 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter/SchemaConversionException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.converter;
import org.apache.gobblin.records.RecordStreamProcessor;
/**
* A type of {@link Exception} thrown when there's anything wrong
* with schema conversion.
*
* @author Yinan Li
*/
public class SchemaConversionException extends RecordStreamProcessor.StreamProcessingException {
private static final long serialVersionUID = 1L;
public SchemaConversionException(Throwable cause) {
super(cause);
}
public SchemaConversionException(String message, Throwable cause) {
super(message, cause);
}
public SchemaConversionException(String message) {
super(message);
}
}
| 2,013 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter/initializer/ConverterInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.converter.initializer;
import org.apache.gobblin.initializer.Initializer;
/**
* ConverterInitializer is being invoked at driver which means it will only invoked once per converter.
* This is to remove any duplication work among task, and any initialization that is same per task can be put in here.
*/
public interface ConverterInitializer extends Initializer {
} | 2,014 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/converter/initializer/NoopConverterInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.converter.initializer;
import lombok.ToString;
import org.apache.gobblin.initializer.Initializer;
import org.apache.gobblin.initializer.NoopInitializer;
@ToString
public class NoopConverterInitializer implements ConverterInitializer {
public static final NoopConverterInitializer INSTANCE = new NoopConverterInitializer();
private final Initializer initializer = NoopInitializer.INSTANCE;
private NoopConverterInitializer() {}
@Override
public void initialize() {
this.initializer.initialize();
}
@Override
public void close() {
this.initializer.close();
}
}
| 2,015 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/CompletedFuture.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class CompletedFuture<T> implements Future<T> {
private final T v;
private final Throwable re;
public CompletedFuture(T v, Throwable re) {
this.v = v;
this.re = re;
}
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return true;
}
public T get() throws ExecutionException {
if(this.re != null) {
throw new ExecutionException(this.re);
} else {
return this.v;
}
}
public T get(long timeout, TimeUnit unit) throws ExecutionException {
return this.get();
}
}
| 2,016 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/Decorator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
/**
* Interface for decorator patterns.
*/
public interface Decorator {
/**
* Get directly underlying object.
* @return directly underlying object.
*/
public Object getDecoratedObject();
}
| 2,017 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/ClassAliasResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import java.util.List;
import java.util.Map;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;
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 javax.annotation.concurrent.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.annotation.Alias;
/**
* A class that scans through all classes in the classpath annotated with {@link Alias} and is a subType of <code>subTypeOf</code> constructor argument.
* It caches the alias to class mapping. Applications can call {@link #resolve(String)} to resolve a class's alias to its
* cannonical name.
*
* <br>
* <b>Note : If same alias is used for multiple classes in the classpath, the first mapping in classpath scan holds good.
* Subsequent ones will be logged and ignored.
* </b>
*
* <br>
* <b>
* Note: For the moment this class will only look for classes with gobblin/com.linkedin.gobblin prefix, as scanning
* the entire classpath is very expensive.
* </b>
*/
@Slf4j
@ThreadSafe
public class ClassAliasResolver<T> {
// Scan all packages in the classpath with prefix gobblin, com.linkedin.gobblin when class is loaded.
// Since scan is expensive we do it only once when class is loaded.
private static final Reflections REFLECTIONS =
new Reflections(new ConfigurationBuilder().forPackages("gobblin", "com.linkedin.gobblin", "org.apache.gobblin"));
private final List<Alias> aliasObjects;
private final Class<T> subtypeOf;
ImmutableMap<String, Class<? extends T>> aliasToClassCache;
public ClassAliasResolver(Class<T> subTypeOf) {
Map<String, Class<? extends T>> cache = Maps.newHashMap();
this.aliasObjects = Lists.newArrayList();
for (Class<? extends T> clazz : REFLECTIONS.getSubTypesOf(subTypeOf)) {
if (clazz.isAnnotationPresent(Alias.class)) {
Alias aliasObject = clazz.getAnnotation(Alias.class);
String alias = aliasObject.value().toUpperCase();
if (cache.containsKey(alias)) {
log.warn(String.format("Alias %s already mapped to class %s. Mapping for %s will be ignored", alias,
cache.get(alias).getCanonicalName(), clazz.getCanonicalName()));
} else {
aliasObjects.add(aliasObject);
cache.put(clazz.getAnnotation(Alias.class).value().toUpperCase(), clazz);
}
}
}
this.subtypeOf = subTypeOf;
this.aliasToClassCache = ImmutableMap.copyOf(cache);
}
/**
* Resolves the given alias to its name if a mapping exits. To create a mapping for a class,
* it has to be annotated with {@link Alias}
*
* @param possibleAlias to use for resolution.
* @return The name of the class with <code>possibleAlias</code> if mapping is available.
* Return the input <code>possibleAlias</code> if no mapping is found.
*/
public String resolve(final String possibleAlias) {
if (this.aliasToClassCache.containsKey(possibleAlias.toUpperCase())) {
return this.aliasToClassCache.get(possibleAlias.toUpperCase()).getName();
}
return possibleAlias;
}
/**
* Attempts to resolve the given alias to a class. It first tries to find a class in the classpath with this alias
* and is also a subclass of {@link #subtypeOf}, if it fails it returns a class object for name
* <code>aliasOrClassName</code>.
*/
public Class<? extends T> resolveClass(final String aliasOrClassName)
throws ClassNotFoundException {
if (this.aliasToClassCache.containsKey(aliasOrClassName.toUpperCase())) {
return this.aliasToClassCache.get(aliasOrClassName.toUpperCase());
}
try {
return Class.forName(aliasOrClassName).asSubclass(this.subtypeOf);
} catch (ClassCastException cce) {
throw new ClassNotFoundException(
String.format("Found class %s but it cannot be cast to %s.", aliasOrClassName, this.subtypeOf.getName()),
cce);
}
}
/**
* Get the map from found aliases to classes.
*/
public Map<String, Class<? extends T>> getAliasMap() {
return ImmutableMap.copyOf(this.aliasToClassCache);
}
public List<Alias> getAliasObjects() {
return ImmutableList.copyOf(this.aliasObjects);
}
}
| 2,018 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/RecordCountProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import java.util.Collection;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.hadoop.fs.Path;
/**
* A class for obtaining record counts from data.
*/
public abstract class RecordCountProvider {
/**
* Get record count from a given {@link Path}.
*/
public abstract long getRecordCount(Path path);
/**
* Convert a {@link Path} from another {@link RecordCountProvider} so that it can be used
* in {@link #getRecordCount(Path)} of this {@link RecordCountProvider}.
*/
public Path convertPath(Path path, String extension, RecordCountProvider src) {
if (this.getClass().equals(src.getClass())) {
return path;
}
throw getNotImplementedException(src);
}
protected NotImplementedException getNotImplementedException(RecordCountProvider src) {
return new NotImplementedException(String.format("converting from %s to %s is not implemented",
src.getClass().getName(), this.getClass().getName()));
}
/**
* Get record count for a list of paths.
*/
public long getRecordCount(Collection<Path> paths) {
long count = 0;
for (Path path : paths) {
count += getRecordCount(path);
}
return count;
}
}
| 2,019 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/FinalState.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import org.apache.gobblin.configuration.State;
/**
* Interface for constructs that can report their final state.
*/
public interface FinalState {
/**
* Called by tasks after all work for the construct has been executed. The construct can return a state
* describing a summary of its execution / final state.
* @return a {@link org.apache.gobblin.configuration.State} with summary of execution / final state of the construct.
*/
public State getFinalState();
}
| 2,020 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/DecoratorUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import java.util.List;
import com.google.common.collect.Lists;
/**
* Utilities for classes implementing the decorator interface.
*/
public class DecoratorUtils {
/**
* Resolves the truly underlying object in a possible chain of {@link org.apache.gobblin.util.Decorator}.
*
* @param obj object to resolve.
* @return the true non-decorator underlying object.
*/
public static Object resolveUnderlyingObject(Object obj) {
while(obj instanceof Decorator) {
obj = ((Decorator)obj).getDecoratedObject();
}
return obj;
}
/**
* Finds the decorator lineage of the given object.
*
* <p>
* If object is not a {@link org.apache.gobblin.util.Decorator}, this method will return a singleton list with just the object.
* If object is a {@link org.apache.gobblin.util.Decorator}, it will return a list of the underlying object followed by the
* decorator lineage up to the input decorator object.
* </p>
*
* @param obj an object.
* @return List of the non-decorator underlying object and all decorators on top of it,
* starting with underlying object and ending with the input object itself (inclusive).
*/
public static List<Object> getDecoratorLineage(Object obj) {
List<Object> lineage = Lists.newArrayList(obj);
Object currentObject = obj;
while(currentObject instanceof Decorator) {
currentObject = ((Decorator)currentObject).getDecoratedObject();
lineage.add(currentObject);
}
return Lists.reverse(lineage);
}
}
| 2,021 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/TaskEventMetadataUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.runtime.api.TaskEventMetadataGenerator;
public class TaskEventMetadataUtils {
/**
* Construct a {@link TaskEventMetadataGenerator} from the task state.
* @param taskState
* @return
*/
public static TaskEventMetadataGenerator getTaskEventMetadataGenerator(State taskState) {
String taskEventMetadataGeneratorClassName =
taskState.getProp(ConfigurationKeys.TASK_EVENT_METADATA_GENERATOR_CLASS_KEY,
ConfigurationKeys.DEFAULT_TASK_EVENT_METADATA_GENERATOR_CLASS_KEY);
ClassAliasResolver<TaskEventMetadataGenerator> aliasResolver =
new ClassAliasResolver<>(TaskEventMetadataGenerator.class);
try {
return aliasResolver.resolveClass(taskEventMetadataGeneratorClassName).newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Could not construct TaskEventMetadataGenerator " +
taskEventMetadataGeneratorClassName, e);
}
}
}
| 2,022 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/util/io/GsonInterfaceAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.util.io;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang3.ClassUtils;
import com.google.common.base.Optional;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* A {@link Gson} interface adapter that makes it possible to serialize and deserialize polymorphic objects.
*
* <p>
* This adapter will capture all instances of {@link #baseClass} and write them as
* {"object-type":"class.name", "object-data":"data"}, allowing for correct serialization and deserialization of
* polymorphic objects. The following types will not be captured by the adapter (i.e. they will be written by the
* default GSON writer):
* - Primitives and boxed primitives
* - Arrays
* - Collections
* - Maps
* Additionally, generic classes (e.g. class MyClass<T>) cannot be correctly decoded.
* </p>
*
* <p>
* To use:
* <pre>
* {@code
* MyClass object = new MyClass();
* Gson gson = GsonInterfaceAdapter.getGson(MyBaseClass.class);
* String json = gson.toJson(object);
* Myclass object2 = gson.fromJson(json, MyClass.class);
* }
* </pre>
* </p>
*
* <p>
* Note: a useful case is GsonInterfaceAdapter.getGson(Object.class), which will correctly serialize / deserialize
* all types except for java generics.
* </p>
*
* @param <T> The interface or abstract type to be serialized and deserialized with {@link Gson}.
*/
@RequiredArgsConstructor
public class GsonInterfaceAdapter implements TypeAdapterFactory {
protected static final String OBJECT_TYPE = "object-type";
protected static final String OBJECT_DATA = "object-data";
private final Class<?> baseClass;
@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (ClassUtils.isPrimitiveOrWrapper(type.getRawType()) || type.getType() instanceof GenericArrayType
|| CharSequence.class.isAssignableFrom(type.getRawType())
|| (type.getType() instanceof ParameterizedType && (Collection.class.isAssignableFrom(type.getRawType())
|| Map.class.isAssignableFrom(type.getRawType())))) {
// delegate primitives, arrays, collections, and maps
return null;
}
if (!this.baseClass.isAssignableFrom(type.getRawType())) {
// delegate anything not assignable from base class
return null;
}
TypeAdapter<R> adapter = new InterfaceAdapter<>(gson, this, type);
return adapter;
}
@AllArgsConstructor
private static class InterfaceAdapter<R> extends TypeAdapter<R> {
private final Gson gson;
private final TypeAdapterFactory factory;
private final TypeToken<R> typeToken;
@Override
public void write(JsonWriter out, R value) throws IOException {
if (Optional.class.isAssignableFrom(this.typeToken.getRawType())) {
Optional opt = (Optional) value;
if (opt != null && opt.isPresent()) {
Object actualValue = opt.get();
writeObject(actualValue, out);
} else {
out.beginObject();
out.endObject();
}
} else {
writeObject(value, out);
}
}
@Override
public R read(JsonReader in) throws IOException {
JsonElement element = Streams.parse(in);
if (element.isJsonNull()) {
return readNull();
}
JsonObject jsonObject = element.getAsJsonObject();
if (this.typeToken.getRawType() == Optional.class) {
if (jsonObject.has(OBJECT_TYPE)) {
return (R) Optional.of(readValue(jsonObject, null));
} else if (jsonObject.entrySet().isEmpty()) {
return (R) Optional.absent();
} else {
throw new IOException("No class found for Optional value.");
}
}
return this.readValue(jsonObject, this.typeToken);
}
private <S> S readNull() {
if (this.typeToken.getRawType() == Optional.class) {
return (S) Optional.absent();
}
return null;
}
private <S> void writeObject(S value, JsonWriter out) throws IOException {
if (value != null) {
JsonObject jsonObject = new JsonObject();
jsonObject.add(OBJECT_TYPE, new JsonPrimitive(value.getClass().getName()));
TypeAdapter<S> delegate =
(TypeAdapter<S>) this.gson.getDelegateAdapter(this.factory, TypeToken.get(value.getClass()));
jsonObject.add(OBJECT_DATA, delegate.toJsonTree(value));
Streams.write(jsonObject, out);
} else {
out.nullValue();
}
}
private <S> S readValue(JsonObject jsonObject, TypeToken<S> defaultTypeToken) throws IOException {
try {
TypeToken<S> actualTypeToken;
if (jsonObject.isJsonNull()) {
return null;
} else if (jsonObject.has(OBJECT_TYPE)) {
String className = jsonObject.get(OBJECT_TYPE).getAsString();
Class<S> klazz = (Class<S>) Class.forName(className);
actualTypeToken = TypeToken.get(klazz);
} else if (defaultTypeToken != null) {
actualTypeToken = defaultTypeToken;
} else {
throw new IOException("Could not determine TypeToken.");
}
TypeAdapter<S> delegate = this.gson.getDelegateAdapter(this.factory, actualTypeToken);
S value = delegate.fromJsonTree(jsonObject.get(OBJECT_DATA));
return value;
} catch (ClassNotFoundException cnfe) {
throw new IOException(cnfe);
}
}
}
public static <T> Gson getGson(Class<T> clazz) {
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonInterfaceAdapter(clazz)).create();
return gson;
}
}
| 2,023 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/Default.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Default {
String value();
}
| 2,024 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/Alias.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Alias {
String value();
}
| 2,025 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/Key.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Key {
String value();
}
| 2,026 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/TypedConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
public class TypedConfig {
public TypedConfig(Properties prop) {
if (prop != null) {
fulfillFields(this.getClass(), prop);
}
}
@SneakyThrows
private void fulfillFields(Class<? extends TypedConfig> clazz, Properties prop) {
if (!clazz.equals(TypedConfig.class)) {
this.fulfillFields((Class<? extends TypedConfig>) clazz.getSuperclass(), prop);
}
for (Field field : clazz.getDeclaredFields()) {
if (field.getAnnotations().length == 0) {
continue;
}
Object defaultValue = pickupDefaultValue(field); // get default value which is in config class
Object configValue = pickupValueByKey(field, prop); // get ini file config value by key
if (configValue == null) {
configValue = pickupValueByAlias(field, prop); // by alias (2nd key)
}
if (configValue == null) {
configValue = defaultValue;
}
if (configValue != null) {
configValue = ConstraintUtil.constraint(field, configValue);
field.set(this, convert(configValue, field.getType()));
}
}
}
private Object pickupDefaultValue(Field field) {
Default defaultAnn = field.getAnnotation(Default.class);
if (defaultAnn == null) {
return null;
}
return defaultAnn.value(); // the value was put in source code instead of ini file
}
private Object pickupValueByAlias(Field field, Properties prop) {
Alias alias = field.getAnnotation(Alias.class);
if (alias == null) {
return null;
}
return prop.get(alias.value()); // get ini config value by alias(2nd key)
}
private Object pickupValueByKey(Field field, Properties prop) {
Key key = field.getAnnotation(Key.class);
if (key == null) {
return null;
}
return prop.get(key.value()); // get ini config value by key
}
private Object convert(Object value, Class targetClazz) {
if (value == null) {
return null;
}
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() {
@SneakyThrows
@Override
public Object convert(Object value, Class clazz) {
if (clazz.isEnum()) {
return Enum.valueOf(clazz, (String) value);
} else if (clazz == Date.class) {
String dateStr = ((String) value).replaceAll("-| |:", ""); // date format: 1, 2020-01-02 03:04:59, 2, 20200102030459
dateStr = String.format("%-14s", dateStr).replaceAll(" ", "0");
Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr);
return date;
} else {
return super.convert(value, clazz);
}
}
});
return beanUtilsBean.getConvertUtils().convert(value, targetClazz);
}
/**
* convert data to property
*/
@SneakyThrows
public Properties toProp() {
Properties prop = new Properties();
for (Field field : this.getClass().getDeclaredFields()) {
Key keyAnn = field.getAnnotation(Key.class);
if (keyAnn == null) {
continue;
}
Object configValue = field.get(this);
if (configValue == null) {
continue;
}
prop.put(keyAnn.value(), configValue.toString());
}
return prop;
}
}
| 2,027 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/ConstraintUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.typedconfig.compiletime.EnumOptions;
import org.apache.gobblin.typedconfig.compiletime.IntRange;
import org.apache.gobblin.typedconfig.compiletime.LongRange;
import org.apache.gobblin.typedconfig.compiletime.StringRegex;
/**
* Util class for handling constraint annotation
* supports: IntRange, LongRange, EnumOption, StringRegex
*/
@Slf4j
public class ConstraintUtil {
private ConstraintUtil() {
}
public static Object constraint(Field field, Object value) {
Class type = field.getType();
if (type.isEnum()) {
return getEnumValue(field, value);
}
switch (type.getName()) {
case "int": case "java.lang.Integer":
return getIntValue(field, value);
case "long": case "java.lang.Long":
return getLongValue(field, value);
case "java.lang.String":
return getStringValue(field, value);
case "boolean": case "java.lang.Boolean":
return getBooleanValue(field, value);
case "java.util.Date":
return getDateValue(field, value);
default:
throw new RuntimeException("not supported the return type: " + type.getName());
}
}
static private Object getIntValue(Field field, Object value) {
IntRange intRange = field.getAnnotation(IntRange.class);
if (intRange == null) {
return value;
}
int[] range = intRange.value();
int intValue = Integer.parseInt(value.toString());
if (range.length != 2) {
throw new RuntimeException(String.format("Field [%s]: Long range is invalid.", field.getName()));
}
if (intValue >= range[0] && intValue <= range[1]) {
return value;
} else {
throw new RuntimeException(
String.format("Field [%s]: value [%s] is out of range [%s, %s].", field.getName(), value, range[0], range[1])
);
}
}
static private Object getLongValue(Field field, Object value) {
LongRange longRange = field.getAnnotation(LongRange.class);
long[] range = longRange.value();
if (range == null) {
return value;
}
long longValue = Long.parseLong(value.toString());
if (range.length != 2) {
throw new RuntimeException(String.format("Field [%s]: Long range is invalid.", field.getName()));
}
if (longValue > range[0] && longValue < range[1]) {
return value;
} else {
throw new RuntimeException(
String.format("Field [%s]: value [%s] is out of range [%s, %s].", field.getName(), value, range[0], range[1])
);
}
}
static private Object getStringValue(Field field, Object value) {
StringRegex stringRegex = field.getAnnotation(StringRegex.class);
if (stringRegex == null) {
return value;
}
String regex = stringRegex.value();
if (regex == null) {
return value;
}
boolean isMatching = value.toString().matches(regex);
if (isMatching) {
return value;
} else {
throw new RuntimeException(String.format("[%s] is not matching pattern [%s]", value, regex));
}
}
static private Object getBooleanValue(Field field, Object value) {
return value; // there is no restriction for boolean value.
}
static private Object getDateValue(Field field, Object value) {
return value; // there is no restriction for Date value.
}
static private Object getEnumValue(Field field, Object value) {
EnumOptions enumOptions = field.getAnnotation(EnumOptions.class);
if (enumOptions == null) {
return value;
}
List<String> options = Arrays.asList(enumOptions.value());
if (options.indexOf(value) >= 0) {
return value;
} else {
throw new RuntimeException(String.format("Enum [%s] is not allowed.", value));
}
}
}
| 2,028 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/compiletime/StringRegex.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig.compiletime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StringRegex {
String value();
}
| 2,029 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/compiletime/LongRange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig.compiletime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LongRange {
long[] value();
}
| 2,030 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/compiletime/IntRange.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig.compiletime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IntRange {
int[] value();
}
| 2,031 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/typedconfig/compiletime/EnumOptions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.typedconfig.compiletime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnumOptions {
String[] value();
}
| 2,032 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/publisher/SingleTaskDataPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.publisher;
import java.io.IOException;
import com.google.common.base.Preconditions;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* A subclass of {@link DataPublisher} that can publish data of a single {@link Task}.
*/
public abstract class SingleTaskDataPublisher extends DataPublisher {
public SingleTaskDataPublisher(State state) {
super(state);
}
/**
* Publish the data for the given task. The state must contains property "writer.final.output.file.paths"
* (or "writer.final.output.file.paths.[branchId]" if there are multiple branches),
* so that the publisher knows which files to publish.
*/
public abstract void publishData(WorkUnitState state) throws IOException;
/**
* Publish the metadata (e.g., schema) for the given task. Checkpoints should not be published as part of metadata.
* They are published by Gobblin runtime after the metadata and data are published.
*/
public abstract void publishMetadata(WorkUnitState state) throws IOException;
/**
* First publish the metadata via {@link DataPublisher#publishMetadata(WorkUnitState)}, and then publish the output data
* via the {@link DataPublisher#publishData(WorkUnitState)} method.
*
* @param state is a {@link WorkUnitState}.
* @throws IOException if there is a problem with publishing the metadata or the data.
*/
public void publish(WorkUnitState state) throws IOException {
publishMetadata(state);
publishData(state);
}
/**
* Get an instance of {@link SingleTaskDataPublisher}.
*
* @param dataPublisherClass A concrete class that extends {@link SingleTaskDataPublisher}.
* @param state A {@link State} used to instantiate the {@link SingleTaskDataPublisher}.
* @return A {@link SingleTaskDataPublisher} instance.
* @throws ReflectiveOperationException
*/
public static SingleTaskDataPublisher getInstance(Class<? extends DataPublisher> dataPublisherClass, State state)
throws ReflectiveOperationException {
Preconditions.checkArgument(SingleTaskDataPublisher.class.isAssignableFrom(dataPublisherClass),
String.format("Cannot instantiate %s since it does not extend %s", dataPublisherClass.getSimpleName(),
SingleTaskDataPublisher.class.getSimpleName()));
return (SingleTaskDataPublisher) DataPublisher.getInstance(dataPublisherClass, state);
}
}
| 2,033 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/publisher/UnpublishedHandling.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.publisher;
import java.io.IOException;
import java.util.Collection;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* {@link DataPublisher}s implementing this interface will cause Gobblin to call {@link #handleUnpublishedWorkUnits} if
* it determines the job will not be published. This allows the publisher to run actions on partially successful jobs
* (e.g. recovery, notification, etc.).
*/
public interface UnpublishedHandling {
/**
* This method will be called by Gobblin if it determines that a job should not be published.
* @param states List of {@link WorkUnitState}s in the job.
* @throws IOException
*/
public void handleUnpublishedWorkUnits(Collection<? extends WorkUnitState> states) throws IOException;
}
| 2,034 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/publisher/DataPublisher.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.publisher;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Map;
import org.apache.gobblin.capability.Capability;
import org.apache.gobblin.capability.CapabilityAware;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* Defines how to publish data and its corresponding metadata. Can be used for either task level or job level publishing.
*/
public abstract class DataPublisher implements Closeable, CapabilityAware {
/**
* Reusable capability.
*/
public static final Capability REUSABLE = new Capability("REUSABLE", false);
protected final State state;
public DataPublisher(State state) {
this.state = state;
}
/**
* @deprecated {@link DataPublisher} initialization should be done in the constructor.
*/
@Deprecated
public abstract void initialize()
throws IOException;
/**
* Publish the data for the given tasks.
*/
public abstract void publishData(Collection<? extends WorkUnitState> states)
throws IOException;
/**
* Publish the metadata (e.g., schema) for the given tasks. Checkpoints should not be published as part of metadata.
* They are published by Gobblin runtime after the metadata and data are published.
*/
public abstract void publishMetadata(Collection<? extends WorkUnitState> states)
throws IOException;
/**
* First publish the metadata via {@link DataPublisher#publishMetadata(Collection)}, and then publish the output data
* via the {@link DataPublisher#publishData(Collection)} method.
*
* @param states is a {@link Collection} of {@link WorkUnitState}s.
* @throws IOException if there is a problem with publishing the metadata or the data.
*/
public void publish(Collection<? extends WorkUnitState> states)
throws IOException {
if (shouldPublishMetadataFirst()) {
publishMetadata(states);
publishData(states);
} else {
publishData(states);
publishMetadata(states);
}
markCommit(states);
}
protected void markCommit(Collection<? extends WorkUnitState> states) {
for (WorkUnitState workUnitState : states) {
if (workUnitState.getWorkingState() == WorkUnitState.WorkingState.SUCCESSFUL) {
workUnitState.setWorkingState(WorkUnitState.WorkingState.COMMITTED);
}
}
}
public State getState() {
return this.state;
}
/**
* Get an instance of {@link DataPublisher}.
*
* @param dataPublisherClass A concrete class that extends {@link DataPublisher}.
* @param state A {@link State} used to instantiate the {@link DataPublisher}.
* @return A {@link DataPublisher} instance.
*/
public static DataPublisher getInstance(Class<? extends DataPublisher> dataPublisherClass, State state)
throws ReflectiveOperationException {
Constructor<? extends DataPublisher> dataPublisherConstructor = dataPublisherClass.getConstructor(State.class);
return dataPublisherConstructor.newInstance(state);
}
/**
* Returns true if the implementation of {@link DataPublisher} is thread-safe.
*
* <p>
* For a thread-safe {@link DataPublisher}, this method should return this.getClass() == <class>.class
* to ensure that any extensions must explicitly be marked as thread safe.
* </p>
*/
public boolean isThreadSafe() {
return this.getClass() == DataPublisher.class;
}
/**
* Return true if the current publisher can be skipped.
*
* <p>
* For a publisher that can be skipped, it should not have any effect on state persistence. It will be skipped when
* a job is cancelled, and all finished tasks are configured to be committed.
* </p>
*/
public boolean canBeSkipped() {
return this.state.getPropAsBoolean(ConfigurationKeys.DATA_PUBLISHER_CAN_BE_SKIPPED,
ConfigurationKeys.DEFAULT_DATA_PUBLISHER_CAN_BE_SKIPPED);
}
/**
* Generally metadata should be published before the data it represents, but this allows subclasses to override
* if they are dependent on data getting published first.
*/
protected boolean shouldPublishMetadataFirst() {
return true;
}
@Override
public boolean supportsCapability(Capability c, Map<String, Object> properties) {
return false;
}
}
| 2,035 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/Dataset.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
/**
* Interface representing a dataset.
*/
public interface Dataset extends URNIdentified {
/**
* URN for this dataset.
* @deprecated use {@link #getUrn()}
*/
@Deprecated
public String datasetURN();
@Override
default String getUrn() {
return datasetURN();
}
}
| 2,036 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DescriptorResolverFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import com.typesafe.config.Config;
/**
* Factory to create a {@link DescriptorResolver} instance
*/
public interface DescriptorResolverFactory {
/**
* @param config configurations only about {@link DescriptorResolver}
*/
DescriptorResolver createResolver(Config config);
}
| 2,037 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/HiveToHdfsDatasetResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.apache.gobblin.configuration.State;
/**
* Singleton {@link DatasetResolver} to convert a Hive {@link DatasetDescriptor} to HDFS {@link DatasetDescriptor}
*/
public class HiveToHdfsDatasetResolver implements DatasetResolver {
public static final String HIVE_TABLE = "hiveTable";
public static final HiveToHdfsDatasetResolver INSTANCE = new HiveToHdfsDatasetResolver();
private HiveToHdfsDatasetResolver() {
// To make it singleton
}
@Override
public DatasetDescriptor resolve(DatasetDescriptor raw, State state) {
ImmutableMap<String, String> metadata = raw.getMetadata();
Preconditions.checkArgument(metadata.containsKey(DatasetConstants.FS_SCHEME),
String.format("Hive Dataset Descriptor must contain metadata %s to create Hdfs Dataset Descriptor",
DatasetConstants.FS_SCHEME));
Preconditions.checkArgument(metadata.containsKey(DatasetConstants.FS_SCHEME),
String.format("Hive Dataset Descriptor must contain metadata %s to create Hdfs Dataset Descriptor",
DatasetConstants.FS_LOCATION));
DatasetDescriptor datasetDescriptor =
new DatasetDescriptor(metadata.get(DatasetConstants.FS_SCHEME), metadata.get(DatasetConstants.FS_LOCATION));
datasetDescriptor.addMetadata(HIVE_TABLE, raw.getName());
return datasetDescriptor;
}
}
| 2,038 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/HiveToHdfsDatasetResolverFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import com.typesafe.config.Config;
public class HiveToHdfsDatasetResolverFactory implements DatasetResolverFactory {
@Override
public DatasetResolver createResolver(Config config) {
return HiveToHdfsDatasetResolver.INSTANCE;
}
}
| 2,039 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/IterableDatasetFinderImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.io.IOException;
import java.util.Iterator;
import lombok.AllArgsConstructor;
import lombok.experimental.Delegate;
/**
* Wraps a {@link DatasetsFinder} into an {@link IterableDatasetFinder}.
*/
@AllArgsConstructor
public class IterableDatasetFinderImpl<T extends Dataset> implements IterableDatasetFinder<T> {
@Delegate
private final DatasetsFinder<T> datasetFinder;
@Override
public Iterator<T> getDatasetsIterator()
throws IOException {
return this.datasetFinder.findDatasets().iterator();
}
}
| 2,040 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/Descriptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.gobblin.util.io.GsonInterfaceAdapter;
/**
* A descriptor is a simplified representation of a resource, which could be a dataset, dataset partition, file, etc.
* It is a digest or abstract, which contains identification properties of the actual resource object, such as ID, name
* primary keys, version, etc
*
* <p>
* When the original object has complicated inner structure and there is a requirement to send it over the wire,
* it's a time to define a corresponding {@link Descriptor} becomes. In this case, the {@link Descriptor} can just
* have minimal information enough to construct the original object on the other side of the wire
* </p>
*
* <p>
* When the cost to instantiate the complete original object is high, for example, network calls are required, but
* the use cases are limited to the identification properties, define a corresponding {@link Descriptor} becomes
* handy
* </p>
*/
@RequiredArgsConstructor
public class Descriptor {
/** Use gson for ser/de */
public static final Gson GSON =
new GsonBuilder().registerTypeAdapterFactory(new GsonInterfaceAdapter(Descriptor.class)).create();
/** Type token for ser/de descriptor list */
private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken<ArrayList<Descriptor>>(){}.getType();
/** Name of the resource */
@Getter
private final String name;
@Override
public String toString() {
return GSON.toJson(this);
}
public Descriptor copy() {
return new Descriptor(name);
}
/**
* Serialize any {@link Descriptor} object as json string
*
* <p>
* Note: it can serialize subclasses
* </p>
*/
public static String toJson(Descriptor descriptor) {
return GSON.toJson(descriptor);
}
/**
* Deserialize the json string to the a {@link Descriptor} object
*/
public static Descriptor fromJson(String json) {
return fromJson(json, Descriptor.class);
}
/**
* Deserialize the json string to the specified {@link Descriptor} object
*/
public static <T extends Descriptor> T fromJson(String json, Class<T> clazz) {
return GSON.fromJson(json, clazz);
}
/**
* Serialize a list of descriptors as json string
*/
public static String toJson(List<Descriptor> descriptors) {
return GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE);
}
/**
* Deserialize the string, resulted from {@link #toJson(List)}, to a list of descriptors
*/
public static List<Descriptor> fromJsonList(String jsonList) {
return GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE);
}
}
| 2,041 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetsFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.fs.Path;
/**
* Finds {@link Dataset}s in the file system.
*
* <p>
* Concrete subclasses should have a constructor with signature
* ({@link org.apache.hadoop.fs.FileSystem}, {@link java.util.Properties}).
* </p>
*/
public interface DatasetsFinder<T extends Dataset> {
/**
* Find all {@link Dataset}s in the file system.
* @return List of {@link Dataset}s in the file system.
* @throws IOException
*/
public List<T> findDatasets() throws IOException;
/**
* @return The deepest common root shared by all {@link Dataset}s root paths returned by this finder.
*/
@Deprecated
public Path commonDatasetRoot();
}
| 2,042 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetResolverFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import com.typesafe.config.Config;
/**
* A factory that creates an instance of {@link DatasetResolver}
*
* @deprecated use {@link DescriptorResolverFactory} as {@link DatasetResolver} is deprecated
* with {@link DescriptorResolver}
*/
@Deprecated
public interface DatasetResolverFactory extends DescriptorResolverFactory {
/**
* Create a {@link DatasetResolver} instance
*/
DatasetResolver createResolver(Config config);
}
| 2,043 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import org.apache.gobblin.configuration.State;
/**
* A {@link DatasetResolver} resolves job specific dataset
*
* @deprecated use the more general {@link DescriptorResolver}
*/
@Deprecated
public interface DatasetResolver extends DescriptorResolver {
/**
* Given raw Gobblin dataset, resolve job specific dataset
*
* @param raw a dataset in terms of Gobblin
* @param state configuration that helps resolve job specific dataset
* @return resolved dataset for the job
*/
DatasetDescriptor resolve(DatasetDescriptor raw, State state);
@Override
default Descriptor resolve(Descriptor raw, State state) {
DatasetDescriptor rawDataset;
if (raw instanceof DatasetDescriptor) {
rawDataset = (DatasetDescriptor) raw;
} else if (raw instanceof PartitionDescriptor) {
rawDataset = ((PartitionDescriptor) raw).getDataset();
} else {
// type not supported
return null;
}
return resolve(rawDataset, state);
}
}
| 2,044 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/URNIdentified.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
/**
* An object that can be identified by URN.
* Note the contract is that given o1, o2, then o1.equals(o2) iff o1.class.equals(o2.class) and o1.getUrn().equals(o2.getUrn())
*/
public interface URNIdentified {
/**
* URN for this object.
*/
public String getUrn();
}
| 2,045 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionDescriptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
/**
* A {@link Descriptor} to identifies a partition of a dataset
*/
public class PartitionDescriptor extends Descriptor {
/** Type token for ser/de partition descriptor list */
private static final Type DESCRIPTOR_LIST_TYPE = new TypeToken<ArrayList<PartitionDescriptor>>(){}.getType();
@Getter
private final DatasetDescriptor dataset;
public PartitionDescriptor(String name, DatasetDescriptor dataset) {
super(name);
this.dataset = dataset;
}
@Override
public PartitionDescriptor copy() {
return new PartitionDescriptor(getName(), dataset);
}
public PartitionDescriptor copyWithNewDataset(DatasetDescriptor dataset) {
return new PartitionDescriptor(getName(), dataset);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PartitionDescriptor that = (PartitionDescriptor) o;
return dataset.equals(that.dataset) && getName().equals(that.getName());
}
@Override
public int hashCode() {
int result = dataset.hashCode();
result = 31 * result + getName().hashCode();
return result;
}
/**
* Serialize a list of partition descriptors as json string
*/
public static String toPartitionJsonList(List<PartitionDescriptor> descriptors) {
return Descriptor.GSON.toJson(descriptors, DESCRIPTOR_LIST_TYPE);
}
/**
* Deserialize the string, resulted from {@link #toPartitionJsonList(List)}, to a list of partition descriptors
*/
public static List<PartitionDescriptor> fromPartitionJsonList(String jsonList) {
return Descriptor.GSON.fromJson(jsonList, DESCRIPTOR_LIST_TYPE);
}
}
| 2,046 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/IterableDatasetFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* A {@link DatasetsFinder} that can return the {@link Dataset}s as an {@link Iterator}. This allows {@link Dataset}s
* to be created on demand instead of all at once, possibly reducing memory usage and improving performance.
*/
public interface IterableDatasetFinder<T extends Dataset> extends DatasetsFinder<T> {
/**
* @return An {@link Iterator} over the {@link Dataset}s found.
* @throws IOException
* @deprecated use {@link #getDatasetsStream} instead.
*/
@Deprecated
public Iterator<T> getDatasetsIterator() throws IOException;
/**
* Get a stream of {@link Dataset}s found.
* @param desiredCharacteristics desired {@link java.util.Spliterator} characteristics of this stream. The returned
* stream need not satisfy these characteristics, this argument merely implies that the
* caller will run optimally when those characteristics are present, allowing pushdown of
* those characteristics. For example {@link java.util.Spliterator#SORTED} can sometimes
* be pushed down at a cost, so the {@link DatasetsFinder} would only push it down if it is valuable
* for the caller.
* @param suggestedOrder suggested order of the datasets in the stream. Implementation may or may not return the entries
* in that order. If the entries are in that order, implementation should ensure the spliterator
* is annotated as such.
* @return a stream of {@link Dataset}s found.
* @throws IOException
*/
default Stream<T> getDatasetsStream(int desiredCharacteristics, Comparator<T> suggestedOrder) throws IOException {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(getDatasetsIterator(), 0), false);
}
}
| 2,047 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetDescriptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nullable;
import lombok.Getter;
/**
* A {@link Descriptor} identifies and provides metadata to describe a dataset
*/
public class DatasetDescriptor extends Descriptor {
private static final String PLATFORM_KEY = "platform";
private static final String NAME_KEY = "name";
private static final String STORAGE_URL = "storageUrl";
/**
* which platform the dataset is stored, for example: local, hdfs, oracle, mysql, kafka
*/
@Getter
private final String platform;
/**
* URL of system that stores the dataset. It does not include the dataset name.
*
* Examples: hdfs://storage.corp.com, https://api.service.test, mysql://mysql-db.test:3306, thrift://hive-server:4567
*
* Using URI instead of URL class to allow for schemas that are not known by URL class
* (https://stackoverflow.com/q/2406518/258737)
*/
@Getter
@Nullable
private final URI storageUrl;
/**
* metadata about the dataset
*/
private final Map<String, String> metadata = Maps.newHashMap();
/**
* @deprecated use {@link #DatasetDescriptor(String, URI, String)} to provide storage system url.
*/
@Deprecated
public DatasetDescriptor(String platform, String name) {
super(name);
this.storageUrl = null;
this.platform = platform;
}
public DatasetDescriptor(String platform, URI storageUrl, String name) {
super(name);
this.storageUrl = storageUrl;
this.platform = platform;
}
/**
* @deprecated use {@link #copy()}
*/
@Deprecated
public DatasetDescriptor(DatasetDescriptor copy) {
super(copy.getName());
platform = copy.getPlatform();
storageUrl = copy.getStorageUrl();
metadata.putAll(copy.getMetadata());
}
/**
* Deserialize a {@link DatasetDescriptor} from a string map
*
* @deprecated use {@link Descriptor#deserialize(String)}
*/
@Deprecated
public static DatasetDescriptor fromDataMap(Map<String, String> dataMap) {
String storageUrlString = dataMap.getOrDefault(STORAGE_URL, null);
URI storageUrl = null;
if (storageUrlString != null) {
storageUrl = URI.create(storageUrlString);
}
DatasetDescriptor descriptor =
new DatasetDescriptor(dataMap.get(PLATFORM_KEY), storageUrl, dataMap.get(NAME_KEY));
dataMap.forEach((key, value) -> {
if (!key.equals(PLATFORM_KEY) && !key.equals(NAME_KEY) && !key.equals(STORAGE_URL)) {
descriptor.addMetadata(key, value);
}
});
return descriptor;
}
public ImmutableMap<String, String> getMetadata() {
return ImmutableMap.<String, String>builder().putAll(metadata).build();
}
@Override
public DatasetDescriptor copy() {
return new DatasetDescriptor(this);
}
public void addMetadata(String key, String value) {
metadata.put(key, value);
}
/**
* Serialize to a string map
*
* @deprecated use {@link Descriptor#serialize(Descriptor)}
*/
@Deprecated
public Map<String, String> toDataMap() {
Map<String, String> map = Maps.newHashMap();
map.put(PLATFORM_KEY, platform);
map.put(NAME_KEY, getName());
if (getStorageUrl() != null) {
map.put(STORAGE_URL, getStorageUrl().toString());
}
map.putAll(metadata);
return map;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DatasetDescriptor that = (DatasetDescriptor) o;
return platform.equals(that.platform) && Objects.equals(storageUrl, that.storageUrl)
&& metadata.equals(that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(platform, storageUrl, metadata);
}
}
| 2,048 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/PartitionableDataset.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import java.io.IOException;
import java.util.Comparator;
import java.util.stream.Stream;
/**
* A {@link Dataset} that can be partitioned into disjoint subsets of the dataset.
* @param <T> the type of partitions returned by the dataset.
*/
public interface PartitionableDataset<T extends PartitionableDataset.DatasetPartition> extends Dataset {
/**
* Get a stream of partitions.
* @param desiredCharacteristics desired {@link java.util.Spliterator} characteristics of this stream. The returned
* stream need not satisfy these characteristics, this argument merely implies that the
* caller will run optimally when those characteristics are present, allowing pushdown of
* those characteristics. For example {@link java.util.Spliterator#SORTED} can sometimes
* be pushed down at a cost, so the {@link Dataset} would only push it down if it is valuable
* for the caller.
* @param suggestedOrder suggested order of the partitions in the stream. Implementation may or may not return the entries
* in that order. If the entries are in that order, implementation should ensure the spliterator
* is annotated as such.
* @return a {@link Stream} over {@link DatasetPartition}s in this dataset.
*/
Stream<T> getPartitions(int desiredCharacteristics, Comparator<T> suggestedOrder) throws IOException;
/**
* A partition of a {@link PartitionableDataset}.
*/
interface DatasetPartition extends URNIdentified {
/**
* URN for this dataset.
*/
String getUrn();
/**
* @return Dataset this partition belongs to.
*/
Dataset getDataset();
}
}
| 2,049 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DatasetConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
public class DatasetConstants {
/** Platforms */
public static final String PLATFORM_FILE = "file";
public static final String PLATFORM_HDFS = "hdfs";
public static final String PLATFORM_KAFKA = "kafka";
public static final String PLATFORM_HIVE = "hive";
public static final String PLATFORM_SALESFORCE = "salesforce";
public static final String PLATFORM_MYSQL = "mysql";
public static final String PLATFORM_ICEBERG = "iceberg";
/** Common metadata */
public static final String BRANCH = "branch";
/** File system metadata */
public static final String FS_URI = "fsUri";
/** Kafka metadata */
public static final String BROKERS = "brokers";
/** JDBC metadata */
public static final String CONNECTION_URL = "connectionUrl";
/** FileSystem scheme and location */
public static final String FS_SCHEME = "fsScheme";
public static final String FS_LOCATION = "fsLocation";
}
| 2,050 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/FileSystemDataset.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import org.apache.hadoop.fs.Path;
/**
* {@link Dataset} in a file system, which can be characterized by a root {@link Path}.
*/
public interface FileSystemDataset extends Dataset {
public Path datasetRoot();
/**
* @return true if the dataset doesn't have a physical file/folder
*/
default boolean isVirtual() {
return false;
}
}
| 2,051 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/NoopDatasetResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import org.apache.gobblin.configuration.State;
/**
* The default {@link DatasetResolver} that directly uses Gobblin raw dataset as job dataset
*/
public class NoopDatasetResolver implements DatasetResolver {
public static final NoopDatasetResolver INSTANCE = new NoopDatasetResolver();
public static final String FACTORY = "NOOP";
private NoopDatasetResolver() {}
@Override
public DatasetDescriptor resolve(DatasetDescriptor raw, State state) {
return raw;
}
@Override
public Descriptor resolve(Descriptor raw, State state) {
return raw;
}
}
| 2,052 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/DescriptorResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset;
import org.apache.gobblin.configuration.State;
/**
* A resolver transforms an existing {@link Descriptor} to a new one
*/
public interface DescriptorResolver {
/**
* Given raw Gobblin descriptor, resolve a job specific descriptor
*
* @param raw the original descriptor
* @param state configuration that helps resolve job specific descriptor
* @return resolved descriptor for the job or {@code null} if failed to resolve
*/
Descriptor resolve(Descriptor raw, State state);
}
| 2,053 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/test/SimpleDatasetPartitionForTesting.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset.test;
import org.apache.gobblin.dataset.Dataset;
import org.apache.gobblin.dataset.PartitionableDataset;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* A dumb {@link org.apache.gobblin.dataset.PartitionableDataset.DatasetPartition} used for testing.
*/
@Data
@EqualsAndHashCode
public class SimpleDatasetPartitionForTesting implements PartitionableDataset.DatasetPartition {
private final String urn;
private Dataset dataset;
}
| 2,054 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/test/StaticDatasetsFinderForTesting.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset.test;
import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.apache.gobblin.dataset.Dataset;
import org.apache.gobblin.dataset.IterableDatasetFinder;
import org.apache.hadoop.fs.Path;
import lombok.AllArgsConstructor;
/**
* A {@link org.apache.gobblin.dataset.DatasetsFinder} that returns a predefined set of {@link Dataset}s for testing.
*/
@AllArgsConstructor
public class StaticDatasetsFinderForTesting implements IterableDatasetFinder<Dataset> {
private final List<Dataset> datasets;
@Override
public List<Dataset> findDatasets() throws IOException {
return this.datasets;
}
@Override
public Path commonDatasetRoot() {
return null;
}
@Override
public Iterator<Dataset> getDatasetsIterator() throws IOException {
return this.datasets.iterator();
}
@Override
public Stream<Dataset> getDatasetsStream(int desiredCharacteristics, Comparator<Dataset> suggestedOrder)
throws IOException {
return this.datasets.stream();
}
}
| 2,055 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/test/SimplePartitionableDatasetForTesting.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset.test;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
import org.apache.gobblin.dataset.PartitionableDataset;
import lombok.EqualsAndHashCode;
/**
* A {@link PartitionableDataset} that just returns a predefined set of {@link SimpleDatasetPartitionForTesting} used for testing.
*/
@EqualsAndHashCode
public class SimplePartitionableDatasetForTesting implements PartitionableDataset<SimpleDatasetPartitionForTesting> {
private final String urn;
private final List<SimpleDatasetPartitionForTesting> partitions;
public SimplePartitionableDatasetForTesting(String urn, List<SimpleDatasetPartitionForTesting> partitions) {
this.urn = urn;
this.partitions = partitions;
for (SimpleDatasetPartitionForTesting partition : this.partitions) {
partition.setDataset(this);
}
}
@Override
public String datasetURN() {
return this.urn;
}
@Override
public Stream<SimpleDatasetPartitionForTesting> getPartitions(int desiredCharacteristics,
Comparator<SimpleDatasetPartitionForTesting> suggestedOrder) throws IOException {
return this.partitions.stream();
}
}
| 2,056 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/test/SimpleDatasetForTesting.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset.test;
import org.apache.gobblin.dataset.Dataset;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
/**
* A dumb {@link Dataset} used for testing.
*/
@AllArgsConstructor
@EqualsAndHashCode
public class SimpleDatasetForTesting implements Dataset {
private final String urn;
@Override
public String datasetURN() {
return this.urn;
}
}
| 2,057 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/comparators/URNLexicographicalComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.dataset.comparators;
import java.io.Serializable;
import java.util.Comparator;
import org.apache.gobblin.dataset.URNIdentified;
import lombok.EqualsAndHashCode;
/**
* Dataset comparator that compares by dataset urn.
*/
@EqualsAndHashCode
public class URNLexicographicalComparator implements Comparator<URNIdentified>, Serializable {
private static final long serialVersionUID = 2647543651352156568L;
@Override
public int compare(URNIdentified o1, URNIdentified o2) {
return o1.getUrn().compareTo(o2.getUrn());
}
/**
* Compare against a raw URN.
*/
public int compare(URNIdentified o1, String urn2) {
return o1.getUrn().compareTo(urn2);
}
/**
* Compare against a raw URN.
*/
public int compare(String urn1, URNIdentified o2) {
return urn1.compareTo(o2.getUrn());
}
}
| 2,058 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/dataset/comparators/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 common dataset orders that {@link org.apache.gobblin.dataset.DatasetsFinder}s can push down.
*/
package org.apache.gobblin.dataset.comparators;
| 2,059 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/codec/StreamCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.codec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.gobblin.annotation.Alpha;
/**
* Interface for an object that can encrypt a bytestream.
*/
@Alpha
public interface StreamCodec {
/**
* Wrap a bytestream and return a new stream that encodes the bytes written to it and writes
* the result into origStream
* @param origStream Stream to wrap
* @return A wrapped stream for encoding
*/
OutputStream encodeOutputStream(OutputStream origStream) throws IOException;
/**
* Wrap a bytestream and return a new stream that will decode
* any bytes from origStream when read from.
* @param origStream Stream to wrap
* @return A wrapped stream for decoding
*/
InputStream decodeInputStream(InputStream origStream) throws IOException;
/**
* Get tag/file extension associated with encoder. This may be added to
* the file extension or other metadata by various writers in the system.
*/
String getTag();
}
| 2,060 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/FlushControlMessage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
/**
* Control message for flushing writers
* @param <D>
*/
@AllArgsConstructor(access= AccessLevel.PRIVATE)
@EqualsAndHashCode
@Builder
public class FlushControlMessage<D> extends ControlMessage<D> {
@Getter
private final String flushReason;
@Getter
private final FlushType flushType;
@Override
protected StreamEntity<D> buildClone() {
return FlushControlMessage.<D>builder().flushReason(this.flushReason).flushType(this.flushType).build();
}
@AllArgsConstructor
public enum FlushType {
FlUSH,
FLUSH_AND_CLOSE /* use this type to request a close after flush */
}
} | 2,061 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/StreamEntity.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import java.io.Closeable;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.gobblin.ack.Ackable;
import org.apache.gobblin.ack.HierarchicalAckable;
/**
* An entity in the Gobblin ingestion stream.
*
* Note:
* When transforming or cloning a stream entity, it is important to construct the new entity in the correct way to ensure callbacks
* are spread correctly:
*
* 1-to-1 entity transformation constructor:
* super(upstreamEntity, true);
*
* 1-to-n entity transformation:
* ForkedEntityBuilder forkedEntityBuilder = new ForkedEntityBuilder();
*
* super(forkedEntityBuilder, true);
*
* forkedEntityBuilder.close();
*
* Cloning entity:
* ForkCloner forkCloner = record.forkCloner();
* forkCloner.getClone();
* forkCloner.close();
*
* @param <D> the type of records represented in the stream.
*/
public abstract class StreamEntity<D> implements Ackable {
private final List<Ackable> _callbacks;
private boolean _callbacksUsedForDerivedEntity = false;
protected StreamEntity() {
_callbacks = Lists.newArrayList();
}
protected StreamEntity(StreamEntity<?> upstreamEntity, boolean copyCallbacks) {
if (copyCallbacks) {
_callbacks = upstreamEntity.getCallbacksForDerivedEntity();
} else {
_callbacks = Lists.newArrayList();
}
}
protected StreamEntity(ForkedEntityBuilder forkedEntityBuilder, boolean copyCallbacks) {
if (copyCallbacks) {
_callbacks = forkedEntityBuilder.getChildCallback();
} else {
_callbacks = Lists.newArrayList();
}
}
@Override
public void ack() {
for (Ackable ackable : _callbacks) {
ackable.ack();
}
}
@Override
public void nack(Throwable error) {
for (Ackable ackable : _callbacks) {
ackable.nack(error);
}
}
private synchronized List<Ackable> getCallbacksForDerivedEntity() {
Preconditions.checkState(!_callbacksUsedForDerivedEntity,
"StreamEntity was attempted to use more than once for a derived entity.");
_callbacksUsedForDerivedEntity = true;
return _callbacks;
}
public StreamEntity<D> addCallBack(Ackable ackable) {
_callbacks.add(ackable);
return this;
}
private void setCallbacks(List<Ackable> callbacks) {
_callbacks.addAll(callbacks);
}
/**
* @return a clone of this {@link StreamEntity}.
*/
public final StreamEntity<D> getSingleClone() {
StreamEntity<D> entity = buildClone();
entity.setCallbacks(getCallbacksForDerivedEntity());
return entity;
}
/**
* @return a clone of this {@link StreamEntity}. Implementations need not worry about the callbacks, they will be set
* automatically.
*/
protected abstract StreamEntity<D> buildClone();
/**
* @return a {@link ForkCloner} to generate multiple clones of this {@link StreamEntity}.
*/
public ForkCloner forkCloner() {
return new ForkCloner();
}
/**
* Used to clone a {@link StreamEntity} retaining the correct callbacks.
*/
public class ForkCloner implements Closeable {
private final ForkedEntityBuilder _forkedEntityBuilder = new ForkedEntityBuilder();
private ForkCloner() {
}
public StreamEntity<D> getClone() {
StreamEntity<D> entity = buildClone();
entity.setCallbacks(_forkedEntityBuilder.getChildCallback());
return entity;
}
@Override
public void close() {
_forkedEntityBuilder.close();
}
}
/**
* Used to generate derived {@link StreamEntity}s using a {@link HierarchicalAckable} to make sure parent ackable
* is automatically acked when all children are acked.
*/
public class ForkedEntityBuilder implements Closeable {
private final HierarchicalAckable _hierarchicalAckable;
protected ForkedEntityBuilder() {
List<Ackable> callbacks = getCallbacksForDerivedEntity();
_hierarchicalAckable = callbacks.isEmpty() ? null : new HierarchicalAckable(callbacks);
}
protected List<Ackable> getChildCallback() {
return _hierarchicalAckable == null ? Lists.newArrayList() : Lists.newArrayList(_hierarchicalAckable.newChildAckable());
}
@Override
public void close() {
if (_hierarchicalAckable != null) {
_hierarchicalAckable.close();
}
}
}
}
| 2,062 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/FlushRecordEnvelope.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
public class FlushRecordEnvelope extends RecordEnvelope {
public FlushRecordEnvelope() {
super(null);
}
}
| 2,063 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/WorkUnitChangeEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import java.util.List;
import lombok.Getter;
import org.apache.gobblin.source.workunit.WorkUnit;
/**
* The event for {@link org.apache.gobblin.source.InfiniteSource} to indicate there is a change in work units
* Job launcher should then be able to handle this event
*/
public class WorkUnitChangeEvent {
@Getter
private final List<String> oldTaskIds;
@Getter
private final List<WorkUnit> newWorkUnits;
public WorkUnitChangeEvent(List<String> oldTaskIds, List<WorkUnit> newWorkUnits) {
this.oldTaskIds = oldTaskIds;
this.newWorkUnits = newWorkUnits;
}
}
| 2,064 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/RecordEnvelope.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import java.util.HashMap;
import java.util.Map;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.fork.CopyHelper;
import org.apache.gobblin.fork.CopyNotSupportedException;
import org.apache.gobblin.source.extractor.CheckpointableWatermark;
import javax.annotation.Nullable;
/**
* An envelope around a record containing metadata and allowing for ack'ing the record.
*
* Note:
* When transforming or cloning a record, it is important to do it in the correct way to ensure callbacks and watermarks
* are spread correctly:
*
* 1-to-1 record transformation:
* record.withRecord(transformedRecord);
*
* 1-to-n record transformation:
* ForkRecordBuilder forkRecordBuilder = record.forkRecordBuilder();
* forkRecordBuilder.childRecord(transformed1);
* forkRecordBuilder.childRecord(transformed2);
* forkRecordBuilder.close();
*
* Cloning record:
* ForkCloner forkCloner = record.forkCloner();
* forkCloner.getClone();
* forkCloner.close();
*/
@Alpha
public class RecordEnvelope<D> extends StreamEntity<D> {
private final D _record;
@Nullable
private final CheckpointableWatermark _watermark;
/**
* The container is lazily created when the first entry is set. Copies of the {@link RecordEnvelope} will copy the
* top-level entries into a new container, but the values will not be cloned. So adding new entries has no effect on
* copies, but values should not be modified in-place if the intention is to not affect the copies.
*/
private Map<String, Object> _recordMetadata;
public RecordEnvelope(D record) {
this(record, (CheckpointableWatermark) null);
}
private RecordEnvelope(D record, RecordEnvelope<?> parentRecord, boolean copyCallbacks) {
super(parentRecord, copyCallbacks);
_record = record;
_watermark = parentRecord._watermark;
if (parentRecord._recordMetadata != null) {
_recordMetadata = new HashMap<>();
_recordMetadata.putAll(parentRecord._recordMetadata);
}
}
private RecordEnvelope(D record, RecordEnvelope<?>.ForkRecordBuilder<D> forkRecordBuilder, boolean copyCallbacks) {
super(forkRecordBuilder, copyCallbacks);
_record = record;
_watermark = forkRecordBuilder.getRecordEnvelope()._watermark;
if (forkRecordBuilder.getRecordEnvelope()._recordMetadata != null) {
_recordMetadata = new HashMap<>();
_recordMetadata.putAll(forkRecordBuilder.getRecordEnvelope()._recordMetadata);
}
}
public RecordEnvelope(D record, CheckpointableWatermark watermark) {
super();
if (record instanceof RecordEnvelope) {
throw new IllegalStateException("Cannot wrap a RecordEnvelope in another RecordEnvelope.");
}
_record = record;
_watermark = watermark;
_recordMetadata = null;
}
/**
* @return a new {@link RecordEnvelope} with just the record changed.
*/
public <DO> RecordEnvelope<DO> withRecord(DO newRecord) {
return new RecordEnvelope<>(newRecord, this, true);
}
/**
* @return the record contained.
*/
public D getRecord() {
return _record;
}
/**
* @return The watermark for this record.
*/
@Nullable public CheckpointableWatermark getWatermark() {
return _watermark;
}
/**
* @return The record metadata with the given key or null if not present
*/
public Object getRecordMetadata(String key) {
if (_recordMetadata != null) {
return _recordMetadata.get(key);
}
return null;
}
/**
* Set the record metadata
* @param key key for the metadata
* @param value value of the metadata
*
* @implNote should not be called concurrently
*/
public void setRecordMetadata(String key, Object value) {
if (_recordMetadata == null) {
_recordMetadata = new HashMap<>();
}
_recordMetadata.put(key, value);
}
@Override
protected StreamEntity<D> buildClone() {
try {
return new RecordEnvelope<>((D) CopyHelper.copy(_record), this, false);
} catch (CopyNotSupportedException cnse) {
throw new UnsupportedOperationException(cnse);
}
}
/**
* Obtain a {@link ForkRecordBuilder} to create derivative records to this record.
*/
public <DO> ForkRecordBuilder<DO> forkRecordBuilder() {
return new ForkRecordBuilder<>();
}
/**
* Used to create derivative records with the same callbacks and watermarks.
*/
public class ForkRecordBuilder<DO> extends StreamEntity.ForkedEntityBuilder {
private ForkRecordBuilder() {
}
/**
* Create a new child {@link RecordEnvelope} with the specified record.
*/
public RecordEnvelope<DO> childRecord(DO newRecord) {
return new RecordEnvelope<>(newRecord, this, true);
}
RecordEnvelope<D> getRecordEnvelope() {
return RecordEnvelope.this;
}
}
}
| 2,065 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/ControlMessageInjector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import java.io.Closeable;
import java.io.IOException;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metadata.GlobalMetadata;
import org.apache.gobblin.records.ControlMessageHandler;
import org.apache.gobblin.records.RecordStreamProcessor;
import org.apache.gobblin.records.RecordStreamWithMetadata;
import io.reactivex.Flowable;
/**
* A {@link RecordStreamProcessor} that inspects an input record and outputs control messages before, after, or around
* the input record
* @param <SI>
* @param <DI>
*/
public abstract class ControlMessageInjector<SI, DI> implements Closeable,
RecordStreamProcessor<SI, SI, DI, DI> {
/**
* Initialize this {@link ControlMessageInjector}.
*
* @param workUnitState a {@link WorkUnitState} object carrying configuration properties
* @return an initialized {@link ControlMessageInjector} instance
*/
protected ControlMessageInjector<SI, DI> init(WorkUnitState workUnitState) {
return this;
}
@Override
public void close() throws IOException {
}
/**
* Set the global metadata of the input messages. The base implementation is empty and should be overridden by
* the subclasses that need to store the input {@link GlobalMetadata}
* @param inputGlobalMetadata the global metadata for input messages
* @param workUnitState
*/
protected void setInputGlobalMetadata(GlobalMetadata<SI> inputGlobalMetadata, WorkUnitState workUnitState) {
}
/**
* Inject {@link ControlMessage}s before the record
* @param inputRecordEnvelope
* @param workUnitState
* @return The {@link ControlMessage}s to inject before the record
*/
protected abstract Iterable<ControlMessage<DI>> injectControlMessagesBefore(RecordEnvelope<DI> inputRecordEnvelope,
WorkUnitState workUnitState);
/**
* Inject {@link ControlMessage}s after the record
* @param inputRecordEnvelope
* @param workUnitState
* @return The {@link ControlMessage}s to inject after the record
*/
protected abstract Iterable<ControlMessage<DI>> injectControlMessagesAfter(RecordEnvelope<DI> inputRecordEnvelope,
WorkUnitState workUnitState);
/**
* Apply injections to the input {@link RecordStreamWithMetadata}.
* {@link ControlMessage}s may be injected before, after, or around the input record.
* A {@link MetadataUpdateControlMessage} will update the current input {@link GlobalMetadata} and pass the
* updated input {@link GlobalMetadata} to the next processor to propagate the metadata update down the pipeline.
*/
@Override
public RecordStreamWithMetadata<DI, SI> processStream(RecordStreamWithMetadata<DI, SI> inputStream,
WorkUnitState workUnitState) throws StreamProcessingException {
init(workUnitState);
setInputGlobalMetadata(inputStream.getGlobalMetadata(), workUnitState);
Flowable<StreamEntity<DI>> outputStream =
inputStream.getRecordStream()
.flatMap(in -> {
if (in instanceof ControlMessage) {
if (in instanceof MetadataUpdateControlMessage) {
setInputGlobalMetadata(((MetadataUpdateControlMessage) in).getGlobalMetadata(), workUnitState);
}
getMessageHandler().handleMessage((ControlMessage) in);
return Flowable.just(in);
} else if (in instanceof RecordEnvelope) {
RecordEnvelope<DI> recordEnvelope = (RecordEnvelope<DI>) in;
Iterable<ControlMessage<DI>> injectedBeforeIterable =
injectControlMessagesBefore(recordEnvelope, workUnitState);
Iterable<ControlMessage<DI>> injectedAfterIterable =
injectControlMessagesAfter(recordEnvelope, workUnitState);
if (injectedBeforeIterable == null && injectedAfterIterable == null) {
// nothing injected so return the record envelope
return Flowable.just(recordEnvelope);
} else {
Flowable<StreamEntity<DI>> flowable;
if (injectedBeforeIterable != null) {
flowable = Flowable.<StreamEntity<DI>>fromIterable(injectedBeforeIterable)
.concatWith(Flowable.just(recordEnvelope));
} else {
flowable = Flowable.just(recordEnvelope);
}
if (injectedAfterIterable != null) {
flowable.concatWith(Flowable.fromIterable(injectedAfterIterable));
}
return flowable;
}
} else {
throw new UnsupportedOperationException();
}
}, 1);
outputStream = outputStream.doOnComplete(this::close);
return inputStream.withRecordStream(outputStream, inputStream.getGlobalMetadata());
}
/**
* @return {@link ControlMessageHandler} to call for each {@link ControlMessage} received.
*/
protected ControlMessageHandler getMessageHandler() {
return ControlMessageHandler.NOOP;
}
}
| 2,066 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/ControlMessage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
/**
* A {@link StreamEntity} used to send control messages through the ingestion pipeline. Most constructs will just
* forward control messages as is. Specific constructs may react to the control message to trigger actions.
* @param <D>
*/
public abstract class ControlMessage<D> extends StreamEntity<D> {
public ControlMessage() {
super();
}
}
| 2,067 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/stream/MetadataUpdateControlMessage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.stream;
import org.apache.gobblin.metadata.GlobalMetadata;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
/**
* Control message for updating the {@link GlobalMetadata} used for processing records
* @param <S> schema type
* @param <D> data type
*/
@AllArgsConstructor
@EqualsAndHashCode
public class MetadataUpdateControlMessage<S, D> extends ControlMessage<D> {
@Getter
private GlobalMetadata<S> globalMetadata;
@Override
protected StreamEntity<D> buildClone() {
return new MetadataUpdateControlMessage(this.globalMetadata);
}
} | 2,068 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/InfiniteSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source;
import com.google.common.eventbus.EventBus;
import org.apache.gobblin.annotation.Alpha;
/**
* An interface for infinite source, where source should be able to detect the work unit change
* and post the change through eventBus
*
* @author Zihan Li
*
* @param <S> output schema type
* @param <D> output record type
*/
@Alpha
public interface InfiniteSource<S, D> extends Source<S, D>{
/**
* Return the eventBus where it will post {@link org.apache.gobblin.stream.WorkUnitChangeEvent} when workUnit change
*/
EventBus getEventBus();
}
| 2,069 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/Source.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.configuration.WorkUnitState;
import java.io.IOException;
import java.util.List;
import org.apache.gobblin.source.extractor.Extractor;
import org.apache.gobblin.source.workunit.WorkUnit;
/**
* An interface for classes that the end users implement to work with a data source from which
* schema and data records can be extracted.
*
* <p>
* An implementation of this interface should contain all the logic required to work with a
* specific data source. This usually includes work determination and partitioning, and details
* of the connection protocol to work with the data source.
* </p>
*
* @author kgoodhop
*
* @param <S> output schema type
* @param <D> output record type
*/
public interface Source<S, D> {
/**
* Get a list of {@link WorkUnit}s, each of which is for extracting a portion of the data.
*
* <p>
* Each {@link WorkUnit} will be used instantiate a {@link org.apache.gobblin.configuration.WorkUnitState} that gets passed to the
* {@link #getExtractor(org.apache.gobblin.configuration.WorkUnitState)} method to get an {@link Extractor} for extracting schema
* and data records from the source. The {@link WorkUnit} instance should have all the properties
* needed for the {@link Extractor} to work.
* </p>
*
* <p>
* Typically the list of {@link WorkUnit}s for the current run is determined by taking into account
* the list of {@link WorkUnit}s from the previous run so data gets extracted incrementally. The
* method {@link org.apache.gobblin.configuration.SourceState#getPreviousWorkUnitStates} can be used to get the list of {@link WorkUnit}s
* from the previous run.
* </p>
*
* @param state see {@link org.apache.gobblin.configuration.SourceState}
* @return a list of {@link WorkUnit}s
*/
public abstract List<WorkUnit> getWorkunits(SourceState state);
/**
* Get an {@link Extractor} based on a given {@link org.apache.gobblin.configuration.WorkUnitState}.
*
* <p>
* The {@link Extractor} returned can use {@link org.apache.gobblin.configuration.WorkUnitState} to store arbitrary key-value pairs
* that will be persisted to the state store and loaded in the next scheduled job run.
* </p>
*
* @param state a {@link org.apache.gobblin.configuration.WorkUnitState} carrying properties needed by the returned {@link Extractor}
* @return an {@link Extractor} used to extract schema and data records from the data source
* @throws IOException if it fails to create an {@link Extractor}
*/
public abstract Extractor<S, D> getExtractor(WorkUnitState state)
throws IOException;
/**
* Shutdown this {@link Source} instance.
*
* <p>
* This method is called once when the job completes. Properties (key-value pairs) added to the input
* {@link SourceState} instance will be persisted and available to the next scheduled job run through
* the method {@link #getWorkunits(SourceState)}. If there is no cleanup or reporting required for a
* particular implementation of this interface, then it is acceptable to have a default implementation
* of this method.
* </p>
*
* @param state see {@link SourceState}
*/
public abstract void shutdown(SourceState state);
/**
* Instead of handling all {@link WorkUnit}s in one run, some {@link Source} may choose to stop early in order to handle the
* proper workload, which can cause multiple runs after the initial run.
* @return If the same job has early stopped
*/
public default boolean isEarlyStopped() {
return false;
}
}
| 2,070 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/WorkUnitStreamSource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.source.workunit.WorkUnitStream;
/**
* A {@link Source} that produces a {@link WorkUnitStream}.
*
* Streamed sources may offer certain advantages over non-streamed sources if the job launcher supports them:
* * Low memory usage: If the {@link WorkUnitStream} is backed by a generator, the job launcher may optimize memory
* usage by never materializing all work units in memory.
* * Eager processing of slow sources: If the source is slow at producing work units, the job launcher may start
* processing available work units while future work units are still being computed.
* * Infinite work unit streams: in the future, some job launchers will support infinite streams of work units.
*/
public interface WorkUnitStreamSource<S, D> extends Source<S, D> {
/**
* Get the {@link WorkUnitStream} to process.
*/
WorkUnitStream getWorkunitStream(SourceState state);
}
| 2,071 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.configuration.WorkUnitState;
/**
* A class representing all the base attributes required by all tables types. Subclasses
* will be expected to validate each table type for their respective required attributes.
*
* <p>
* The extract ID only needs to be unique for {@link Extract}s belonging to the same
* namespace/table. One or more {@link WorkUnit}s can share the same extract ID.
* {@link WorkUnit}s that do share an extract ID will be considered parts of a single
* {@link Extract} for the purpose of applying publishing policies.
* </p>
*
* @author kgoodhop
*
*/
public class Extract extends State {
public enum TableType {
SNAPSHOT_ONLY,
SNAPSHOT_APPEND,
APPEND_ONLY
}
private final State previousTableState = new State();
/**
* Constructor.
*
* @param state a {@link SourceState} carrying properties needed to construct an {@link Extract}
* @param namespace dot separated namespace path
* @param type {@link TableType}
* @param table table name
*
* @deprecated Extract does not use any property in {@link SourceState}.
* Use {@link #Extract(TableType, String, String)}
*/
@Deprecated
public Extract(SourceState state, TableType type, String namespace, String table) {
// Values should only be null for deserialization
if (state != null && type != null && !Strings.isNullOrEmpty(namespace) && !Strings.isNullOrEmpty(table)) {
// Constructing DTF
DateTimeZone timeZone = getTimeZoneHelper(state);
DateTimeFormatter DTF = DateTimeFormat.forPattern("yyyyMMddHHmmss").withLocale(Locale.US).withZone(timeZone);
String extractId = DTF.print(new DateTime());
super.addAll(state);
super.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, type.toString());
super.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, namespace);
super.setProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, table);
super.setProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, extractId);
for (WorkUnitState pre : state.getPreviousWorkUnitStates()) {
Extract previousExtract = pre.getWorkunit().getExtract();
if (previousExtract.getNamespace().equals(namespace) && previousExtract.getTable().equals(table)) {
this.previousTableState.addAll(pre);
}
}
// Setting full drop date if not already specified, the value can still be overridden if required.
if (state.getPropAsBoolean(ConfigurationKeys.EXTRACT_IS_FULL_KEY)
&& !state.contains(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY)) {
super.setProp(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY, System.currentTimeMillis());
}
}
}
DateTimeZone getTimeZoneHelper(SourceState state) {
return DateTimeZone.forID(state.getProp(ConfigurationKeys.EXTRACT_ID_TIME_ZONE,
ConfigurationKeys.DEFAULT_EXTRACT_ID_TIME_ZONE));
}
/**
* Constructor.
*
* @param type {@link TableType}
* @param namespace dot separated namespace path
* @param table table name
*/
public Extract(TableType type, String namespace, String table) {
this(new SourceState(), type, namespace, table);
}
/**
* Deep copy constructor.
*
* @param extract the other {@link Extract} instance
*/
public Extract(Extract extract) {
super.addAll(extract.getProperties());
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Extract)) {
return false;
}
Extract other = (Extract) object;
return super.equals(other) && this.getNamespace().equals(other.getNamespace())
&& this.getTable().equals(other.getTable()) && this.getExtractId().equals(other.getExtractId());
}
@Override
public int hashCode() {
return (this.getNamespace() + this.getTable() + this.getExtractId()).hashCode();
}
/**
* Get the writer output file path corresponding to this {@link Extract}.
*
* @return writer output file path corresponding to this {@link Extract}
* @deprecated As {@code this.getIsFull} is deprecated.
*/
@Deprecated
public String getOutputFilePath() {
return this.getNamespace().replaceAll("\\.", "/") + "/" + this.getTable() + "/" + this.getExtractId() + "_"
+ (this.getIsFull() ? "full" : "append");
}
/**
* If this {@link Extract} has extract table type defined.
*
* @return <code>true</code> if it has, <code>false</code> otherwise.
*/
public boolean hasType() {
return contains(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY);
}
/**
* Get the {@link TableType} of the table.
*
* @return {@link TableType} of the table
*/
public TableType getType() {
return TableType.valueOf(getProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY));
}
/**
* Get the dot-separated namespace of the table.
*
* @return dot-separated namespace of the table
*/
public String getNamespace() {
return getProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, "");
}
/**
* Get the name of the table.
*
* @return name of the table
*/
public String getTable() {
return getProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, "");
}
/**
* Get a (non-globally) unique ID for this {@link Extract}.
*
* @return unique ID for this {@link Extract}
*/
public String getExtractId() {
return getProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, "");
}
/**
* Set a (non-globally) unique ID for this {@link Extract}.
*
* @param extractId unique ID for this {@link Extract}
*/
public void setExtractId(String extractId) {
setProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, extractId);
}
/**
* Check if this {@link Extract} represents the full contents of the source table.
*
* @return <code>true</code> if this {@link Extract} represents the full contents
* of the source table and <code>false</code> otherwise
* @deprecated It is recommend to get this information from {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public boolean getIsFull() {
return getPropAsBoolean(ConfigurationKeys.EXTRACT_IS_FULL_KEY, false);
}
/**
* Set full drop date from the given time.
*
* @param extractFullRunTime full extract time
* @deprecated It is recommend to set this information in {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public void setFullTrue(long extractFullRunTime) {
setProp(ConfigurationKeys.EXTRACT_IS_FULL_KEY, true);
setProp(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY, extractFullRunTime);
}
/**
* Set primary keys.
*
* <p>
* The order of primary keys does not matter.
* </p>
*
* @param primaryKeyFieldName primary key names
* @deprecated It is recommended to set primary keys in {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public void setPrimaryKeys(String... primaryKeyFieldName) {
setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, Joiner.on(",").join(primaryKeyFieldName));
}
/**
* Add more primary keys to the existing set of primary keys.
*
* @param primaryKeyFieldName primary key names
* @deprecated @deprecated It is recommended to add primary keys in {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public void addPrimaryKey(String... primaryKeyFieldName) {
StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, ""));
Joiner.on(",").appendTo(sb, primaryKeyFieldName);
setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, sb.toString());
}
/**
* Get the list of primary keys.
*
* @return list of primary keys
* @deprecated It is recommended to obtain primary keys from {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public List<String> getPrimaryKeys() {
return getPropAsList(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY);
}
/**
* Set delta fields.
*
* <p>
* The order of delta fields does not matter.
* </p>
*
* @param deltaFieldName delta field names
* @deprecated It is recommended to set delta fields in {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public void setDeltaFields(String... deltaFieldName) {
setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, Joiner.on(",").join(deltaFieldName));
}
/**
* Add more delta fields to the existing set of delta fields.
*
* @param deltaFieldName delta field names
* @deprecated It is recommended to add delta fields in {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public void addDeltaField(String... deltaFieldName) {
StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, ""));
Joiner.on(",").appendTo(sb, deltaFieldName);
setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, sb.toString());
}
/**
* Get the list of delta fields.
*
* @return list of delta fields
* @deprecated It is recommended to obtain delta fields from {@code WorkUnit} instead of {@code Extract}.
*/
@Deprecated
public List<String> getDeltaFields() {
return getPropAsList(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY);
}
/**
* Get the previous table {@link State}.
*
* @return previous table {@link State}
*/
public State getPreviousTableState() {
return this.previousTableState;
}
}
| 2,072 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/WorkUnitBinPacker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.util.List;
/**
* A bin packing algorithm for packing {@link WorkUnit}s into {@link MultiWorkUnit}s.
*/
public interface WorkUnitBinPacker {
/**
* Packs the input {@link WorkUnit}s into {@link MultiWorkUnit}s.
* @param workUnitsIn List of {@link WorkUnit}s to pack.
* @param weighter {@link WorkUnitWeighter} that provides weights for {@link WorkUnit}s.
*/
public List<WorkUnit> pack(List<WorkUnit> workUnitsIn, WorkUnitWeighter weighter);
}
| 2,073 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/MissingExtractAttributeException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
public class MissingExtractAttributeException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Thrown if a required attributes hasn't been set for an extract.
*
* @author kgoodhop
*/
public MissingExtractAttributeException(String arg0) {
super(arg0);
}
}
| 2,074 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/BasicWorkUnitStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import lombok.Getter;
/**
* A basic implementation of {@link WorkUnitStream}.
*/
public class BasicWorkUnitStream implements WorkUnitStream {
/**
* Iterator over the {@link WorkUnit}s. Best practice is to only generate {@link WorkUnit}s on demand to save memory.
*/
private final Iterator<WorkUnit> workUnits;
private List<WorkUnit> materializedWorkUnits;
/**
* If true, this stream can be safely consumed before processing any work units.
* Note not all job launchers support infinite streams.
*/
@Getter
private final boolean finiteStream;
/**
* If true, this {@link WorkUnitStream} can be retrieved as a collection of {@link WorkUnit}s.
*/
@Getter
private final boolean safeToMaterialize;
BasicWorkUnitStream(Iterator<WorkUnit> workUnits, List<WorkUnit> materializedWorkUnits, boolean finiteStream, boolean safeToMaterialize) {
this.workUnits = workUnits;
this.materializedWorkUnits = materializedWorkUnits;
this.finiteStream = finiteStream;
this.safeToMaterialize = safeToMaterialize;
}
private BasicWorkUnitStream(BasicWorkUnitStream other, Iterator<WorkUnit> workUnits, List<WorkUnit> materializedWorkUnits) {
this.workUnits = workUnits;
this.materializedWorkUnits = materializedWorkUnits;
this.finiteStream = other.finiteStream;
this.safeToMaterialize = other.safeToMaterialize;
}
public Iterator<WorkUnit> getWorkUnits() {
if (this.materializedWorkUnits == null) {
return this.workUnits;
} else {
return this.materializedWorkUnits.iterator();
}
}
/**
* Apply a transformation function to this stream.
*/
public WorkUnitStream transform(Function<WorkUnit, WorkUnit> function) {
if (this.materializedWorkUnits == null) {
return new BasicWorkUnitStream(this, Iterators.transform(this.workUnits, function), null);
} else {
return new BasicWorkUnitStream(this, null, Lists.newArrayList(Lists.transform(this.materializedWorkUnits, function)));
}
}
/**
* Apply a filtering function to this stream.
*/
public WorkUnitStream filter(Predicate<WorkUnit> predicate) {
if (this.materializedWorkUnits == null) {
return new BasicWorkUnitStream(this, Iterators.filter(this.workUnits, predicate), null);
} else {
return new BasicWorkUnitStream(this, null, Lists.newArrayList(Iterables.filter(this.materializedWorkUnits, predicate)));
}
}
/**
* Get a materialized collection of the {@link WorkUnit}s in this stream. Note this call will fail if
* {@link #isSafeToMaterialize()} is false.
*/
public Collection<WorkUnit> getMaterializedWorkUnitCollection() {
materialize();
return this.materializedWorkUnits;
}
private void materialize() {
if (this.materializedWorkUnits != null) {
return;
}
if (!isSafeToMaterialize()) {
throw new UnsupportedOperationException("WorkUnitStream is not safe to materialize.");
}
this.materializedWorkUnits = Lists.newArrayList(this.workUnits);
}
public static class Builder {
private Iterator<WorkUnit> workUnits;
private List<WorkUnit> workUnitList;
private boolean finiteStream = true;
private boolean safeToMaterialize = false;
public Builder(Iterator<WorkUnit> workUnits) {
this.workUnits = workUnits;
}
public Builder(List<WorkUnit> workUnits) {
this.workUnitList = workUnits;
this.safeToMaterialize = true;
this.finiteStream = true;
}
public Builder setFiniteStream(boolean finiteStream) {
this.finiteStream = finiteStream;
return this;
}
public Builder setSafeToMaterialize(boolean safeToMaterialize) {
this.safeToMaterialize = safeToMaterialize;
return this;
}
public WorkUnitStream build() {
return new BasicWorkUnitStream(this.workUnits, this.workUnitList, this.finiteStream, this.safeToMaterialize);
}
}
}
| 2,075 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/ExtractFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.util.Locale;
import java.util.Set;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import org.apache.gobblin.source.workunit.Extract.TableType;
public class ExtractFactory {
private final Set<Extract> createdInstances;
private final DateTimeFormatter dtf;
public ExtractFactory(String dateTimeFormat) {
this.createdInstances = Sets.newHashSet();
this.dtf = DateTimeFormat.forPattern(dateTimeFormat).withLocale(Locale.US).withZone(DateTimeZone.UTC);
}
/**
* Returns a unique {@link Extract} instance.
* Any two calls of this method from the same {@link ExtractFactory} instance guarantees to
* return {@link Extract}s with different IDs.
*
* @param type {@link TableType}
* @param namespace dot separated namespace path
* @param table table name
* @return a unique {@link Extract} instance
*/
public synchronized Extract getUniqueExtract(TableType type, String namespace, String table) {
Extract newExtract = new Extract(type, namespace, table);
while (this.createdInstances.contains(newExtract)) {
if (Strings.isNullOrEmpty(newExtract.getExtractId())) {
newExtract.setExtractId(this.dtf.print(new DateTime()));
} else {
DateTime extractDateTime = this.dtf.parseDateTime(newExtract.getExtractId());
newExtract.setExtractId(this.dtf.print(extractDateTime.plusSeconds(1)));
}
}
this.createdInstances.add(newExtract);
return newExtract;
}
}
| 2,076 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/WorkUnitStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.util.Collection;
import java.util.Iterator;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
/**
* A stream of {@link WorkUnit}s, allows for working with large numbers of work units in a memory-efficient way, as
* well as processing infinite streams of work units.
*/
public interface WorkUnitStream {
/**
* @return Iterator of {@link WorkUnit}s.
*/
Iterator<WorkUnit> getWorkUnits();
/**
* @return true if this {@link WorkUnitStream} is finite.
*/
boolean isFiniteStream();
/**
* Apply a transformation function to this stream.
*/
WorkUnitStream transform(Function<WorkUnit, WorkUnit> function);
/**
* Apply a filtering function to this stream.
*/
WorkUnitStream filter(Predicate<WorkUnit> predicate);
/**
* @return true if it is safe to call {@link #getMaterializedWorkUnitCollection()} to get a collection of
* {@link WorkUnit}s.
*/
boolean isSafeToMaterialize();
/**
* Get a materialized collection of the {@link WorkUnit}s in this stream. Note this call will fail if
* {@link #isSafeToMaterialize()} is false. This method should be avoided unless strictly necessary, as it
* introduces a synchronization point for all work units, removing the speed and memory-efficiency benefits.
*/
Collection<WorkUnit> getMaterializedWorkUnitCollection();
}
| 2,077 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/ImmutableWorkUnit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.io.DataInput;
import java.io.IOException;
import java.util.Properties;
import org.apache.gobblin.configuration.State;
/**
* An immutable version of {@link WorkUnit}.
*
* @author Yinan Li
*/
public class ImmutableWorkUnit extends WorkUnit {
public ImmutableWorkUnit(WorkUnit workUnit) {
super(workUnit.getExtract());
// Only copy the specProperties from the given workUnit.
Properties specificPropertiesCopy = new Properties();
specificPropertiesCopy.putAll(workUnit.getSpecProperties());
super.setProps(workUnit.getCommonProperties(), specificPropertiesCopy);
}
@Override
public void setProp(String key, Object value) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override
public void setHighWaterMark(long highWaterMark) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override
public void setLowWaterMark(long lowWaterMark) {
throw new UnsupportedOperationException();
}
@Override
public void addAll(Properties properties) {
throw new UnsupportedOperationException();
}
@Override
public void addAll(State otherState) {
throw new UnsupportedOperationException();
}
@Override
public void addAllIfNotExist(Properties properties) {
throw new UnsupportedOperationException();
}
@Override
public void addAllIfNotExist(State otherState) {
throw new UnsupportedOperationException();
}
@Override
public void overrideWith(Properties properties) {
throw new UnsupportedOperationException();
}
@Override
public void overrideWith(State otherState) {
throw new UnsupportedOperationException();
}
@Override
public void setId(String id) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void appendToListProp(String key, String value) {
throw new UnsupportedOperationException();
}
@Override
public void readFields(DataInput in)
throws IOException {
throw new UnsupportedOperationException();
}
}
| 2,078 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/MultiWorkUnit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import lombok.ToString;
/**
* A class that wraps multiple {@link WorkUnit}s so they can executed within a single task.
*
* <p>
* This class also extends the {@link org.apache.gobblin.configuration.State} object and thus it is possible to set and get
* properties from this class. The {@link #setProp(String, Object)} method will add the specified key, value pair to
* this class as well as to every {@link WorkUnit} in {@link #workUnits}. The {@link #getProp(String)} methods will
* only return properties that have been explicitily set in this class (e.g. it will not retrieve properties from
* {@link #workUnits}.
* </p>
*
* @author Yinan Li
*/
@ToString(callSuper = true)
public class MultiWorkUnit extends WorkUnit {
private final List<WorkUnit> workUnits = Lists.newArrayList();
/**
* @deprecated Use {@link #createEmpty()} instead.
*/
@Deprecated
public MultiWorkUnit() {
super();
}
@Override
public boolean isMultiWorkUnit() {
return true;
}
/**
* Get an immutable list of {@link WorkUnit}s wrapped by this {@link MultiWorkUnit}.
*
* @return immutable list of {@link WorkUnit}s wrapped by this {@link MultiWorkUnit}
*/
public List<WorkUnit> getWorkUnits() {
return ImmutableList.<WorkUnit>builder().addAll(this.workUnits).build();
}
/**
* Add a single {@link WorkUnit}.
*
* @param workUnit {@link WorkUnit} to add
*/
public void addWorkUnit(WorkUnit workUnit) {
this.workUnits.add(workUnit);
}
/**
* Add a collection of {@link WorkUnit}s.
*
* @param workUnits collection of {@link WorkUnit}s to add
*/
public void addWorkUnits(Collection<WorkUnit> workUnits) {
this.workUnits.addAll(workUnits);
}
/**
* Set the specified key, value pair in this {@link MultiWorkUnit} as well as in all the inner {@link WorkUnit}s.
*
* {@inheritDoc}
* @see org.apache.gobblin.configuration.State#setProp(java.lang.String, java.lang.Object)
*/
@Override
public void setProp(String key, Object value) {
super.setProp(key, value);
for (WorkUnit workUnit : this.workUnits) {
workUnit.setProp(key, value);
}
}
/**
* Set the specified key, value pair in this {@link MultiWorkUnit} only, but do not propagate it to all the inner
* {@link WorkUnit}s.
*
* @param key property key
* @param value property value
*/
public void setPropExcludeInnerWorkUnits(String key, Object value) {
super.setProp(key, value);
}
@Override
public void readFields(DataInput in)
throws IOException {
int numWorkUnits = in.readInt();
for (int i = 0; i < numWorkUnits; i++) {
WorkUnit workUnit = WorkUnit.createEmpty();
workUnit.readFields(in);
this.workUnits.add(workUnit);
}
super.readFields(in);
}
@Override
public void write(DataOutput out)
throws IOException {
out.writeInt(this.workUnits.size());
for (WorkUnit workUnit : this.workUnits) {
workUnit.write(out);
}
super.write(out);
}
@Override
public boolean equals(Object object) {
if (!(object instanceof MultiWorkUnit)) {
return false;
}
MultiWorkUnit other = (MultiWorkUnit) object;
return super.equals(other) && this.workUnits.equals(other.workUnits);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((this.workUnits == null) ? 0 : this.workUnits.hashCode());
return result;
}
/**
* Create a new empty {@link MultiWorkUnit} instance.
*
* @return a new empty {@link MultiWorkUnit} instance
*/
public static MultiWorkUnit createEmpty() {
return new MultiWorkUnit();
}
/**
* Create a new {@link MultiWorkUnit} instance based on provided collection of {@link WorkUnit}s.
*
* @return a the {@link MultiWorkUnit} instance with the provided collection of {@link WorkUnit}s.
*/
public static MultiWorkUnit createMultiWorkUnit(Collection<WorkUnit> workUnits) {
MultiWorkUnit multiWorkUnit = new MultiWorkUnit();
multiWorkUnit.addWorkUnits(workUnits);
return multiWorkUnit;
}
}
| 2,079 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/WorkUnit.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.configuration.State;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.StringWriter;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.apache.gobblin.source.extractor.Extractor;
import org.apache.gobblin.source.extractor.Watermark;
import org.apache.gobblin.source.extractor.WatermarkInterval;
import lombok.ToString;
/**
* A logic concept that defines a unit of work or task for extracting a portion of the data
* to be pulled in a job run.
* <p>
* An instance of this class should contain all the properties an {@link Extractor} needs
* to extract the schema and data records.
* </p>
*
* @author kgoodhop
*/
@ToString(callSuper=true)
public class WorkUnit extends State {
private Extract extract;
private static final JsonParser JSON_PARSER = new JsonParser();
private static final Gson GSON = new Gson();
/**
* Default constructor.
*
* @deprecated Use {@link #createEmpty()}
*/
@Deprecated
public WorkUnit() {
this(null, null);
}
/**
* Constructor.
*
* @param state a {@link SourceState} the properties of which will be copied into this {@link WorkUnit} instance
* @param extract an {@link Extract}
*
* @deprecated Properties in {@link SourceState} should not be added to a {@link WorkUnit}. Having each
* {@link WorkUnit} contain a copy of {@link SourceState} is a waste of memory. Use {@link #create(Extract)}.
*/
@Deprecated
public WorkUnit(SourceState state, Extract extract) {
// Values should only be null for deserialization
if (state != null) {
super.addAll(state);
}
if (extract != null) {
this.extract = extract;
} else {
this.extract = new Extract(null, null, null, null);
}
}
/**
* Constructor for a {@link WorkUnit} given a {@link SourceState}, {@link Extract}, and a {@link WatermarkInterval}.
*
* @param state a {@link org.apache.gobblin.configuration.SourceState} the properties of which will be copied into this {@link WorkUnit} instance.
* @param extract an {@link Extract}.
* @param watermarkInterval a {@link WatermarkInterval} which defines the range of data this {@link WorkUnit} will process.
*
* @deprecated Properties in {@link SourceState} should not be added to a {@link WorkUnit}. Having each
* {@link WorkUnit} contain a copy of {@link SourceState} is a waste of memory. Use {@link #create(Extract, WatermarkInterval)}.
*/
@Deprecated
public WorkUnit(SourceState state, Extract extract, WatermarkInterval watermarkInterval) {
this(state, extract);
/**
* TODO
*
* Hack that stores a {@link WatermarkInterval} by using its {@link WatermarkInterval#toJson()} method. Until a
* state-store migration, or a new state-store format is chosen, this hack will be the way that the
* {@link WatermarkInterval} is serialized / de-serialized. Once a state-store migration can be done, the
* {@link Watermark} can be stored as Binary JSON.
*/
setProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY, watermarkInterval.toJson().toString());
}
/**
* Constructor.
*
* @param extract a {@link Extract} object
*/
public WorkUnit(Extract extract) {
this.extract = extract;
}
/**
* Copy constructor.
*
* @param other the other {@link WorkUnit} instance
*
* @deprecated Use {@link #copyOf(WorkUnit)}
*/
@Deprecated
public WorkUnit(WorkUnit other) {
super.addAll(other);
this.extract = other.getExtract();
}
/** @return whether a multi-work-unit (or else a singular one) */
public boolean isMultiWorkUnit() {
return false; // more efficient than `this instanceof MultiWorkUnit` plus no circular dependency
}
/**
* Factory method.
*
* @return An empty {@link WorkUnit}.
*/
public static WorkUnit createEmpty() {
return new WorkUnit();
}
/**
* Factory method.
*
* @param extract {@link Extract}
* @return A {@link WorkUnit} with the given {@link Extract}
*/
public static WorkUnit create(Extract extract) {
return new WorkUnit(null, extract);
}
/**
* Factory method.
*
* @param extract {@link Extract}
* @param watermarkInterval {@link WatermarkInterval}
* @return A {@link WorkUnit} with the given {@link Extract} and {@link WatermarkInterval}
*/
public static WorkUnit create(Extract extract, WatermarkInterval watermarkInterval) {
return new WorkUnit(null, extract, watermarkInterval);
}
/**
* Factory method.
*
* @param other a {@link WorkUnit} instance
* @return A copy of the given {@link WorkUnit} instance
*/
public static WorkUnit copyOf(WorkUnit other) {
return new WorkUnit(other);
}
/**
* Get the {@link Extract} associated with this {@link WorkUnit}.
*
* @return the {@link Extract} associated with this {@link WorkUnit}
*/
public Extract getExtract() {
return new ImmutableExtract(this.extract);
}
/**
* This method will allow a work unit to be skipped if needed.
*/
public void skip() {
this.setProp(ConfigurationKeys.WORK_UNIT_SKIP_KEY, true);
}
/**
* Get the low {@link Watermark} as a {@link JsonElement}.
*
* @return a {@link JsonElement} representing the low {@link Watermark} or
* {@code null} if the low {@link Watermark} is not set.
*/
public JsonElement getLowWatermark() {
if (!contains(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)) {
return null;
}
return JSON_PARSER.parse(getProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)).getAsJsonObject()
.get(WatermarkInterval.LOW_WATERMARK_TO_JSON_KEY);
}
/**
* Get the low {@link Watermark}.
*
* @param watermarkClass the watermark class for this {@code WorkUnit}.
* @param gson a {@link Gson} object used to deserialize the watermark.
* @return the low watermark in this {@code WorkUnit}.
*/
public <T extends Watermark> T getLowWatermark(Class<T> watermarkClass, Gson gson) {
JsonElement json = getLowWatermark();
if (json == null) {
return null;
}
return gson.fromJson(json, watermarkClass);
}
/**
* Get the low {@link Watermark}. A default {@link Gson} object will be used to deserialize the watermark.
*
* @param watermarkClass the watermark class for this {@code WorkUnit}.
* @return the low watermark in this {@code WorkUnit}.
*/
public <T extends Watermark> T getLowWatermark(Class<T> watermarkClass) {
return getLowWatermark(watermarkClass, GSON);
}
/**
* Get the expected high {@link Watermark} as a {@link JsonElement}.
*
* @return a {@link JsonElement} representing the expected high {@link Watermark}.
*/
public JsonElement getExpectedHighWatermark() {
return JSON_PARSER.parse(getProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)).getAsJsonObject()
.get(WatermarkInterval.EXPECTED_HIGH_WATERMARK_TO_JSON_KEY);
}
/**
* Get the expected high {@link Watermark}.
*
* @param watermarkClass the watermark class for this {@code WorkUnit}.
* @param gson a {@link Gson} object used to deserialize the watermark.
* @return the expected high watermark in this {@code WorkUnit}.
*/
public <T extends Watermark> T getExpectedHighWatermark(Class<T> watermarkClass, Gson gson) {
JsonElement json = getExpectedHighWatermark();
if (json == null) {
return null;
}
return gson.fromJson(json, watermarkClass);
}
/**
* Get the expected high {@link Watermark}. A default {@link Gson} object will be used to deserialize the watermark.
*
* @param watermarkClass the watermark class for this {@code WorkUnit}.
* @return the expected high watermark in this {@code WorkUnit}.
*/
public <T extends Watermark> T getExpectedHighWatermark(Class<T> watermarkClass) {
return getExpectedHighWatermark(watermarkClass, GSON);
}
/**
* Get the high watermark of this {@link WorkUnit}.
*
* @return high watermark
* @deprecated use the {@link #getExpectedHighWatermark()} method.
*/
@Deprecated
public long getHighWaterMark() {
return getPropAsLong(ConfigurationKeys.WORK_UNIT_HIGH_WATER_MARK_KEY);
}
/**
* Set {@link WatermarkInterval} for a {@link WorkUnit}.
*/
public void setWatermarkInterval(WatermarkInterval watermarkInterval) {
setProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY, watermarkInterval.toJson().toString());
}
/**
* Set the high watermark of this {@link WorkUnit}.
*
* @param highWaterMark high watermark
* @deprecated use {@link #setWatermarkInterval(WatermarkInterval)}.
*/
@Deprecated
public void setHighWaterMark(long highWaterMark) {
setProp(ConfigurationKeys.WORK_UNIT_HIGH_WATER_MARK_KEY, highWaterMark);
}
/**
* Get the low watermark of this {@link WorkUnit}.
*
* @return low watermark
* @deprecated use the {@link #getLowWatermark()} method.
*/
@Deprecated
public long getLowWaterMark() {
return getPropAsLong(ConfigurationKeys.WORK_UNIT_LOW_WATER_MARK_KEY);
}
@Override
public boolean contains(String key) {
return super.contains(key) || this.extract.contains(key);
}
@Override
public String getProp(String key) {
return getProp(key, null);
}
@Override
public String getProp(String key, String def) {
String value = super.getProp(key);
if (value == null) {
value = this.extract.getProp(key, def);
}
return value;
}
/**
* Set the low watermark of this {@link WorkUnit}.
*
* @param lowWaterMark low watermark
* @deprecated use {@link #setWatermarkInterval(WatermarkInterval)}.
*/
@Deprecated
public void setLowWaterMark(long lowWaterMark) {
setProp(ConfigurationKeys.WORK_UNIT_LOW_WATER_MARK_KEY, lowWaterMark);
}
@Override
public void readFields(DataInput in) throws IOException {
super.readFields(in);
this.extract.readFields(in);
}
@Override
public void write(DataOutput out) throws IOException {
super.write(out);
this.extract.write(out);
}
@Override
public boolean equals(Object object) {
if (!(object instanceof WorkUnit)) {
return false;
}
WorkUnit other = (WorkUnit) object;
return ((this.extract == null && other.extract == null)
|| (this.extract != null && this.extract.equals(other.extract))) && super.equals(other);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((this.extract == null) ? 0 : this.extract.hashCode());
return result;
}
/** @return pretty-printed JSON, including all properties */
public String toJsonString() {
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = new JsonWriter(stringWriter)) {
jsonWriter.setIndent("\t");
this.toJson(jsonWriter);
} catch (IOException ioe) {
// Ignored
}
return stringWriter.toString();
}
public void toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("id").value(this.getId());
jsonWriter.name("properties");
jsonWriter.beginObject();
for (String key : this.getPropertyNames()) {
jsonWriter.name(key).value(this.getProp(key));
}
jsonWriter.endObject();
jsonWriter.name("extract");
jsonWriter.beginObject();
jsonWriter.name("extractId").value(this.getExtract().getId());
jsonWriter.name("extractProperties");
jsonWriter.beginObject();
for (String key : this.getExtract().getPropertyNames()) {
jsonWriter.name(key).value(this.getExtract().getProp(key));
}
jsonWriter.endObject();
State prevTableState = this.getExtract().getPreviousTableState();
if (prevTableState != null) {
jsonWriter.name("extractPrevTableState");
jsonWriter.beginObject();
jsonWriter.name("prevStateId").value(prevTableState.getId());
jsonWriter.name("prevStateProperties");
jsonWriter.beginObject();
for (String key : prevTableState.getPropertyNames()) {
jsonWriter.name(key).value(prevTableState.getProp(key));
}
jsonWriter.endObject();
jsonWriter.endObject();
}
jsonWriter.endObject();
jsonWriter.endObject();
}
public String getOutputFilePath() {
// Search for the properties in the workunit.
// This search for the property first in State and then in the Extract of this workunit.
String namespace = getProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, "");
String table = getProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, "");
String extractId = getProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, "");
// getPropAsBoolean and other similar methods are not overridden in WorkUnit class
// Thus, to enable searching in WorkUnit's Extract, we use getProp, and not getPropAsBoolean
boolean isFull = Boolean.parseBoolean(getProp(ConfigurationKeys.EXTRACT_IS_FULL_KEY));
return namespace.replaceAll("\\.", "/") + "/" + table + "/" + extractId + "_"
+ (isFull ? "full" : "append");
}
}
| 2,080 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/WorkUnitWeighter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
/**
* Provides weights for {@link WorkUnit}s to use by a {@link WorkUnitBinPacker}.
*
* <p>
* The weight is used by a bin packing algorithm to organize {@link WorkUnit}s into {@link org.apache.gobblin.source.workunit.MultiWorkUnit}s
* with a bounded total weight. The weighter must have the following properties:
* <ul>
* <li>If wu1.equals(wu2), then weight(wu1) == weight(wu2).</li>
* <li>Each weight must be positive.</li>
* </ul>
* Ideally, the weights are a linear representation of the resources needed to process a work unit.
* </p>
*/
public interface WorkUnitWeighter {
/**
* The weight of this work unit.
*/
public long weight(WorkUnit workUnit);
}
| 2,081 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/ImmutableExtract.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.workunit;
import java.io.DataInput;
import java.io.IOException;
import java.util.Properties;
import org.apache.gobblin.configuration.SourceState;
import org.apache.gobblin.configuration.State;
/**
* An immutable version of {@link Extract}.
*
* @author Yinan Li
*/
public class ImmutableExtract extends Extract {
public ImmutableExtract(SourceState state, TableType type, String namespace, String table) {
super(state, type, namespace, table);
}
public ImmutableExtract(Extract extract) {
super(extract);
}
@Override
public void setFullTrue(long extractFullRunTime) {
throw new UnsupportedOperationException();
}
@Override
public void setPrimaryKeys(String... primaryKeyFieldName) {
throw new UnsupportedOperationException();
}
@Override
public void setDeltaFields(String... deltaFieldName) {
throw new UnsupportedOperationException();
}
@Override
public void setId(String id) {
throw new UnsupportedOperationException();
}
@Override
public void setProp(String key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void appendToListProp(String key, String value) {
throw new UnsupportedOperationException();
}
@Override
public void addAll(Properties properties) {
throw new UnsupportedOperationException();
}
@Override
public void addAll(State otherState) {
throw new UnsupportedOperationException();
}
@Override
public void addAllIfNotExist(Properties properties) {
throw new UnsupportedOperationException();
}
@Override
public void addAllIfNotExist(State otherState) {
throw new UnsupportedOperationException();
}
public void overrideWith(Properties properties) {
throw new UnsupportedOperationException();
}
public void overrideWith(State otherState) {
throw new UnsupportedOperationException();
}
@Override
public void readFields(DataInput in) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void setExtractId(String extractId) {
throw new UnsupportedOperationException();
}
@Override
public void addPrimaryKey(String... primaryKeyFieldName) {
throw new UnsupportedOperationException();
}
@Override
public void addDeltaField(String... deltaFieldName) {
throw new UnsupportedOperationException();
}
}
| 2,082 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/ComparableWatermark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
/**
* {@link Watermark} that is also {@link Comparable}.
*/
public interface ComparableWatermark extends Watermark, Comparable<ComparableWatermark>{
}
| 2,083 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/Watermark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import com.google.gson.JsonElement;
/**
* A {@link Watermark} represents a checkpoint in data processing, and indicates that all data up to specific point has
* been pulled from some source. Implementations of this interface are responsible for defining data structures in order
* to track this state.
*
* <p>
* A {@link Watermark} will be serialized in {@link org.apache.gobblin.source.workunit.WorkUnit}s and
* {@link org.apache.gobblin.configuration.WorkUnitState}s. The {@link #toJson()} method will be used to serialize the
* {@link Watermark} into a {@link JsonElement}.
* </p>
*/
public interface Watermark {
/**
* Convert this {@link Watermark} into a {@link JsonElement}.
* @return a {@link JsonElement} representing this {@link Watermark}.
*/
public JsonElement toJson();
/**
* This method must return a value from [0, 100]. The value should correspond to a percent completion. Given two
* {@link Watermark} values, where the lowWatermark is the starting point, and the highWatermark is the goal, what
* is the percent completion of this {@link Watermark}.
*
* @param lowWatermark is the starting {@link Watermark} for the percent completion calculation. So if this.equals(lowWatermark) is true, this method should return 0.
* @param highWatermark is the end value {@link Watermark} for the percent completion calculation. So if this.equals(highWatermark) is true, this method should return 100.
* @return a value from [0, 100] representing the percentage completion of this {@link Watermark}.
*/
public short calculatePercentCompletion(Watermark lowWatermark, Watermark highWatermark);
}
| 2,084 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/WatermarkInterval.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Each {@link org.apache.gobblin.source.workunit.WorkUnit} has a corresponding {@link WatermarkInterval}. The
* {@link WatermarkInterval} represents the range of the data that needs to be pulled for the {@link WorkUnit}. So, the
* {@link org.apache.gobblin.source.workunit.WorkUnit} should pull data from the {@link #lowWatermark} to the
* {@link #expectedHighWatermark}.
*/
public class WatermarkInterval {
public static final String LOW_WATERMARK_TO_JSON_KEY = "low.watermark.to.json";
public static final String EXPECTED_HIGH_WATERMARK_TO_JSON_KEY = "expected.watermark.to.json";
private final Watermark lowWatermark;
private final Watermark expectedHighWatermark;
public WatermarkInterval(Watermark lowWatermark, Watermark expectedHighWatermark) {
this.lowWatermark = lowWatermark;
this.expectedHighWatermark = expectedHighWatermark;
}
public Watermark getLowWatermark() {
return this.lowWatermark;
}
public Watermark getExpectedHighWatermark() {
return this.expectedHighWatermark;
}
public JsonElement toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.add(LOW_WATERMARK_TO_JSON_KEY, this.lowWatermark.toJson());
jsonObject.add(EXPECTED_HIGH_WATERMARK_TO_JSON_KEY, this.expectedHighWatermark.toJson());
return jsonObject;
}
}
| 2,085 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/WatermarkSerializerHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
/**
* Provides default implementation for converting a {@link Watermark} to a {@link JsonElement}, and vice versa. The
* class uses <a href="https://code.google.com/p/google-gson/">GSON</a> to achieve this. This class provides a default
* way to serialize and de-serialize {@link Watermark}s, and is useful for implementing the {@link Watermark#toJson()}
* method.
*/
public class WatermarkSerializerHelper {
private static final Gson GSON = new Gson();
/**
* Converts a {@link Watermark} to a {@link JsonElement} using the {@link Gson#toJsonTree(Object)} method.
*
* @param watermark the {@link Watermark} that needs to be converted to json.
* @return a {@link JsonElement} that represents the given {@link Watermark}.
*/
public static JsonElement convertWatermarkToJson(Watermark watermark) {
return GSON.toJsonTree(watermark);
}
/**
* Converts a {@link JsonElement} into the specified class type using the {@link Gson#fromJson(JsonElement, Class)}
* method.
*
* @param jsonElement is a {@link JsonElement} that will be converted into a {@link Watermark}.
* @param clazz is the {@link Class} that the {@link JsonElement} will be converted into.
* @return an instance of a class that extends {@link Watermark}.
*/
public static <T extends Watermark> T convertJsonToWatermark(JsonElement jsonElement, Class<T> clazz) {
return GSON.fromJson(jsonElement, clazz);
}
}
| 2,086 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/DataRecordException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
public class DataRecordException extends Exception {
private static final long serialVersionUID = 1L;
public DataRecordException(String message, Exception e) {
super(message, e);
}
public DataRecordException(String message) {
super(message);
}
}
| 2,087 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/StreamingExtractor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import java.io.IOException;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.writer.WatermarkStorage;
/**
* An interface for implementing streaming / continuous extractors
*/
@Alpha
public interface StreamingExtractor<S, D> extends Extractor<S, D> {
/**
* Initialize the extractor to be ready to read records
* @param watermarkStorage : watermark storage to retrieve previously committed watermarks
* @throws IOException : typically if there was a failure in retrieving watermarks
*/
void start(WatermarkStorage watermarkStorage) throws IOException;
}
| 2,088 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/Extractor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.gobblin.metadata.GlobalMetadata;
import org.apache.gobblin.records.RecordStreamWithMetadata;
import org.apache.gobblin.runtime.JobShutdownException;
import org.apache.gobblin.stream.RecordEnvelope;
import org.apache.gobblin.stream.StreamEntity;
import org.apache.gobblin.util.Decorator;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import io.reactivex.Emitter;
import io.reactivex.Flowable;
import io.reactivex.functions.BiConsumer;
import javax.annotation.Nullable;
/**
* An interface for classes that are responsible for extracting data from a data source.
*
* <p>
* All source specific logic for a data source should be encapsulated in an
* implementation of this interface and {@link org.apache.gobblin.source.Source}.
* </p>
*
* @author kgoodhop
*
* @param <S> output schema type
* @param <D> output record type
*/
public interface Extractor<S, D> extends Closeable {
/**
* Get the schema (metadata) of the extracted data records.
*
* @return schema of the extracted data records
* @throws java.io.IOException if there is problem getting the schema
*/
S getSchema() throws IOException;
/**
* Read the next data record from the data source.
*
* <p>
* Reuse of data records has been deprecated and is not executed internally.
* </p>
*
* @param reuse the data record object to be reused
* @return the next data record extracted from the data source
* @throws DataRecordException if there is problem with the extracted data record
* @throws java.io.IOException if there is problem extracting the next data record from the source
*/
@Nullable
default D readRecord(@Deprecated D reuse) throws DataRecordException, IOException {
throw new UnsupportedOperationException();
}
/**
* Get the expected source record count.
*
* @return the expected source record count
*/
long getExpectedRecordCount();
/**
* Get the calculated high watermark up to which data records are to be extracted.
*
* @return the calculated high watermark
* @deprecated there is no longer support for reporting the high watermark via this method, please see
* <a href="https://gobblin.readthedocs.io/en/latest/user-guide/State-Management-and-Watermarks/">Watermarks</a> for more information.
*/
@Deprecated
long getHighWatermark();
/**
* Called to notify the Extractor it should shut down as soon as possible. If this call returns successfully, the task
* will continue consuming records from the Extractor and continue execution normally. The extractor should only emit
* those records necessary to stop at a graceful committable state. Most job executors will eventually kill the task
* if the Extractor does not stop emitting records after a few seconds.
*
* @throws JobShutdownException if the extractor does not support early termination. This will cause the task to fail.
*/
default void shutdown() throws JobShutdownException {
if (this instanceof Decorator && ((Decorator) this).getDecoratedObject() instanceof Extractor) {
((Extractor) ((Decorator) this).getDecoratedObject()).shutdown();
} else {
throw new JobShutdownException(this.getClass().getName() + ": Extractor does not support shutdown.");
}
}
/**
* Read an {@link RecordEnvelope}. By default, just wrap {@link #readRecord(Object)} in a {@link RecordEnvelope}.
*/
@SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
justification = "Findbugs believes readRecord(null) is non-null. This is not true.")
default RecordEnvelope<D> readRecordEnvelope() throws DataRecordException, IOException {
D record = readRecord(null);
return record == null ? null : new RecordEnvelope<>(record);
}
/**
* Read an {@link StreamEntity}. By default, just return result of {@link #readRecordEnvelope()}.
*/
default StreamEntity<D> readStreamEntity() throws DataRecordException, IOException {
return readRecordEnvelope();
}
/**
* @param shutdownRequest an {@link AtomicBoolean} that becomes true when a shutdown has been requested.
* @return a {@link Flowable} with the records from this source. Note the flowable should honor downstream backpressure.
*/
default RecordStreamWithMetadata<D, S> recordStream(AtomicBoolean shutdownRequest) throws IOException {
S schema = getSchema();
Flowable<StreamEntity<D>> recordStream = Flowable.generate(() -> shutdownRequest, (BiConsumer<AtomicBoolean, Emitter<StreamEntity<D>>>) (state, emitter) -> {
if (state.get()) {
// shutdown requested
try {
shutdown();
} catch (JobShutdownException exc) {
emitter.onError(exc);
}
}
try {
StreamEntity<D> record = readStreamEntity();
if (record != null) {
emitter.onNext(record);
} else {
emitter.onComplete();
}
} catch (DataRecordException | IOException exc) {
emitter.onError(exc);
}
});
recordStream = recordStream.doFinally(this::close);
return new RecordStreamWithMetadata<>(recordStream, GlobalMetadata.<S>builder().schema(schema).build());
}
}
| 2,089 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/source/extractor/CheckpointableWatermark.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.source.extractor;
import org.apache.gobblin.annotation.Alpha;
/**
* {@link Watermark} that is {@link Comparable} and Checkpointable
*/
@Alpha
public interface CheckpointableWatermark extends Watermark, Comparable<CheckpointableWatermark> {
/**
*
* @return the unique id of the source that generated this watermark.
* Watermarks generated by different sources are not comparable and therefore need to be checkpoint-ed independently
*/
String getSource();
/**
*
* @return the source-local watermark.
*/
ComparableWatermark getWatermark();
} | 2,090 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/capability/Capability.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.capability;
import org.apache.gobblin.annotation.Alpha;
import lombok.Data;
/**
* Represents a set of functionality a job-creator can ask for. Examples could include
* encryption, compression, partitioning...
*
* Each Capability has a name and then a set of associated configuration properties. An example is
* the encryption algorithm to use.
*/
@Alpha
@Data
public class Capability {
/**
* Threadsafe capability.
*/
public static final Capability THREADSAFE = new Capability("THREADSAFE", false);
private final String name;
private final boolean critical;
}
| 2,091 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/capability/CapabilityAware.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.capability;
import java.util.Map;
import org.apache.gobblin.annotation.Alpha;
/**
* Describes an object that is aware of the capabilities it supports.
*/
@Alpha
public interface CapabilityAware {
/**
* Checks if this object supports the given Capability with the given properties.
*
* Implementers of this should always check if their super-class may happen to support a capability
* before returning false!
* @param c Capability being queried
* @param properties Properties specific to the capability. Properties are capability specific.
* @return True if this object supports the given capability + property settings, false if not
*/
boolean supportsCapability(Capability c, Map<String, Object> properties);
}
| 2,092 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/NoopTaskEventMetadataGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.apache.gobblin.annotation.Alias;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.runtime.api.TaskEventMetadataGenerator;
@Alias("nooptask")
public class NoopTaskEventMetadataGenerator implements TaskEventMetadataGenerator {
/**
* Generate a map of additional metadata for the specified event name.
*
* @param taskState
* @param eventName the event name used to determine which additional metadata should be emitted
* @return {@link Map} with the additional metadata
*/
@Override
public Map<String, String> getMetadata(State taskState, String eventName) {
return ImmutableMap.of();
}
}
| 2,093 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/CheckpointableWatermarkState.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime;
import com.google.gson.Gson;
import org.apache.gobblin.configuration.State;
import org.apache.gobblin.source.extractor.CheckpointableWatermark;
/**
* Making {@link CheckpointableWatermark} look like {@link State} so it can be
* stored in a Gobblin state store.
*/
public class CheckpointableWatermarkState extends State {
/**
* Create a CheckpointableWatermarkState object from a CheckpointableWatermark
* @param watermark: the checkpointable watermark
* @param gson: the instance of {@link Gson} to use for serializing the {@param watermark}.
*/
public CheckpointableWatermarkState(CheckpointableWatermark watermark, Gson gson) {
super.setProp(watermark.getSource(), gson.toJsonTree(watermark));
super.setId(watermark.getSource());
}
public String getSource() {
return getId();
}
/**
* Needed for reflection based construction.
*/
public CheckpointableWatermarkState() {
}
}
| 2,094 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/JobShutdownException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime;
/**
* An exception thrown when a job cannot be graciously shutdown.
*/
public class JobShutdownException extends Exception {
public JobShutdownException(String message) {
super(message);
}
}
| 2,095 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/BasicTestControlMessage.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime;
import org.apache.gobblin.stream.ControlMessage;
import org.apache.gobblin.stream.StreamEntity;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
/**
* A basic {@link ControlMessage} used for testing.
*/
@AllArgsConstructor
@EqualsAndHashCode
public class BasicTestControlMessage<T> extends ControlMessage<T> {
private final String id;
@Override
public StreamEntity<T> buildClone() {
return new BasicTestControlMessage(this.id);
}
}
| 2,096 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/api/AdminWebServerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime.api;
import java.net.URI;
import java.util.Properties;
import com.google.common.util.concurrent.Service;
import org.apache.gobblin.annotation.Alpha;
/**
* A factory interface for AdminWebServer.
*
* NOTE: This interface is provided for backwards compatibility and may change in the future.
* @author cbotev
*
*/
@Alpha
public interface AdminWebServerFactory {
/**
* Creates a new AdminWebServer instance
* @param config the server config
* @param executionInfoServerURI the URI to the job execution server
* @return the instance
*/
Service createInstance(Properties config, URI executionInfoServerURI);
}
| 2,097 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/api/SpecProducer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime.api;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Future;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.util.CompletedFuture;
/**
* Defines a SpecProducer to produce jobs to {@link SpecExecutor}
* that can execute a {@link Spec}.
*
* A handle on the Orchestrator side to send {@link Spec}s.
*/
@Alpha
public interface SpecProducer<V> {
/** Add a {@link Spec} for execution on {@link SpecExecutor}. */
Future<?> addSpec(V addedSpec);
/** Update a {@link Spec} being executed on {@link SpecExecutor}. */
Future<?> updateSpec(V updatedSpec);
default Future<?> deleteSpec(URI deletedSpecURI) {
return deleteSpec(deletedSpecURI, new Properties());
}
/** Delete a {@link Spec} being executed on {@link SpecExecutor}. */
Future<?> deleteSpec(URI deletedSpecURI, Properties headers);
/** List all {@link Spec} being executed on {@link SpecExecutor}. */
Future<? extends List<V>> listSpecs();
default String getExecutionLink(Future<?> future, String specExecutorUri) {
return "";
}
default String serializeAddSpecResponse(Future<?> response) {
return "";
}
default Future<?> deserializeAddSpecResponse(String serializedResponse) {
return new CompletedFuture(serializedResponse, null);
}
/** Cancel the job execution identified by jobURI */
default Future<?> cancelJob(URI jobURI, Properties properties) {
return new CompletedFuture<>(jobURI, null);
}
} | 2,098 |
0 | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime | Create_ds/gobblin/gobblin-api/src/main/java/org/apache/gobblin/runtime/api/FlowEdge.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.gobblin.runtime.api;
import com.typesafe.config.Config;
/**
* A typical edge consists of two types of attributes:
* - Numerical value based: Return an numerical value for evaluation.
* - Boolean value based: Return either true or false.
*/
public interface FlowEdge {
/**
* @return Uniqueness of an edge is defined by
* - sourceNode
* - targetNode
* - SpecExecutor
* hashCode and equals is required to implemented accordingly.
*/
String getEdgeIdentity();
/**
* Return read-only Edge Properties .
* @return
*/
Config getEdgeProperties();
/**
* @return If a edge should be considered as part of flow spec compilation result,
* based on all boolean-based properties like safety.
*/
boolean isEdgeEnabled();
} | 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.