index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestDataset.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.api.consumer.HollowConsumer;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import com.netflix.hollow.core.util.StateEngineRoundTripper;
import com.netflix.hollow.core.write.HollowBlobWriter;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public abstract class HollowTestDataset {
private final HollowWriteStateEngine writeEngine;
private final List<HollowTestRecord<Void>> recsToAdd;
private HollowTestBlobRetriever blobRetriever;
private long currentState = 0L;
public HollowTestDataset() {
this.writeEngine = new HollowWriteStateEngine();
this.recsToAdd = new ArrayList<>();
}
public void add(HollowTestRecord<Void> rec) {
recsToAdd.add(rec);
}
public HollowConsumer.Builder<?> newConsumerBuilder() {
blobRetriever = new HollowTestBlobRetriever();
return HollowConsumer
.newHollowConsumer()
.withBlobRetriever(blobRetriever);
}
public void buildHeader(HollowConsumer consumer) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HollowBlobWriter writer = new HollowBlobWriter(writeEngine);
writer.writeHeader(baos, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void buildSnapshot(HollowConsumer consumer) {
for(HollowTestRecord<Void> rec : recsToAdd) {
rec.addTo(writeEngine);
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HollowBlobWriter writer = new HollowBlobWriter(writeEngine);
writer.writeSnapshot(baos);
writeEngine.prepareForNextCycle();
blobRetriever.addSnapshot(currentState, new HollowTestBlobRetriever.TestBlob(currentState, baos.toByteArray()));
consumer.triggerRefreshTo(currentState);
} catch(IOException rethrow) {
throw new RuntimeException(rethrow);
}
}
public void buildDelta(HollowConsumer consumer) {
for(HollowTestRecord<Void> rec : recsToAdd) {
rec.addTo(writeEngine);
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HollowBlobWriter writer = new HollowBlobWriter(writeEngine);
writer.writeDelta(baos);
writeEngine.prepareForNextCycle();
long nextState = currentState + 1;
blobRetriever.addDelta(currentState, new HollowTestBlobRetriever.TestBlob(currentState, nextState, baos.toByteArray()));
consumer.triggerRefreshTo(nextState);
currentState = nextState;
} catch(IOException rethrow) {
throw new RuntimeException(rethrow);
}
}
public HollowReadStateEngine buildSnapshot() {
for(HollowTestRecord<Void> rec : recsToAdd) {
rec.addTo(writeEngine);
}
try {
return StateEngineRoundTripper.roundTripSnapshot(writeEngine);
} catch(IOException rethrow) {
throw new RuntimeException(rethrow);
}
}
public void buildDelta(HollowReadStateEngine readEngine) {
for(HollowTestRecord<Void> rec : recsToAdd) {
rec.addTo(writeEngine);
}
try {
StateEngineRoundTripper.roundTripDelta(writeEngine, readEngine);
} catch(IOException rethrow) {
throw new RuntimeException(rethrow);
}
}
}
| 9,200 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestBlobRetriever.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.api.consumer.HollowConsumer.Blob;
import com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever;
import com.netflix.hollow.api.consumer.HollowConsumer.HeaderBlob;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* A simple implementation of a BlobRetriever which allows adding blobs and holds them all in
* memory.
*/
class HollowTestBlobRetriever implements BlobRetriever {
private final Map<Long, Blob> snapshots = new HashMap<>();
private final Map<Long, Blob> deltas = new HashMap<>();
private final Map<Long, Blob> reverseDeltas = new HashMap<>();
private final Map<Long, HeaderBlob> headers = new HashMap<>();
@Override
public Blob retrieveSnapshotBlob(long desiredVersion) {
return snapshots.get(desiredVersion);
}
@Override
public Blob retrieveDeltaBlob(long currentVersion) {
return deltas.get(currentVersion);
}
@Override
public Blob retrieveReverseDeltaBlob(long currentVersion) {
return reverseDeltas.get(currentVersion);
}
@Override
public HeaderBlob retrieveHeaderBlob(long desiredVersion) {
return headers.get(desiredVersion);
}
public void addSnapshot(long desiredVersion, Blob transition) {
snapshots.put(desiredVersion, transition);
}
public void addDelta(long currentVersion, Blob transition) {
deltas.put(currentVersion, transition);
}
public void addHeader(long desiredVersion, HeaderBlob headerBlob) {
headers.put(desiredVersion, headerBlob);
}
public void addReverseDelta(long currentVersion, Blob transition) {
reverseDeltas.put(currentVersion, transition);
}
public static class TestHeaderBlob extends HeaderBlob {
private final byte[] data;
protected TestHeaderBlob(long version, byte[] data) {
super(version);
this.data = data;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
}
public static class TestBlob extends Blob {
private final byte[] data;
public TestBlob(long snapshotVersion, byte[] data) {
super(snapshotVersion);
this.data = data;
}
public TestBlob(long fromVersion, long toVersion, byte[] data) {
super(fromVersion, toVersion);
this.data = data;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
}
}
| 9,201 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestObjectRecord.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.write.HollowObjectWriteRecord;
import com.netflix.hollow.core.write.HollowWriteRecord;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import java.util.HashMap;
import java.util.Map;
public abstract class HollowTestObjectRecord<T> extends HollowTestRecord<T> {
private final Map<String, Field> fields;
protected HollowTestObjectRecord(T parent) {
super(parent);
this.fields = new HashMap<>();
}
protected void addField(String fieldName, Object value) {
if(value == null) {
fields.remove(fieldName);
} else {
addField(new Field(fieldName, value));
}
}
protected void addField(Field field) {
if(field.value == null)
this.fields.remove(field.name);
else
this.fields.put(field.name, field);
}
protected Field getField(String name) {
return fields.get(name);
}
@SuppressWarnings("rawtypes")
@Override
protected HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine) {
HollowObjectWriteRecord rec = new HollowObjectWriteRecord(getSchema());
for(Map.Entry<String, Field> entry : fields.entrySet()) {
Field field = entry.getValue();
if(field.value instanceof Integer) {
rec.setInt(field.name, (Integer)field.value);
} else if(field.value instanceof Long) {
rec.setLong(field.name, (Long)field.value);
} else if(field.value instanceof Float) {
rec.setFloat(field.name, (Float)field.value);
} else if(field.value instanceof Boolean) {
rec.setBoolean(field.name, (Boolean)field.value);
} else if(field.value instanceof String) {
rec.setString(field.name, (String)field.value);
} else if(field.value instanceof byte[]) {
rec.setBytes(field.name, (byte[])field.value);
} else if(field.value instanceof HollowTestRecord) {
rec.setReference(field.name, ((HollowTestRecord)field.value).addTo(writeEngine));
} else {
throw new IllegalStateException("Unknown field type: " + field.value.getClass());
}
}
return rec;
}
protected abstract HollowObjectSchema getSchema();
protected static class Field {
public final String name;
public final Object value;
public Field(String name, Object value) {
this.name = name;
this.value = value;
}
}
}
| 9,202 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestListRecord.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.core.write.HollowListWriteRecord;
import com.netflix.hollow.core.write.HollowWriteRecord;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import java.util.ArrayList;
import java.util.List;
public abstract class HollowTestListRecord<T> extends HollowTestRecord<T> {
private final List<HollowTestRecord<?>> elements = new ArrayList<>();
protected HollowTestListRecord(T parent) {
super(parent);
}
protected void addElement(HollowTestRecord<?> element) {
elements.add(element);
}
@SuppressWarnings({ "hiding", "unchecked" })
public <T extends HollowTestRecord<?>> T getRecord(int idx) {
return (T) elements.get(idx);
}
public HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine) {
HollowListWriteRecord rec = new HollowListWriteRecord();
for(HollowTestRecord<?> e : elements) {
rec.addElement(e.addTo(writeEngine));
}
return rec;
}
}
| 9,203 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestSetRecord.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.core.write.HollowSetWriteRecord;
import com.netflix.hollow.core.write.HollowWriteRecord;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import java.util.HashSet;
import java.util.Set;
public abstract class HollowTestSetRecord<T> extends HollowTestRecord<T> {
private final Set<HollowTestRecord<?>> elements = new HashSet<>();
protected HollowTestSetRecord(T parent) {
super(parent);
}
protected void addElement(HollowTestRecord<?> element) {
elements.add(element);
}
public HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine) {
HollowSetWriteRecord rec = new HollowSetWriteRecord();
for(HollowTestRecord<?> e : elements) {
rec.addElement(e.addTo(writeEngine));
}
return rec;
}
}
| 9,204 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestDataMapEntry.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
@SuppressWarnings("rawtypes")
public class HollowTestDataMapEntry<K extends HollowTestRecord, V extends HollowTestRecord> {
private final K key;
private final V value;
public HollowTestDataMapEntry(K key, V value) {
this.key = key;
this.value = value;
}
public K key() {
return key;
}
public V value() {
return value;
}
public static <K extends HollowTestRecord, V extends HollowTestRecord> HollowTestDataMapEntry<K, V> entry(K key, V value) {
return new HollowTestDataMapEntry<>(key, value);
}
}
| 9,205 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestMapRecord.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.write.HollowMapWriteRecord;
import com.netflix.hollow.core.write.HollowWriteRecord;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import java.util.ArrayList;
import java.util.List;
public abstract class HollowTestMapRecord<T> extends HollowTestRecord<T> {
private final List<Entry<?>> entries = new ArrayList<>();
protected HollowTestMapRecord(T parent) {
super(parent);
}
protected void addEntry(Entry<? extends HollowTestRecord<?>> entry) {
entries.add(entry);
}
@SuppressWarnings({ "unchecked", "hiding" })
public <T> Entry<T> getEntry(int idx) {
return (Entry<T>) entries.get(idx);
}
public HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine) {
HollowMapWriteRecord rec = new HollowMapWriteRecord();
for(Entry<?> entry : entries) {
int keyOrdinal = entry.key.addTo(writeEngine);
int valueOrdinal = entry.value.addTo(writeEngine);
rec.addEntry(keyOrdinal, valueOrdinal);
}
return rec;
}
public static class Entry<T> extends HollowTestRecord<T> {
private HollowTestRecord<?> key;
private HollowTestRecord<?> value;
public Entry(T parent) {
super(parent);
}
protected void setKey(HollowTestRecord<?> key) {
this.key = key;
}
protected void setValue(HollowTestRecord<?> value) {
this.value = value;
}
@SuppressWarnings({ "hiding", "unchecked" })
public <T extends HollowTestRecord<?>> T getKey() {
return (T)key;
}
@SuppressWarnings({ "hiding", "unchecked" })
public <T extends HollowTestRecord<?>> T getValue() {
return (T)value;
}
@Override
protected HollowSchema getSchema() {
throw new UnsupportedOperationException();
}
@Override
protected HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine) {
throw new UnsupportedOperationException();
}
}
}
| 9,206 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/testdata/HollowTestRecord.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.testdata;
import com.netflix.hollow.core.schema.HollowListSchema;
import com.netflix.hollow.core.schema.HollowMapSchema;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSetSchema;
import com.netflix.hollow.core.write.HollowListTypeWriteState;
import com.netflix.hollow.core.write.HollowMapTypeWriteState;
import com.netflix.hollow.core.write.HollowObjectTypeWriteState;
import com.netflix.hollow.core.write.HollowSetTypeWriteState;
import com.netflix.hollow.core.write.HollowTypeWriteState;
import com.netflix.hollow.core.write.HollowWriteRecord;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
public abstract class HollowTestRecord<T> {
private final T parent;
private int assignedOrdinal = -1;
protected HollowTestRecord(T parent) {
this.parent = parent;
}
public T up() {
return parent;
}
@SuppressWarnings({ "hiding", "unchecked" })
public <T> T upTop() {
HollowTestRecord<?> root = this;
while(root.up() != null) {
root = (HollowTestRecord<?>) root.up();
}
return (T)root;
}
int addTo(HollowWriteStateEngine writeEngine) {
HollowSchema schema = getSchema();
HollowTypeWriteState typeState = writeEngine.getTypeState(schema.getName());
if(typeState == null) {
switch(schema.getSchemaType()) {
case OBJECT:
typeState = new HollowObjectTypeWriteState((HollowObjectSchema)schema);
break;
case LIST:
typeState = new HollowListTypeWriteState((HollowListSchema)schema);
break;
case SET:
typeState = new HollowSetTypeWriteState((HollowSetSchema)schema);
break;
case MAP:
typeState = new HollowMapTypeWriteState((HollowMapSchema)schema);
break;
}
writeEngine.addTypeState(typeState);
}
assignedOrdinal = typeState.add(toWriteRecord(writeEngine));
return assignedOrdinal;
}
public int getOrdinal() {
return assignedOrdinal;
}
protected abstract HollowSchema getSchema();
protected abstract HollowWriteRecord toWriteRecord(HollowWriteStateEngine writeEngine);
}
| 9,207 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/HollowProducerListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.api.producer.HollowProducer.ReadState;
import com.netflix.hollow.api.producer.listener.AnnouncementListener;
import com.netflix.hollow.api.producer.listener.CycleListener;
import com.netflix.hollow.api.producer.listener.DataModelInitializationListener;
import com.netflix.hollow.api.producer.listener.IntegrityCheckListener;
import com.netflix.hollow.api.producer.listener.PopulateListener;
import com.netflix.hollow.api.producer.listener.PublishListener;
import com.netflix.hollow.api.producer.listener.RestoreListener;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* A class should implement {@code HollowProducerListener}, if it wants to be notified on
* start/completion of various stages of the {@link HollowProducer}.
* Subclasses are encouraged to extend {@link AbstractHollowProducerListener}
*
* @author Kinesh Satiya {@literal kineshsatiya@gmail.com}.
*/
public interface HollowProducerListener extends
DataModelInitializationListener,
RestoreListener,
CycleListener,
PopulateListener,
PublishListener,
IntegrityCheckListener,
AnnouncementListener {
///////////////////////////
// DataModelInitializationListener
///////////////////////////
// Called when HollowProducer.initializeDataModel is called
@Override
default void onProducerInit(Duration elapsed) {
onProducerInit(elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after the {@code HollowProducer} has initialized its data model.
* @param elapsed the elapsed duration
* @param unit the units of duration
*/
void onProducerInit(long elapsed, TimeUnit unit);
///////////////////////////
// RestoreListener
///////////////////////////
/**
* Called after the {@code HollowProducer} has restored its data state to the indicated version.
* If previous state is not available to restore from, then this callback will not be called.
*
* @param restoreVersion Version from which the state for {@code HollowProducer} was restored.
*/
@Override
void onProducerRestoreStart(long restoreVersion);
@Override
default void onProducerRestoreComplete(com.netflix.hollow.api.producer.Status status, long versionDesired, long versionReached, Duration elapsed) {
onProducerRestoreComplete(new RestoreStatus(status, versionDesired, versionReached),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after the {@code HollowProducer} has restored its data state to the indicated version.
* If previous state is not available to restore from, then this callback will not be called.
*
* @param status of the restore. {@link RestoreStatus#getStatus()} will return {@code SUCCESS} when
* the desired version was reached during restore, otheriwse {@code FAIL} will be returned.
* @param elapsed duration of the restore in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onProducerRestoreComplete(RestoreStatus status, long elapsed, TimeUnit unit);
///////////////////////////
// CycleListener
///////////////////////////
// See also HollowProducerListenerV2.onCycleSkip
@Override
default void onCycleSkip(CycleSkipReason reason) {
}
// This is called just before onCycleStart, can the two be merged with additional arguments
/**
* Indicates that the next state produced will begin a new delta chain.
* This will be called prior to the next state being produced either if
* {@link HollowProducer#restore(long, com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever)}
* hasn't been called or the restore failed.
*
* @param version the version of the state that will become the first of a new delta chain
*/
@Override
void onNewDeltaChain(long version);
/**
* Called when the {@code HollowProducer} has begun a new cycle.
*
* @param version Version produced by the {@code HollowProducer} for new cycle about to start.
*/
@Override
void onCycleStart(long version);
@Override
default void onCycleComplete(com.netflix.hollow.api.producer.Status status, ReadState readState, long version, Duration elapsed) {
onCycleComplete(new ProducerStatus(status, readState, version),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after {@code HollowProducer} has completed a cycle normally or abnormally. A {@code SUCCESS} status indicates that the
* entire cycle was successful and the producer is available to begin another cycle.
*
* @param status ProducerStatus of this cycle. {@link ProducerStatus#getStatus()} will return {@code SUCCESS}
* when the a new data state has been announced to consumers or when there were no changes to the data; it will return @{code FAIL}
* when any stage failed or any other failure occured during the cycle.
* @param elapsed duration of the cycle in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit);
///////////////////////////
// PopulateListener
///////////////////////////
/**
* Called before starting to execute the task to populate data into Hollow.
*
* @param version Current version of the cycle
*/
@Override
void onPopulateStart(long version);
@Override
default void onPopulateComplete(com.netflix.hollow.api.producer.Status status, long version, Duration elapsed) {
onPopulateComplete(new ProducerStatus(status, version),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called once populating task stage has finished successfully or failed. Use {@code ProducerStatus#getStatus()} to get status of the task.
*
* @param status A value of {@code Success} indicates that all data was successfully populated. {@code Fail} status indicates populating hollow with data failed.
* @param elapsed Time taken to populate hollow.
* @param unit unit of {@code elapsed} duration.
*/
void onPopulateComplete(ProducerStatus status, long elapsed, TimeUnit unit);
///////////////////////////
// PublishListener
///////////////////////////
// Called after populate
// Called after populateComplete and instead of publish
// Can be merged in to PublishListener?
/**
* Called after the new state has been populated if the {@code HollowProducer} detects that no data has changed, thus no snapshot nor delta should be produced.<p>
*
* @param version Current version of the cycle.
*/
@Override
void onNoDeltaAvailable(long version);
/**
* Called when the {@code HollowProducer} has begun publishing the {@code HollowBlob}s produced this cycle.
*
* @param version Version to be published.
*/
@Override
void onPublishStart(long version);
// Called during publish start-complete cycle for each blob
// Can be merged in to PublishListener?
@Override
default void onBlobPublish(com.netflix.hollow.api.producer.Status status, HollowProducer.Blob blob, Duration elapsed) {
onArtifactPublish(new PublishStatus(status, blob),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called once a blob has been published successfully or failed to published. Use {@link PublishStatus#getBlob()} to get more details on blob type and size.
* This method is called for every {@link com.netflix.hollow.api.producer.HollowProducer.Blob.Type} that was published.
*
* @param publishStatus Status of publishing. {@link PublishStatus#getStatus()} returns {@code SUCCESS} or {@code FAIL}.
* @param elapsed time taken to publish the blob
* @param unit unit of elapsed.
*/
// TODO(hollow3): "artifact" as a term is redundant with "blob", probably don't need both. #onBlobPublish(...)?
void onArtifactPublish(PublishStatus publishStatus, long elapsed, TimeUnit unit);
@Override
default void onPublishComplete(com.netflix.hollow.api.producer.Status status, long version, Duration elapsed) {
onPublishComplete(new ProducerStatus(status, version), elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after the publish stage finishes normally or abnormally. A {@code SUCCESS} status indicates that
* the {@code HollowBlob}s produced this cycle has been published to the blob store.
*
* @param status CycleStatus of the publish stage. {@link ProducerStatus#getStatus()} will return {@code SUCCESS}
* when the publish was successful; @{code FAIL} otherwise.
* @param elapsed duration of the publish stage in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onPublishComplete(ProducerStatus status, long elapsed, TimeUnit unit);
///////////////////////////
// IntegrityCheckListener
///////////////////////////
// This is effectively a validator that is executed before any other validators
// Called after publish start-complete cycle
/**
* Called when the {@code HollowProducer} has begun checking the integrity of the {@code HollowBlob}s produced this cycle.
*
* @param version Version to be checked
*/
@Override
void onIntegrityCheckStart(long version);
@Override
default void onIntegrityCheckComplete(com.netflix.hollow.api.producer.Status status, ReadState readState, long version, Duration elapsed) {
onIntegrityCheckComplete(new ProducerStatus(status, readState, version),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after the integrity check stage finishes normally or abnormally. A {@code SUCCESS} status indicates that
* the previous snapshot, current snapshot, delta, and reverse-delta {@code HollowBlob}s are all internally consistent.
*
* @param status CycleStatus of the integrity check stage. {@link ProducerStatus#getStatus()} will return {@code SUCCESS}
* when the blobs are internally consistent; @{code FAIL} otherwise.
* @param elapsed duration of the integrity check stage in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onIntegrityCheckComplete(ProducerStatus status, long elapsed, TimeUnit unit);
///////////////////////////
///////////////////////////
// See also HollowValidationListener (deprecated) and Validators.ValidationStatusListener
// Called after integrity check cycle
// Validators will be called during the validation start-complete cycle
/**
* Called when the {@code HollowProducer} has begun validating the new data state produced this cycle.
*
* @param version Version to be validated
*/
void onValidationStart(long version);
/**
* Called after the validation stage finishes normally or abnormally. A {@code SUCCESS} status indicates that
* the newly published data state is considered valid.
*
* @param status CycleStatus of the publish stage. {@link ProducerStatus#getStatus()} will return {@code SUCCESS}
* when the publish was successful; @{code FAIL} otherwise.
* @param elapsed duration of the validation stage in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onValidationComplete(ProducerStatus status, long elapsed, TimeUnit unit);
///////////////////////////
// AnnouncementListener
///////////////////////////
// Called after a successful validation start-complete cycle
/**
* Called when the {@code HollowProducer} has begun announcing the {@code HollowBlob} published this cycle.
*
* @param version of {@code HollowBlob} that will be announced.
*/
@Override
void onAnnouncementStart(long version);
@Override
default void onAnnouncementComplete(com.netflix.hollow.api.producer.Status status, ReadState readState, long version, Duration elapsed) {
onAnnouncementComplete(new ProducerStatus(status, readState, version),
elapsed.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Called after the announcement stage finishes normally or abnormally. A {@code SUCCESS} status indicates
* that the {@code HollowBlob} published this cycle has been announced to consumers.
*
* @param status CycleStatus of the announcement stage. {@link ProducerStatus#getStatus()} will return {@code SUCCESS}
* when the announce was successful; @{code FAIL} otherwise.
* @param elapsed duration of the announcement stage in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
void onAnnouncementComplete(ProducerStatus status, long elapsed, TimeUnit unit);
/**
* This class represents information on details when {@link HollowProducer} has finished executing a particular stage.
* An instance of this class is provided on different events of {@link HollowProducerListener}.
*
* @author Kinesh Satiya {@literal kineshsatiya@gmail.com}
*/
class ProducerStatus {
private final long version;
private final Status status;
private final Throwable throwable;
private final HollowProducer.ReadState readState;
ProducerStatus(com.netflix.hollow.api.producer.Status s, long version) {
this(s, null, version);
}
ProducerStatus(com.netflix.hollow.api.producer.Status s, ReadState readState, long version) {
this.status = Status.of(s.getType());
this.throwable = s.getCause();
this.readState = readState;
this.version = version;
}
ProducerStatus(Status status, Throwable throwable, long version, HollowProducer.ReadState readState) {
this.status = status;
this.version = version;
this.readState = readState;
this.throwable = throwable;
}
/**
* This version is currently under process by {@code HollowProducer}.
*
* @return Current version of the {@code HollowProducer}.
*/
public long getVersion() {
return version;
}
/**
* Status of the latest stage completed by {@code HollowProducer}.
*
* @return SUCCESS or FAIL.
*/
public Status getStatus() {
return status;
}
/**
* Returns the failure cause if this status represents a {@code HollowProducer} failure that was caused by an exception.
*
* @return Throwable if {@code Status.equals(FAIL)} else null.
*/
public Throwable getCause() {
return throwable;
}
/**
* Returns the resulting read state engine after adding new data into write state engine.
*
* @return Resulting read state engine only if data is added successfully else null.
*/
public ReadState getReadState() {
return readState;
}
}
/**
* This class represents information on details when {@link HollowProducer} has finished executing a particular stage.
* An instance of this class is provided on different events of {@link HollowProducerListener}.
*
* @author Tim Taylor {@literal tim@toolbear.io}
*/
class RestoreStatus {
private final Status status;
private final long versionDesired;
private final long versionReached;
private final Throwable throwable;
RestoreStatus(com.netflix.hollow.api.producer.Status s, long versionDesired, long versionReached) {
this.status = Status.of(s.getType());
this.throwable = s.getCause();
this.versionDesired = versionDesired;
this.versionReached = versionReached;
}
/**
* The version desired to restore to when calling
* {@link HollowProducer#restore(long, com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever)}
*
* @return the latest announced version or {@code HollowConstants.VERSION_NONE} if latest announced version couldn't be
* retrieved
*/
public long getDesiredVersion() {
return versionDesired;
}
/**
* The version reached when restoring.
* When {@link HollowProducer#restore(long, com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever)}
* succeeds then {@code versionDesired == versionReached} is always true. Can be {@code HollowConstants.VERSION_NONE}
* indicating restore failed to reach any state, or the version of an intermediate state reached.
*
* @return the version restored to when successful, otherwise {@code HollowConstants.VERSION_NONE} if no version was
* reached or the version of an intermediate state reached before restore completed unsuccessfully.
*/
public long getVersionReached() {
return versionReached;
}
/**
* Status of the restore
*
* @return SUCCESS or FAIL.
*/
public Status getStatus() {
return status;
}
/**
* Returns the failure cause if this status represents a {@code HollowProducer} failure that was caused by an exception.
*
* @return the {@code Throwable} cause of a failure, otherwise {@code null} if restore succeeded or it failed
* without an exception.
*/
public Throwable getCause() {
return throwable;
}
}
class PublishStatus {
private final Status status;
private final HollowProducer.Blob blob;
private final Throwable throwable;
PublishStatus(com.netflix.hollow.api.producer.Status s, HollowProducer.Blob blob) {
this.status = Status.of(s.getType());
this.throwable = s.getCause();
this.blob = blob;
}
/**
* Status to indicate if publishing was successful or failed.
*
* @return {@code Success} or {@code Fail}
*/
public Status getStatus() {
return status;
}
/**
* An instance of {@code Blob} has methods to get details on type of blob, size, from and to version.
*
* @return Blob that was published.
*/
public HollowProducer.Blob getBlob() {
return blob;
}
/**
* @return Throwable that contains the error cause if publishing failed.
*/
public Throwable getCause() {
return throwable;
}
}
enum Status {
SUCCESS, FAIL,
// This is currently only used to report skipping of a validator
// with SingleValidationStatusBuilder and SingleValidationStatus
@Deprecated
SKIP;
static Status of(com.netflix.hollow.api.producer.Status.StatusType st) {
return st == com.netflix.hollow.api.producer.Status.StatusType.SUCCESS
? Status.SUCCESS
: Status.FAIL;
}
static com.netflix.hollow.api.producer.Status.StatusType from(Status s) {
return s == Status.SUCCESS
? com.netflix.hollow.api.producer.Status.StatusType.SUCCESS
: com.netflix.hollow.api.producer.Status.StatusType.FAIL;
}
}
} | 9,208 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/CloseableIncrementalWriteState.java | package com.netflix.hollow.api.producer;
import static com.netflix.hollow.api.producer.HollowIncrementalCyclePopulator.AddIfAbsent;
import static com.netflix.hollow.api.producer.HollowIncrementalCyclePopulator.DELETE_RECORD;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecord;
import java.util.concurrent.ConcurrentHashMap;
// @@@ Move into HollowIncrementalCyclePopulator since the event map is a shared resource
// HollowIncrementalCyclePopulator constructed from the write state instance
final class CloseableIncrementalWriteState implements HollowProducer.Incremental.IncrementalWriteState, AutoCloseable {
private final ConcurrentHashMap<RecordPrimaryKey, Object> events;
private final HollowObjectMapper objectMapper;
private volatile boolean closed;
public CloseableIncrementalWriteState(
ConcurrentHashMap<RecordPrimaryKey, Object> events,
HollowObjectMapper objectMapper) {
this.events = events;
this.objectMapper = objectMapper;
}
@Override
public void addOrModify(Object o) {
ensureNotClosed();
events.put(getKey(o), o);
}
@Override
public void addIfAbsent(Object o) {
ensureNotClosed();
events.putIfAbsent(getKey(o), new AddIfAbsent(o));
}
@Override
public void delete(Object o) {
delete(getKey(o));
}
@Override
public void delete(RecordPrimaryKey key) {
ensureNotClosed();
// @@@ Deletion is silently ignored if no object exists for the key
events.put(key, DELETE_RECORD);
}
private RecordPrimaryKey getKey(Object o) {
if (o instanceof FlatRecord) {
FlatRecord fr = (FlatRecord) o;
return fr.getRecordPrimaryKey();
} else {
return objectMapper.extractPrimaryKey(o);
}
}
private void ensureNotClosed() {
if (closed) {
throw new IllegalStateException(
"Write state operated on after the incremental population stage of a cycle");
}
}
@Override public void close() {
closed = true;
}
}
| 9,209 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/Status.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import java.time.Duration;
/**
* A status representing success or failure for a particular producer action.
*/
public final class Status {
final StatusType type;
final Throwable cause;
public Status(StatusType type, Throwable cause) {
this.type = type;
this.cause = cause;
}
/**
* The status type.
*/
public enum StatusType {
/**
* If the producer action was successful.
*/
SUCCESS,
/**
* If the producer action failed.
*/
FAIL;
}
/**
* Gets the status type
*
* @return the status type
*/
public StatusType getType() {
return type;
}
/**
* Returns the cause of producer action failure.
*
* @return the cause of producer action failure
*/
public Throwable getCause() {
return cause;
}
abstract static class AbstractStatusBuilder<T extends AbstractStatusBuilder<T>> {
StatusType type;
Throwable cause;
long start;
long end;
AbstractStatusBuilder() {
start = System.currentTimeMillis();
}
@SuppressWarnings("unchecked")
T success() {
this.type = StatusType.SUCCESS;
return (T) this;
}
@SuppressWarnings("unchecked")
T fail(Throwable cause) {
this.type = StatusType.FAIL;
this.cause = cause;
return (T) this;
}
Status build() {
end = System.currentTimeMillis();
return new Status(type, cause);
}
Duration elapsed() {
return Duration.ofMillis(end - start);
}
}
static final class StageBuilder extends AbstractStatusBuilder<StageBuilder> {
long version;
StageBuilder version(long version) {
this.version = version;
return this;
}
}
static final class StageWithStateBuilder extends AbstractStatusBuilder<StageWithStateBuilder> {
HollowProducer.ReadState readState;
long version;
StageWithStateBuilder readState(HollowProducer.ReadState readState) {
this.readState = readState;
return version(readState.getVersion());
}
StageWithStateBuilder version(long version) {
this.version = version;
return this;
}
}
static final class IncrementalPopulateBuilder extends AbstractStatusBuilder<PublishBuilder> {
long version;
long removed;
long addedOrModified;
IncrementalPopulateBuilder version(long version) {
this.version = version;
return this;
}
IncrementalPopulateBuilder changes(long removed, long addedOrModified) {
this.removed = removed;
this.addedOrModified = addedOrModified;
return this;
}
}
static final class PublishBuilder extends AbstractStatusBuilder<PublishBuilder> {
HollowProducer.Blob blob;
PublishBuilder blob(HollowProducer.Blob blob) {
this.blob = blob;
return this;
}
}
static final class RestoreStageBuilder extends AbstractStatusBuilder<RestoreStageBuilder> {
long versionDesired;
long versionReached;
RestoreStageBuilder versions(long versionDesired, long versionReached) {
this.versionDesired = versionDesired;
this.versionReached = versionReached;
return this;
}
}
}
| 9,210 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/AbstractHollowProducer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import static com.netflix.hollow.api.producer.ProducerListenerSupport.ProducerListeners;
import static java.lang.System.currentTimeMillis;
import static java.util.stream.Collectors.toList;
import com.netflix.hollow.api.consumer.HollowConsumer;
import com.netflix.hollow.api.metrics.HollowMetricsCollector;
import com.netflix.hollow.api.metrics.HollowProducerMetrics;
import com.netflix.hollow.api.producer.enforcer.BasicSingleProducerEnforcer;
import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer;
import com.netflix.hollow.api.producer.fs.HollowFilesystemBlobStager;
import com.netflix.hollow.api.producer.listener.CycleListener;
import com.netflix.hollow.api.producer.listener.HollowProducerEventListener;
import com.netflix.hollow.api.producer.validation.ValidationResult;
import com.netflix.hollow.api.producer.validation.ValidationStatus;
import com.netflix.hollow.api.producer.validation.ValidationStatusException;
import com.netflix.hollow.api.producer.validation.ValidatorListener;
import com.netflix.hollow.core.HollowConstants;
import com.netflix.hollow.core.HollowStateEngine;
import com.netflix.hollow.core.read.HollowBlobInput;
import com.netflix.hollow.core.read.engine.HollowBlobHeaderReader;
import com.netflix.hollow.core.read.engine.HollowBlobReader;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSchemaHash;
import com.netflix.hollow.core.util.HollowObjectHashCodeFinder;
import com.netflix.hollow.core.util.HollowWriteStateCreator;
import com.netflix.hollow.core.write.HollowBlobWriter;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey;
import com.netflix.hollow.tools.checksum.HollowChecksum;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.logging.Level;
import java.util.logging.Logger;
abstract class AbstractHollowProducer {
static final long DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE = 16L * 1024L * 1024L;
// An announcement metadata tag indicating the approx heap footprint of the corresponding read state engine
private static final String ANNOUNCE_TAG_HEAP_FOOTPRINT = "hollow.data.size.heap.bytes.approx";
final Logger log = Logger.getLogger(AbstractHollowProducer.class.getName());
final HollowProducer.BlobStager blobStager;
final HollowProducer.Publisher publisher;
final HollowProducer.Announcer announcer;
final HollowProducer.BlobStorageCleaner blobStorageCleaner;
HollowObjectMapper objectMapper;
final HollowProducer.VersionMinter versionMinter;
final ProducerListenerSupport listeners;
ReadStateHelper readStates;
final Executor snapshotPublishExecutor;
final int numStatesBetweenSnapshots;
int numStatesUntilNextSnapshot;
HollowProducerMetrics metrics;
HollowMetricsCollector<HollowProducerMetrics> metricsCollector;
final SingleProducerEnforcer singleProducerEnforcer;
long lastSuccessfulCycle = 0;
final HollowObjectHashCodeFinder hashCodeFinder;
final boolean doIntegrityCheck;
// Count to track number of cycles run by a primary producer. In the future, this can be useful in determining stickiness of a
// producer instance.
int cycleCountSincePrimaryStatus = 0;
boolean isInitialized;
@Deprecated
public AbstractHollowProducer(
HollowProducer.Publisher publisher,
HollowProducer.Announcer announcer) {
this(new HollowFilesystemBlobStager(), publisher, announcer,
Collections.emptyList(),
new VersionMinterWithCounter(), null, 0,
DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE, false, null,
new DummyBlobStorageCleaner(), new BasicSingleProducerEnforcer(),
null, true);
}
// The only constructor should be that which accepts a builder
// This ensures that if the builder modified to include new state that
// extended builders will not require modification to pass on that new state
AbstractHollowProducer(HollowProducer.Builder<?> b) {
this(b.stager, b.publisher, b.announcer,
b.eventListeners,
b.versionMinter, b.snapshotPublishExecutor,
b.numStatesBetweenSnapshots, b.targetMaxTypeShardSize, b.focusHoleFillInFewestShards,
b.metricsCollector, b.blobStorageCleaner, b.singleProducerEnforcer,
b.hashCodeFinder, b.doIntegrityCheck);
}
private AbstractHollowProducer(
HollowProducer.BlobStager blobStager,
HollowProducer.Publisher publisher,
HollowProducer.Announcer announcer,
List<? extends HollowProducerEventListener> eventListeners,
HollowProducer.VersionMinter versionMinter,
Executor snapshotPublishExecutor,
int numStatesBetweenSnapshots,
long targetMaxTypeShardSize,
boolean focusHoleFillInFewestShards,
HollowMetricsCollector<HollowProducerMetrics> metricsCollector,
HollowProducer.BlobStorageCleaner blobStorageCleaner,
SingleProducerEnforcer singleProducerEnforcer,
HollowObjectHashCodeFinder hashCodeFinder,
boolean doIntegrityCheck) {
this.publisher = publisher;
this.announcer = announcer;
this.versionMinter = versionMinter;
this.blobStager = blobStager;
this.singleProducerEnforcer = singleProducerEnforcer;
this.snapshotPublishExecutor = snapshotPublishExecutor;
this.numStatesBetweenSnapshots = numStatesBetweenSnapshots;
this.hashCodeFinder = hashCodeFinder;
this.doIntegrityCheck = doIntegrityCheck;
HollowWriteStateEngine writeEngine = hashCodeFinder == null
? new HollowWriteStateEngine()
: new HollowWriteStateEngine(hashCodeFinder);
writeEngine.setTargetMaxTypeShardSize(targetMaxTypeShardSize);
writeEngine.setFocusHoleFillInFewestShards(focusHoleFillInFewestShards);
this.objectMapper = new HollowObjectMapper(writeEngine);
if (hashCodeFinder != null) {
objectMapper.doNotUseDefaultHashKeys();
}
this.readStates = ReadStateHelper.newDeltaChain();
this.blobStorageCleaner = blobStorageCleaner;
this.listeners = new ProducerListenerSupport(eventListeners.stream().distinct().collect(toList()));
this.metrics = new HollowProducerMetrics();
this.metricsCollector = metricsCollector;
}
/**
* @return the metrics for this producer
*/
public HollowProducerMetrics getMetrics() {
return this.metrics;
}
/**
* Initializes the data model for the given classes.
* <p>
* Data model initialization is required prior to {@link #restore(long, HollowConsumer.BlobRetriever) restoring}
* the producer.
* This ensures that restoration can correctly compare the producer's current data model
* with the data model of the restored data state and manage any differences in those models
* (such as not restoring state for any types in the restoring data model not present in the
* producer's current data model).
* <p>
* After initialization a data model initialization event will be emitted
* to all registered data model initialization listeners
* {@link com.netflix.hollow.api.producer.listener.DataModelInitializationListener listeners}.
*
* @param classes the data model classes
* @throws IllegalArgumentException if {@code classes} is empty
* @see #restore(long, HollowConsumer.BlobRetriever)
*/
public void initializeDataModel(Class<?>... classes) {
Objects.requireNonNull(classes);
if (classes.length == 0) {
throw new IllegalArgumentException("classes is empty");
}
long start = currentTimeMillis();
for (Class<?> c : classes) {
objectMapper.initializeTypeState(c);
}
listeners.listeners().fireProducerInit(currentTimeMillis() - start);
isInitialized = true;
}
/**
* Initializes the producer data model for the given schemas.
* <p>
* Data model initialization is required prior to {@link #restore(long, HollowConsumer.BlobRetriever) restoring}
* the producer.
* This ensures that restoration can correctly compare the producer's current data model
* with the data model of the restored data state and manage any differences in those models
* (such as not restoring state for any types in the restoring data model not present in the
* producer's current data model).
* <p>
* After initialization a data model initialization event will be emitted
* to all registered data model initialization listeners
* {@link com.netflix.hollow.api.producer.listener.DataModelInitializationListener listeners}.
*
* @param schemas the data model classes
* @throws IllegalArgumentException if {@code schemas} is empty
* @see #restore(long, HollowConsumer.BlobRetriever)
*/
public void initializeDataModel(HollowSchema... schemas) {
Objects.requireNonNull(schemas);
if (schemas.length == 0) {
throw new IllegalArgumentException("classes is empty");
}
long start = currentTimeMillis();
HollowWriteStateCreator.populateStateEngineWithTypeWriteStates(getWriteEngine(), Arrays.asList(schemas));
listeners.listeners().fireProducerInit(currentTimeMillis() - start);
isInitialized = true;
}
/**
* Restores the data state to a desired version.
* <p>
* Data model {@link #initializeDataModel(Class[]) initialization} is required prior to
* restoring the producer. This ensures that restoration can correctly compare the producer's
* current data model with the data model of the restored data state and manage any differences
* in those models (such as not restoring state for any types in the restoring data model not
* present in the producer's current data model)
*
* @param versionDesired the desired version
* @param blobRetriever the blob retriever
* @return the read state of the restored state
* @throws IllegalStateException if the producer's data model has not been initialized
* @see #initializeDataModel(Class[])
*/
public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) {
return restore(versionDesired, blobRetriever,
(restoreFrom, restoreTo) -> restoreTo.restoreFrom(restoreFrom));
}
HollowProducer.ReadState hardRestore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) {
return restore(versionDesired, blobRetriever,
(restoreFrom, restoreTo) -> HollowWriteStateCreator.
populateUsingReadEngine(restoreTo, restoreFrom, false));
}
private HollowProducer.ReadState restore(
long versionDesired, HollowConsumer.BlobRetriever blobRetriever,
BiConsumer<HollowReadStateEngine, HollowWriteStateEngine> restoreAction) {
Objects.requireNonNull(blobRetriever);
Objects.requireNonNull(restoreAction);
if (!isInitialized) {
throw new IllegalStateException(
"You must initialize the data model of a HollowProducer with producer.initializeDataModel(...) prior to restoring");
}
HollowProducer.ReadState readState = null;
ProducerListeners localListeners = listeners.listeners();
Status.RestoreStageBuilder status = localListeners.fireProducerRestoreStart(versionDesired);
try {
if (versionDesired != HollowConstants.VERSION_NONE) {
HollowConsumer client = HollowConsumer.withBlobRetriever(blobRetriever).build();
client.triggerRefreshTo(versionDesired);
readState = ReadStateHelper.newReadState(client.getCurrentVersionId(), client.getStateEngine());
readStates = ReadStateHelper.restored(readState);
// Need to restore data to new ObjectMapper since can't restore to non empty Write State Engine
Collection<HollowSchema> schemas = objectMapper.getStateEngine().getSchemas();
HollowWriteStateEngine writeEngine = hashCodeFinder == null
? new HollowWriteStateEngine()
: new HollowWriteStateEngine(hashCodeFinder);
HollowWriteStateCreator.populateStateEngineWithTypeWriteStates(writeEngine, schemas);
HollowObjectMapper newObjectMapper = new HollowObjectMapper(writeEngine);
if (hashCodeFinder != null) {
newObjectMapper.doNotUseDefaultHashKeys();
}
restoreAction.accept(readStates.current().getStateEngine(), writeEngine);
status.versions(versionDesired, readState.getVersion())
.success();
objectMapper = newObjectMapper; // Restore completed successfully so swap
}
} catch (Throwable th) {
status.fail(th);
throw th;
} finally {
localListeners.fireProducerRestoreComplete(status);
}
return readState;
}
public HollowWriteStateEngine getWriteEngine() {
return objectMapper.getStateEngine();
}
public HollowObjectMapper getObjectMapper() {
return objectMapper;
}
/**
* Invoke this method to alter runCycle behavior. If this Producer is not primary, runCycle is a no-op. Note that by default,
* SingleProducerEnforcer is instantiated as BasicSingleProducerEnforcer, which is initialized to return true for isPrimary()
*
* @param doEnable true if enable primary producer, if false
* @return true if the intended action was successful
*/
public boolean enablePrimaryProducer(boolean doEnable) {
if (!singleProducerEnforcer.isPrimary()) {
cycleCountSincePrimaryStatus = 0;
}
if (doEnable) {
singleProducerEnforcer.enable();
} else {
singleProducerEnforcer.disable();
}
return (singleProducerEnforcer.isPrimary() == doEnable);
}
long runCycle(HollowProducer.Incremental.IncrementalPopulator incrementalPopulator, HollowProducer.Populator populator) {
ProducerListeners localListeners = listeners.listeners();
if (!singleProducerEnforcer.isPrimary()) {
// TODO: minimum time spacing between cycles
log.log(Level.INFO, "cycle not executed -- not primary (aka leader)");
localListeners.fireCycleSkipped(CycleListener.CycleSkipReason.NOT_PRIMARY_PRODUCER);
cycleCountSincePrimaryStatus = 0;
return lastSuccessfulCycle;
}
long toVersion = versionMinter.mint();
if (!readStates.hasCurrent()) {
localListeners.fireNewDeltaChain(toVersion);
}
Status.StageWithStateBuilder cycleStatus = localListeners.fireCycleStart(toVersion);
try {
return runCycle(localListeners, incrementalPopulator, populator, cycleStatus, toVersion);
} finally {
localListeners.fireCycleComplete(cycleStatus);
metrics.updateCycleMetrics(cycleStatus.build(), cycleStatus.readState, cycleStatus.version);
if (metricsCollector != null) {
metricsCollector.collect(metrics);
}
}
}
long runCycle(
ProducerListeners listeners,
HollowProducer.Incremental.IncrementalPopulator incrementalPopulator, HollowProducer.Populator populator,
Status.StageWithStateBuilder cycleStatus, long toVersion) {
// 1. Begin a new cycle
Artifacts artifacts = new Artifacts();
HollowWriteStateEngine writeEngine = getWriteEngine();
try {
// 1a. Prepare the write state
writeEngine.prepareForNextCycle();
// save timestamp in ms of when cycle starts
writeEngine.addHeaderTag(HollowStateEngine.HEADER_TAG_METRIC_CYCLE_START, String.valueOf(System.currentTimeMillis()));
// 2. Populate the state
populate(listeners, incrementalPopulator, populator, toVersion);
// 3. Produce a new state if there's work to do
if (writeEngine.hasChangedSinceLastCycle()) {
writeEngine.addHeaderTag(HollowStateEngine.HEADER_TAG_SCHEMA_HASH, new HollowSchemaHash(writeEngine.getSchemas()).getHash());
boolean schemaChangedFromPriorVersion = readStates.hasCurrent() &&
!writeEngine.hasIdenticalSchemas(readStates.current().getStateEngine());
if (schemaChangedFromPriorVersion) {
writeEngine.addHeaderTag(HollowStateEngine.HEADER_TAG_SCHEMA_CHANGE, Boolean.TRUE.toString());
} else {
writeEngine.getHeaderTags().remove(HollowStateEngine.HEADER_TAG_SCHEMA_CHANGE);
}
writeEngine.addHeaderTag(HollowStateEngine.HEADER_TAG_PRODUCER_TO_VERSION, String.valueOf(toVersion));
// 3a. Publish, run checks & validation, then announce new state consumers
publish(listeners, toVersion, artifacts);
ReadStateHelper candidate = readStates.roundtrip(toVersion);
cycleStatus.readState(candidate.pending());
candidate = doIntegrityCheck ?
checkIntegrity(listeners, candidate, artifacts, schemaChangedFromPriorVersion) :
noIntegrityCheck(candidate, artifacts);
try {
validate(listeners, candidate.pending());
announce(listeners, candidate.pending());
readStates = candidate.commit();
cycleStatus.readState(readStates.current()).success();
} catch (Throwable th) {
if (artifacts.hasReverseDelta()) {
applyDelta(artifacts.reverseDelta, candidate.pending().getStateEngine());
readStates = candidate.rollback();
}
throw th;
}
lastSuccessfulCycle = toVersion;
} else {
// 3b. Nothing to do; reset the effects of Step 2
// Return the lastSucessfulCycle to the caller thereby
// the callee can track that version against consumers
// without having to listen to events.
// Consistently report the version that would be used if
// data had been published for the events. This
// is for consistency in tracking
writeEngine.resetToLastPrepareForNextCycle();
cycleStatus.success();
listeners.fireNoDelta(toVersion);
log.info("Populate stage completed with no delta in output state; skipping publish, announce, etc.");
}
} catch (Throwable th) {
try {
writeEngine.resetToLastPrepareForNextCycle();
} catch (Throwable innerTh) {
log.log(Level.SEVERE, "resetToLastPrepareForNextCycle encountered an exception when attempting recovery:", innerTh);
// swallow the inner throwable to preserve the original
}
cycleStatus.fail(th);
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
}
throw new RuntimeException(th);
} finally {
artifacts.cleanup();
cycleCountSincePrimaryStatus ++;
}
return lastSuccessfulCycle;
}
/**
* Adds a listener to this producer.
* <p>
* If the listener was previously added to this consumer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is added, concurrently, during the occurrence of a cycle or restore then the listener will not
* receive events until the next cycle or restore. The listener may also be removed concurrently.
*
* @param listener the listener to add
*/
public void addListener(HollowProducerListener listener) {
listeners.addListener(listener);
}
/**
* Adds a listener to this producer.
* <p>
* If the listener was previously added to this consumer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is added, concurrently, during the occurrence of a cycle or restore then the listener will not
* receive events until the next cycle or restore. The listener may also be removed concurrently.
*
* @param listener the listener to add
*/
public void addListener(HollowProducerEventListener listener) {
listeners.addListener(listener);
}
/**
* Removes a listener to this producer.
* <p>
* If the listener was not previously added to this producer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is removed, concurrently, during the occurrence of a cycle or restore then the listener will
* receive all events for that cycle or restore but not receive events for a subsequent cycle or restore.
*
* @param listener the listener to remove
*/
public void removeListener(HollowProducerListener listener) {
listeners.removeListener(listener);
}
/**
* Removes a listener to this producer.
* <p>
* If the listener was not previously added to this producer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is removed, concurrently, during the occurrence of a cycle or restore then the listener will
* receive all events for that cycle or restore but not receive events for a subsequent cycle or restore.
*
* @param listener the listener to remove
*/
public void removeListener(HollowProducerEventListener listener) {
listeners.removeListener(listener);
}
void populate(
ProducerListeners listeners,
HollowProducer.Incremental.IncrementalPopulator incrementalPopulator, HollowProducer.Populator populator,
long toVersion) throws Exception {
assert incrementalPopulator != null ^ populator != null;
Status.StageBuilder populateStatus = listeners.firePopulateStart(toVersion);
try {
if (incrementalPopulator != null) {
// Incremental population is a sub-stage of the population stage
// This ensures good integration with existing population listeners if this sub-stage fails
// then the population stage will fail
populator = incrementalPopulate(listeners, incrementalPopulator, toVersion);
}
try (CloseableWriteState writeState = new CloseableWriteState(toVersion, objectMapper,
readStates.current())) {
populator.populate(writeState);
populateStatus.success();
}
} catch (Throwable th) {
populateStatus.fail(th);
throw th;
} finally {
listeners.firePopulateComplete(populateStatus);
}
}
HollowProducer.Populator incrementalPopulate(
ProducerListeners listeners,
HollowProducer.Incremental.IncrementalPopulator incrementalPopulator,
long toVersion) throws Exception {
ConcurrentHashMap<RecordPrimaryKey, Object> events = new ConcurrentHashMap<>();
Status.IncrementalPopulateBuilder incrementalPopulateStatus = listeners.fireIncrementalPopulateStart(toVersion);
try (CloseableIncrementalWriteState iws = new CloseableIncrementalWriteState(events, getObjectMapper())) {
incrementalPopulator.populate(iws);
incrementalPopulateStatus.success();
long removed = events.values().stream()
.filter(o -> o == HollowIncrementalCyclePopulator.DELETE_RECORD).count();
long addedOrModified = events.size() - removed;
incrementalPopulateStatus.changes(removed, addedOrModified);
} catch (Throwable th) {
incrementalPopulateStatus.fail(th);
throw th;
} finally {
listeners.fireIncrementalPopulateComplete(incrementalPopulateStatus);
}
return new HollowIncrementalCyclePopulator(events, 1.0);
}
/*
* Publish the write state, storing the artifacts in the provided object. Visible for testing.
*/
void publish(ProducerListeners listeners, long toVersion, Artifacts artifacts) throws IOException {
Status.StageBuilder psb = listeners.firePublishStart(toVersion);
try {
// We want a header to be created for all states.
artifacts.header = blobStager.openHeader(toVersion);
if(!readStates.hasCurrent() || doIntegrityCheck || numStatesUntilNextSnapshot <= 0)
artifacts.snapshot = stageBlob(listeners, blobStager.openSnapshot(toVersion));
publishHeaderBlob(artifacts.header);
if (readStates.hasCurrent()) {
artifacts.delta = stageBlob(listeners,
blobStager.openDelta(readStates.current().getVersion(), toVersion));
artifacts.reverseDelta = stageBlob(listeners,
blobStager.openReverseDelta(toVersion, readStates.current().getVersion()));
publishBlob(listeners, artifacts.delta);
publishBlob(listeners, artifacts.reverseDelta);
if (--numStatesUntilNextSnapshot < 0) {
if (snapshotPublishExecutor == null) {
publishBlob(listeners, artifacts.snapshot);
artifacts.markSnapshotPublishComplete();
} else {
// Submit the publish blob task to the executor
publishSnapshotBlobAsync(listeners, artifacts);
}
numStatesUntilNextSnapshot = numStatesBetweenSnapshots;
} else {
artifacts.markSnapshotPublishComplete();
}
} else {
publishBlob(listeners, artifacts.snapshot);
artifacts.markSnapshotPublishComplete();
numStatesUntilNextSnapshot = numStatesBetweenSnapshots;
}
psb.success();
} catch (Throwable throwable) {
psb.fail(throwable);
throw throwable;
} finally {
listeners.firePublishComplete(psb);
}
}
private HollowProducer.Blob stageBlob(ProducerListeners listeners, HollowProducer.Blob blob)
throws IOException {
Status.PublishBuilder builder = new Status.PublishBuilder();
HollowBlobWriter writer = new HollowBlobWriter(getWriteEngine());
try {
builder.blob(blob);
blob.write(writer);
builder.success();
return blob;
} catch (Throwable t) {
builder.fail(t);
throw t;
} finally {
listeners.fireBlobStage(builder);
}
}
private void publishBlob(ProducerListeners listeners, HollowProducer.Blob blob) {
Status.PublishBuilder builder = new Status.PublishBuilder();
try {
builder.blob(blob);
if (!blob.type.equals(HollowProducer.Blob.Type.SNAPSHOT)) {
// Don't allow producer to enable/disable between validating primary status and publishing for delta
// or reverse delta blobs. No need to check for primary status when publishing snapshots because a
// snapshot publish by a non-primary producer would be harmless, and the wasted effort is justified
// by the shorter wait for a call to release the primary status when artifacts are being published.
try {
singleProducerEnforcer.lock();
if (!singleProducerEnforcer.isPrimary()) {
// This situation can arise when the producer is asked to relinquish primary status mid-cycle.
// If this non-primary producer is allowed to publish a delta or reverse delta then a different
// producer instance could have been running concurrently as primary and that could break the delta chain.
log.log(Level.INFO,
"Publish failed because current producer is not primary (aka leader)");
throw new HollowProducer.NotPrimaryMidCycleException("Publish failed primary (aka leader) check");
}
publishBlob(blob);
} finally {
singleProducerEnforcer.unlock();
}
} else {
publishBlob(blob);
}
builder.success();
} catch (Throwable t) {
builder.fail(t);
throw t;
} finally {
listeners.fireBlobPublish(builder);
metrics.updateBlobTypeMetrics(builder.build(), blob);
if (metricsCollector != null) {
metricsCollector.collect(metrics);
}
}
}
private void publishSnapshotBlobAsync(ProducerListeners listeners, Artifacts artifacts) {
HollowProducer.Blob blob = artifacts.snapshot;
CompletableFuture<HollowProducer.Blob> cf = new CompletableFuture<>();
try {
snapshotPublishExecutor.execute(() -> {
Status.StageBuilder builder = new Status.StageBuilder();
try {
publishBlob(blob);
builder.success();
// Any dependent task that needs access to the blob contents should
// not execute asynchronously otherwise the blob will be cleaned up
cf.complete(blob);
} catch (Throwable t) {
builder.fail(t);
cf.completeExceptionally(t);
throw t;
} finally {
metrics.updateBlobTypeMetrics(builder.build(), blob);
if (metricsCollector != null) {
metricsCollector.collect(metrics);
}
}
artifacts.markSnapshotPublishComplete();
});
} catch (Throwable t) {
cf.completeExceptionally(t);
metrics.updateBlobTypeMetrics(new Status.StageBuilder().fail(t).build(), blob);
if (metricsCollector != null) {
metricsCollector.collect(metrics);
}
throw t;
} finally {
listeners.fireBlobPublishAsync(cf);
}
}
private void publishBlob(HollowProducer.Blob b) {
try {
publisher.publish((HollowProducer.PublishArtifact)b);
} finally {
blobStorageCleaner.clean(b.getType());
}
}
private void publishHeaderBlob(HollowProducer.HeaderBlob b) {
try {
HollowBlobWriter writer = new HollowBlobWriter(getWriteEngine());
b.write(writer);
publisher.publish(b);
} catch (IOException e){
throw new RuntimeException(e);
}
}
/**
* Given these read states
*
* * S(cur) at the currently announced version
* * S(pnd) = empty read state
*
* 1. Read in the snapshot artifact to initialize S(pnd)
* 2. Ensure that:
* - S(cur).apply(forwardDelta).checksum == S(pnd).checksum
* - S(pnd).apply(reverseDelta).checksum == S(cur).checksum
*
* @return S(cur) and S(pnd)
*/
private ReadStateHelper checkIntegrity(
ProducerListeners listeners, ReadStateHelper readStates, Artifacts artifacts,
boolean schemaChangedFromPriorVersion) throws Exception {
Status.StageWithStateBuilder status = listeners.fireIntegrityCheckStart(readStates.pending());
try {
ReadStateHelper result = readStates;
HollowReadStateEngine pending = readStates.pending().getStateEngine();
readSnapshot(artifacts.snapshot, pending);
if (readStates.hasCurrent()) {
HollowReadStateEngine current = readStates.current().getStateEngine();
log.info("CHECKSUMS");
HollowChecksum currentChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending);
log.info(" CUR " + currentChecksum);
HollowChecksum pendingChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current);
log.info(" PND " + pendingChecksum);
if (artifacts.hasDelta()) {
if (!artifacts.hasReverseDelta()) {
throw new IllegalStateException("Both a delta and reverse delta are required");
}
// FIXME: timt: future cycles will fail unless both deltas validate
applyDelta(artifacts.delta, current);
HollowChecksum forwardChecksum = HollowChecksum.forStateEngineWithCommonSchemas(current, pending);
//out.format(" CUR => PND %s\n", forwardChecksum);
if (!forwardChecksum.equals(pendingChecksum)) {
throw new HollowProducer.ChecksumValidationException(HollowProducer.Blob.Type.DELTA);
}
applyDelta(artifacts.reverseDelta, pending);
HollowChecksum reverseChecksum = HollowChecksum.forStateEngineWithCommonSchemas(pending, current);
//out.format(" CUR <= PND %s\n", reverseChecksum);
if (!reverseChecksum.equals(currentChecksum)) {
throw new HollowProducer.ChecksumValidationException(HollowProducer.Blob.Type.REVERSE_DELTA);
}
if (!schemaChangedFromPriorVersion) {
// optimization - they have identical schemas, so just swap them
log.log(Level.FINE, "current and pending have identical schemas, swapping");
result = readStates.swap();
} else {
// undo the changes we made to the read states
log.log(Level.FINE, "current and pending have non-identical schemas, reverting");
applyDelta(artifacts.reverseDelta, current);
applyDelta(artifacts.delta, pending);
}
}
}
status.success();
return result;
} catch (Throwable th) {
status.fail(th);
throw th;
} finally {
listeners.fireIntegrityCheckComplete(status);
}
}
private ReadStateHelper noIntegrityCheck(ReadStateHelper readStates, Artifacts artifacts) throws IOException {
ReadStateHelper result = readStates;
if(!readStates.hasCurrent() ||
(!readStates.current().getStateEngine().hasIdenticalSchemas(getWriteEngine()) && artifacts.snapshot != null)) {
HollowReadStateEngine pending = readStates.pending().getStateEngine();
readSnapshot(artifacts.snapshot, pending);
} else {
HollowReadStateEngine current = readStates.current().getStateEngine();
if (artifacts.hasDelta()) {
if (!artifacts.hasReverseDelta()) {
throw new IllegalStateException("Both a delta and reverse delta are required");
}
applyDelta(artifacts.delta, current);
result = readStates.swap();
}
}
return result;
}
private void readSnapshot(HollowProducer.Blob blob, HollowReadStateEngine stateEngine) throws IOException {
try (HollowBlobInput in = HollowBlobInput.serial(blob.newInputStream())) { // shared memory mode is not supported for producer
new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).readSnapshot(in);
}
}
private void applyDelta(HollowProducer.Blob blob, HollowReadStateEngine stateEngine) throws IOException {
try (HollowBlobInput in = HollowBlobInput.serial(blob.newInputStream())) { // shared memory mode is not supported for producer
new HollowBlobReader(stateEngine, new HollowBlobHeaderReader()).applyDelta(in);
}
}
private void validate(ProducerListeners listeners, HollowProducer.ReadState readState) {
Status.StageWithStateBuilder psb = listeners.fireValidationStart(readState);
ValidationStatus status = null;
try {
// Stream over the concatenation of the old and new validators
List<ValidationResult> results =
listeners.getListeners(ValidatorListener.class)
.map(v -> {
try {
return v.onValidate(readState);
} catch (RuntimeException e) {
return ValidationResult.from(v).error(e);
}
})
.collect(toList());
status = new ValidationStatus(results);
if (!status.passed()) {
ValidationStatusException e = new ValidationStatusException(
status, "One or more validations failed. Please check individual failures.");
psb.fail(e);
throw e;
}
psb.success();
} finally {
listeners.fireValidationComplete(psb, status);
}
}
private void announce(ProducerListeners listeners, HollowProducer.ReadState readState) {
if (announcer != null) {
Status.StageWithStateBuilder status = listeners.fireAnnouncementStart(readState);
try {
// don't allow producer to enable/disable between validating primary status and then announcing
singleProducerEnforcer.lock();
try {
if (!singleProducerEnforcer.isPrimary()) {
// This situation can arise when the producer is asked to relinquish primary status mid-cycle.
// If this non-primary producer is allowed to announce then a different producer instance could
// have been running concurrently as primary and that would break the delta chain.
log.log(Level.INFO,
"Fail the announcement because current producer is not primary (aka leader)");
throw new HollowProducer.NotPrimaryMidCycleException("Announcement failed primary (aka leader) check");
}
Map<String, String> announcementMetadata = new HashMap<>();
// save timestamp in milliseconds to mark the announcement start stage
announcementMetadata.put(HollowStateEngine.HEADER_TAG_METRIC_ANNOUNCEMENT, String.valueOf(System.currentTimeMillis()));
announcementMetadata.putAll(readState.getStateEngine().getHeaderTags());
announcementMetadata.put(ANNOUNCE_TAG_HEAP_FOOTPRINT, String.valueOf(readState.getStateEngine().calcApproxDataSize()));
announcer.announce(readState.getVersion(), announcementMetadata);
} finally {
singleProducerEnforcer.unlock();
}
status.success();
} catch (Throwable th) {
status.fail(th);
throw th;
} finally {
listeners.fireAnnouncementComplete(status);
}
}
}
static final class Artifacts {
HollowProducer.Blob snapshot = null;
HollowProducer.Blob delta = null;
HollowProducer.Blob reverseDelta = null;
HollowProducer.HeaderBlob header = null;
boolean cleanupCalled;
boolean snapshotPublishComplete;
synchronized void cleanup() {
cleanupCalled = true;
cleanupSnapshot();
if (delta != null) {
delta.cleanup();
delta = null;
}
if (reverseDelta != null) {
reverseDelta.cleanup();
reverseDelta = null;
}
if (header != null) {
header.cleanup();
header = null;
}
}
synchronized void markSnapshotPublishComplete() {
snapshotPublishComplete = true;
cleanupSnapshot();
}
private void cleanupSnapshot() {
if (cleanupCalled && snapshotPublishComplete && snapshot != null) {
snapshot.cleanup();
snapshot = null;
}
}
boolean hasDelta() {
return delta != null;
}
boolean hasReverseDelta() {
return reverseDelta != null;
}
boolean hasHeader() { return header != null; }
}
/**
* This Dummy blob storage cleaner does nothing
*/
static class DummyBlobStorageCleaner extends HollowProducer.BlobStorageCleaner {
@Override
public void cleanSnapshots() {
}
@Override
public void cleanReverseDeltas() {
}
@Override
public void cleanDeltas() {
}
}
/**
* This determines the latest number of cycles completed by a producer with a primary status. This value is 0 by default and
* increments by 1 only for a successful cycle and gets reset to 0 whenever a producer loses its primary status at
* any time during the cycle is being run.
*
* @return cycle count of a producer with primary status.
* */
public int getCycleCountWithPrimaryStatus() {
return this.cycleCountSincePrimaryStatus;
}
}
| 9,211 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/VersionMinterWithCounter.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.api.producer.HollowProducer.VersionMinter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A {@link VersionMinter}, which combines a timestamp with a repeating 3-digit sequence number
*
* @author Tim Taylor {@literal<tim@toolbear.io>}
*/
public class VersionMinterWithCounter implements VersionMinter {
private static AtomicInteger versionCounter = new AtomicInteger();
/**
* Create a new state version.<p>
*
* State versions should be ascending -- later states have greater versions.<p>
*
* Here we use an easily readable timestamp format.
*
* @return a new state version
*/
public long mint() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = dateFormat.format(new Date());
String versionStr = formattedDate + String.format("%03d", versionCounter.incrementAndGet() % 1000);
return Long.parseLong(versionStr);
}
}
| 9,212 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/AbstractIncrementalCycleListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import java.util.concurrent.TimeUnit;
/**
* Beta API subject to change.
* @deprecated see {@link com.netflix.hollow.api.producer.listener.IncrementalPopulateListener}
* @see com.netflix.hollow.api.producer.listener.IncrementalPopulateListener
*/
@Deprecated
public class AbstractIncrementalCycleListener implements IncrementalCycleListener {
@Override
public void onCycleComplete(IncrementalCycleStatus status, long elapsed, TimeUnit unit) { }
@Override
public void onCycleFail(IncrementalCycleStatus status, long elapsed, TimeUnit unit) { }
}
| 9,213 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/ReadStateHelper.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.api.producer.HollowProducer.ReadState;
import com.netflix.hollow.core.HollowConstants;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
/**
* Beta API subject to change.
*
* Helper for {@link HollowProducer} to manage current and pending read states and the
* transition that occurs within a cycle.
*
* @author Tim Taylor {@literal<tim@toolbear.io>}
*
*/
final class ReadStateHelper {
static ReadStateHelper newDeltaChain() {
return new ReadStateHelper(null, null);
}
static ReadStateHelper restored(ReadState state) {
return new ReadStateHelper(state, null);
}
static ReadState newReadState(final long version, final HollowReadStateEngine stateEngine) {
return new HollowProducer.ReadState() {
@Override
public long getVersion() {
return version;
}
@Override
public HollowReadStateEngine getStateEngine() {
return stateEngine;
}
};
}
private final ReadState current;
private final ReadState pending;
private ReadStateHelper(ReadState current, ReadState pending) {
this.current = current;
this.pending = pending;
}
ReadStateHelper roundtrip(long version) {
if(pending != null) throw new IllegalStateException();
return new ReadStateHelper(this.current, newReadState(version, new HollowReadStateEngine()));
}
/**
* Swap underlying state engines between current and pending while keeping the versions consistent;
* used after delta integrity checks have altered the underlying state engines.
*
* @return
*/
ReadStateHelper swap() {
return new ReadStateHelper(newReadState(current.getVersion(), pending.getStateEngine()),
newReadState(pending.getVersion(), current.getStateEngine()));
}
ReadStateHelper commit() {
if(pending == null) throw new IllegalStateException();
return new ReadStateHelper(this.pending, null);
}
ReadStateHelper rollback() {
if(pending == null) throw new IllegalStateException();
return new ReadStateHelper(newReadState(current.getVersion(), pending.getStateEngine()), null);
}
ReadState current() {
return current;
}
boolean hasCurrent() {
return current != null;
}
ReadState pending() {
return pending;
}
long pendingVersion() {
return pending != null ? pending.getVersion() : HollowConstants.VERSION_NONE;
}
}
| 9,214 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/HollowIncrementalCyclePopulator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.core.index.HollowPrimaryKeyIndex;
import com.netflix.hollow.core.memory.ThreadSafeBitSet;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import com.netflix.hollow.core.read.engine.HollowTypeReadState;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.util.SimultaneousExecutor;
import com.netflix.hollow.core.write.HollowTypeWriteState;
import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecord;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecordDumper;
import com.netflix.hollow.tools.traverse.TransitiveSetTraverser;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Used by HollowIncrementalProducer for Delta-Based Producer Input
* @since 2.9.9
* @deprecated see {@link HollowProducer.Incremental#runIncrementalCycle(HollowProducer.Incremental.IncrementalPopulator)}
* @see HollowProducer.Incremental#runIncrementalCycle(HollowProducer.Incremental.IncrementalPopulator)
*/
@Deprecated
public class HollowIncrementalCyclePopulator implements HollowProducer.Populator {
public static final Object DELETE_RECORD = new Object();
private final double threadsPerCpu;
private final Map<RecordPrimaryKey, Object> mutations;
HollowIncrementalCyclePopulator(Map<RecordPrimaryKey, Object> mutations, double threadsPerCpu) {
this.mutations = mutations;
this.threadsPerCpu = threadsPerCpu;
}
@Override
public void populate(HollowProducer.WriteState newState) throws Exception {
newState.getStateEngine().addAllObjectsFromPreviousCycle();
removeRecords(newState);
addRecords(newState);
}
private void removeRecords(HollowProducer.WriteState newState) {
if (newState.getPriorState() != null) {
Collection<String> types = findTypesWithRemovedRecords(newState.getPriorState());
Map<String, BitSet> recordsToRemove = markRecordsToRemove(newState.getPriorState(), types);
removeRecordsFromNewState(newState, recordsToRemove);
}
}
private Set<String> findTypesWithRemovedRecords(HollowProducer.ReadState readState) {
Set<String> typesWithRemovedRecords = new HashSet<>();
for(RecordPrimaryKey key : mutations.keySet()) {
if(!typesWithRemovedRecords.contains(key.getType())) {
HollowTypeReadState typeState = readState.getStateEngine().getTypeState(key.getType());
if(typeState != null) {
typesWithRemovedRecords.add(key.getType());
}
}
}
return typesWithRemovedRecords;
}
private Map<String, BitSet> markRecordsToRemove(HollowProducer.ReadState priorState, Collection<String> types) {
HollowReadStateEngine priorStateEngine = priorState.getStateEngine();
Map<String, BitSet> recordsToRemove = new HashMap<>();
for(String type : types) {
recordsToRemove.put(type, markTypeRecordsToRemove(priorStateEngine, type));
}
TransitiveSetTraverser.addTransitiveMatches(priorStateEngine, recordsToRemove);
TransitiveSetTraverser.removeReferencedOutsideClosure(priorStateEngine, recordsToRemove);
return recordsToRemove;
}
private BitSet markTypeRecordsToRemove(HollowReadStateEngine priorStateEngine, final String type) {
HollowTypeReadState priorReadState = priorStateEngine.getTypeState(type);
HollowSchema schema = priorReadState.getSchema();
int populatedOrdinals = priorReadState.getPopulatedOrdinals().length();
if(schema.getSchemaType() == HollowSchema.SchemaType.OBJECT) {
final HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(priorStateEngine, ((HollowObjectSchema) schema).getPrimaryKey()); ///TODO: Should we scan instead? Can we create this once and do delta updates?
ThreadSafeBitSet typeRecordsToRemove = new ThreadSafeBitSet(ThreadSafeBitSet.DEFAULT_LOG2_SEGMENT_SIZE_IN_BITS, populatedOrdinals);
SimultaneousExecutor executor = new SimultaneousExecutor(threadsPerCpu, getClass(), "mark-type-records-to-remove");
for(final Map.Entry<RecordPrimaryKey, Object> entry : mutations.entrySet()) {
executor.execute(() -> {
if(entry.getKey().getType().equals(type)) {
int priorOrdinal = idx.getMatchingOrdinal(entry.getKey().getKey());
if(priorOrdinal != -1) {
if(entry.getValue() instanceof AddIfAbsent)
((AddIfAbsent)entry.getValue()).wasFound = true;
else
typeRecordsToRemove.set(priorOrdinal);
}
}
});
}
try {
executor.awaitSuccessfulCompletion();
} catch(Exception e) {
throw new RuntimeException(e);
}
return typeRecordsToRemove.toBitSet();
}
return new BitSet(populatedOrdinals);
}
private void removeRecordsFromNewState(HollowProducer.WriteState newState, Map<String, BitSet> recordsToRemove) {
for(Map.Entry<String, BitSet> removalEntry : recordsToRemove.entrySet()) {
HollowTypeWriteState writeState = newState.getStateEngine().getTypeState(removalEntry.getKey());
BitSet typeRecordsToRemove = removalEntry.getValue();
int ordinalToRemove = typeRecordsToRemove.nextSetBit(0);
while(ordinalToRemove != -1) {
writeState.removeOrdinalFromThisCycle(ordinalToRemove);
ordinalToRemove = typeRecordsToRemove.nextSetBit(ordinalToRemove+1);
}
}
}
private void addRecords(final HollowProducer.WriteState newState) {
List<Map.Entry<RecordPrimaryKey, Object>> entryList = new ArrayList<>(mutations.entrySet());
AtomicInteger nextMutation = new AtomicInteger(0);
// @@@ Use parallel stream
SimultaneousExecutor executor = new SimultaneousExecutor(threadsPerCpu, getClass(), "add-records");
for(int i=0;i<executor.getCorePoolSize();i++) {
executor.execute(() -> {
FlatRecordDumper flatRecordDumper = null;
int currentMutationIdx = nextMutation.getAndIncrement();
while(currentMutationIdx < entryList.size()) {
Object currentMutation = entryList.get(currentMutationIdx).getValue();
if(currentMutation instanceof AddIfAbsent) {
AddIfAbsent aia = (AddIfAbsent) currentMutation;
if(aia.wasFound)
currentMutation = DELETE_RECORD;
else
currentMutation = aia.obj;
}
if(currentMutation != DELETE_RECORD) {
if(currentMutation instanceof FlatRecord) {
if(flatRecordDumper == null)
flatRecordDumper = new FlatRecordDumper(newState.getStateEngine());
flatRecordDumper.dump((FlatRecord)currentMutation);
} else {
newState.add(currentMutation);
}
}
currentMutationIdx = nextMutation.getAndIncrement();
}
});
}
try {
executor.awaitSuccessfulCompletion();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
static final class AddIfAbsent {
private final Object obj;
private boolean wasFound;
public AddIfAbsent(Object obj) {
this.obj = obj;
this.wasFound = false;
}
}
} | 9,215 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/CloseableWriteState.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
final class CloseableWriteState implements HollowProducer.WriteState, AutoCloseable {
private final long version;
private final HollowObjectMapper objectMapper;
private final HollowProducer.ReadState priorReadState;
private volatile boolean closed;
CloseableWriteState(long version, HollowObjectMapper objectMapper, HollowProducer.ReadState priorReadState) {
this.version = version;
this.objectMapper = objectMapper;
this.priorReadState = priorReadState;
}
@Override
public int add(Object o) throws IllegalStateException {
ensureNotClosed();
return objectMapper.add(o);
}
@Override
public HollowObjectMapper getObjectMapper() throws IllegalStateException {
ensureNotClosed();
return objectMapper;
}
@Override
public HollowWriteStateEngine getStateEngine() throws IllegalStateException {
ensureNotClosed();
return objectMapper.getStateEngine();
}
@Override
public long getVersion() throws IllegalStateException {
ensureNotClosed();
return version;
}
@Override
public HollowProducer.ReadState getPriorState() throws IllegalStateException {
ensureNotClosed();
return priorReadState;
}
private void ensureNotClosed() {
if (closed) {
throw new IllegalStateException(
String.format("Write state operated on after the population stage of a cycle; version=%d",
version));
}
}
@Override
public void close() {
closed = true;
}
}
| 9,216 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/HollowIncrementalProducer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import static com.netflix.hollow.api.producer.HollowIncrementalCyclePopulator.AddIfAbsent;
import static com.netflix.hollow.api.producer.HollowIncrementalCyclePopulator.DELETE_RECORD;
import com.netflix.hollow.api.consumer.HollowConsumer;
import com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever;
import com.netflix.hollow.api.consumer.fs.HollowFilesystemAnnouncementWatcher;
import com.netflix.hollow.core.util.SimultaneousExecutor;
import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey;
import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecord;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Warning: This is a BETA API and is subject to breaking changes.
* @deprecated see {@link HollowProducer.Incremental}
* @see HollowProducer.Incremental
*/
@Deprecated
public class HollowIncrementalProducer {
private static final long FAILED_VERSION = Long.MIN_VALUE;
private final HollowProducer producer;
private final ConcurrentHashMap<RecordPrimaryKey, Object> mutations;
private final HollowProducer.Populator populator;
private final ProducerListenerSupport listeners;
private final Map<String, Object> cycleMetadata;
private final Class<?>[] dataModel;
private final HollowConsumer.AnnouncementWatcher announcementWatcher;
private final HollowConsumer.BlobRetriever blobRetriever;
private final double threadsPerCpu;
private long lastSucessfulCycle;
public HollowIncrementalProducer(HollowProducer producer) {
this(producer, 1.0d, null, null, new ArrayList<IncrementalCycleListener>());
}
//For backwards compatible. TODO: @Deprecated ??
public HollowIncrementalProducer(HollowProducer producer, double threadsPerCpu) {
this(producer, threadsPerCpu, null, null, new ArrayList<IncrementalCycleListener>());
}
protected HollowIncrementalProducer(HollowProducer producer, double threadsPerCpu, HollowConsumer.AnnouncementWatcher announcementWatcher, HollowConsumer.BlobRetriever blobRetriever, List<IncrementalCycleListener> listeners, Class<?>... classes) {
this.producer = producer;
this.mutations = new ConcurrentHashMap<RecordPrimaryKey, Object>();
this.populator = new HollowIncrementalCyclePopulator(mutations, threadsPerCpu);
this.dataModel = classes;
this.announcementWatcher = announcementWatcher;
this.blobRetriever = blobRetriever;
this.listeners = new ProducerListenerSupport();
this.cycleMetadata = new HashMap<String, Object>();
this.threadsPerCpu = threadsPerCpu;
for (IncrementalCycleListener listener : listeners)
this.listeners.add(listener);
}
/**
* Initializes the data model and restores from existing state.
*/
public void restoreFromLastState() {
producer.initializeDataModel(dataModel);
long latestAnnouncedVersion = announcementWatcher.getLatestVersion();
if (latestAnnouncedVersion == HollowFilesystemAnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE || latestAnnouncedVersion < 0) {
return;
}
restore(latestAnnouncedVersion, blobRetriever);
}
public void restore(long versionDesired, BlobRetriever blobRetriever) {
producer.hardRestore(versionDesired, blobRetriever);
}
public void addOrModify(Object obj) {
RecordPrimaryKey pk = extractRecordPrimaryKey(obj);
mutations.put(pk, obj);
}
public void addIfAbsent(Object obj) {
RecordPrimaryKey pk = extractRecordPrimaryKey(obj);
mutations.putIfAbsent(pk, new AddIfAbsent(obj));
}
public void addOrModify(Collection<Object> objList) {
for(Object obj : objList) {
addOrModify(obj);
}
}
public void addOrModify(FlatRecord flatRecord) {
RecordPrimaryKey pk = flatRecord.getRecordPrimaryKey();
mutations.put(pk, flatRecord);
}
public void addIfAbsent(FlatRecord flatRecord) {
RecordPrimaryKey pk = flatRecord.getRecordPrimaryKey();
mutations.putIfAbsent(pk, new AddIfAbsent(flatRecord));
}
public void addOrModifyInParallel(Collection<Object> objList) {
executeInParallel(objList, "add-or-modify", this::addOrModify);
}
public void delete(Object obj) {
RecordPrimaryKey pk = extractRecordPrimaryKey(obj);
delete(pk);
}
public void delete(Collection<Object> objList) {
for(Object obj : objList) {
delete(obj);
}
}
public void deleteInParallel(Collection<Object> objList) {
executeInParallel(objList, "delete", this::delete);
}
public void discard(Object obj) {
RecordPrimaryKey pk = extractRecordPrimaryKey(obj);
discard(pk);
}
public void discard(Collection<Object> objList) {
for(Object obj : objList) {
discard(obj);
}
}
public void discardInParallel(Collection<Object> objList) {
executeInParallel(objList, "discard", this::discard);
}
public void delete(RecordPrimaryKey key) {
mutations.put(key, DELETE_RECORD);
}
public void discard(RecordPrimaryKey key) {
mutations.remove(key);
}
public void clearChanges() {
this.mutations.clear();
}
public boolean hasChanges() {
return this.mutations.size() > 0;
}
public void addCycleMetadata(String key, Object value) {
this.cycleMetadata.put(key, value);
}
public void addAllCycleMetadata(Map<String, Object> metadata) {
this.cycleMetadata.putAll(metadata);
}
public void removeFromCycleMetadata(String key) {
this.cycleMetadata.remove(key);
}
public void clearCycleMetadata() {
this.cycleMetadata.clear();
}
public boolean hasMetadata() {
return !this.cycleMetadata.isEmpty();
}
public void addListener(IncrementalCycleListener listener) {
this.listeners.add(listener);
}
public void removeListener(IncrementalCycleListener listener) {
this.listeners.remove(listener);
}
/**
* Runs a Hollow Cycle, if successful, cleans the mutations map.
*
* @return the version of the cycle if successful, otherwise the {@link #FAILED_VERSION}
* @since 2.9.9
*/
public long runCycle() {
long recordsRemoved = countRecordsToRemove();
long recordsAddedOrModified = this.mutations.values().size() - recordsRemoved;
try {
long version = producer.runCycle(populator);
if(version == lastSucessfulCycle) {
return version;
}
listeners.fireIncrementalCycleComplete(version, recordsAddedOrModified, recordsRemoved, new HashMap<String, Object>(cycleMetadata));
//Only clean changes when the version is new.
clearChanges();
lastSucessfulCycle = version;
return version;
} catch (Exception e) {
listeners.fireIncrementalCycleFail(e, recordsAddedOrModified, recordsRemoved, new HashMap<String, Object>(cycleMetadata));
return FAILED_VERSION;
} finally {
clearCycleMetadata();
}
}
private long countRecordsToRemove() {
long recordsToRemove = 0L;
Collection<Object> records = mutations.values();
for (Object record : records) {
if (record == HollowIncrementalCyclePopulator.DELETE_RECORD) recordsToRemove++;
}
return recordsToRemove;
}
private RecordPrimaryKey extractRecordPrimaryKey(Object obj) {
return producer.getObjectMapper().extractPrimaryKey(obj);
}
public static HollowIncrementalProducer.Builder withProducer(HollowProducer hollowProducer) {
Builder builder = new Builder();
return builder.withProducer(hollowProducer);
}
public static class Builder<B extends HollowIncrementalProducer.Builder<B>> {
protected HollowProducer producer;
protected double threadsPerCpu = 1.0d;
protected HollowConsumer.AnnouncementWatcher announcementWatcher;
protected HollowConsumer.BlobRetriever blobRetriever;
protected Class<?>[] dataModel;
protected List<IncrementalCycleListener> listeners = new ArrayList<IncrementalCycleListener>();
public B withProducer(HollowProducer producer) {
this.producer = producer;
return (B) this;
}
public B withThreadsPerCpu(double threadsPerCpu) {
this.threadsPerCpu = threadsPerCpu;
return (B) this;
}
public B withAnnouncementWatcher(HollowConsumer.AnnouncementWatcher announcementWatcher) {
this.announcementWatcher = announcementWatcher;
return (B) this;
}
public B withBlobRetriever(HollowConsumer.BlobRetriever blobRetriever) {
this.blobRetriever = blobRetriever;
return (B) this;
}
public B withDataModel(Class<?>... classes) {
this.dataModel = classes;
return (B) this;
}
public B withListener(IncrementalCycleListener listener) {
this.listeners.add(listener);
return (B) this;
}
public B withListeners(IncrementalCycleListener... listeners) {
for (IncrementalCycleListener listener : listeners)
this.listeners.add(listener);
return (B) this;
}
protected void checkArguments() {
if (producer == null)
throw new IllegalArgumentException("HollowProducer must be specified.");
}
public HollowIncrementalProducer build() {
checkArguments();
return new HollowIncrementalProducer(producer, threadsPerCpu, announcementWatcher, blobRetriever, listeners, dataModel);
}
}
/**
* Parallel execution. Modifies the mutation ConcurrentHashMap in parallel based on a Callback.
* <p>
* Note: This could be replaced with Java 8 parallelStream and lambadas instead of Callback interface
* </p>
* @param objList
* @param callback
*/
private void executeInParallel(Collection<Object> objList, String description, final Callback callback) {
SimultaneousExecutor executor = new SimultaneousExecutor(threadsPerCpu, getClass(), description);
for(final Object obj : objList) {
executor.execute(() -> callback.call(obj));
}
try {
executor.awaitSuccessfulCompletion();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private interface Callback {
void call(Object obj);
}
}
| 9,217 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/ProducerOptionalBlobPartConfig.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import com.netflix.hollow.api.consumer.HollowConsumer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* A blob may be configured to produce optional "parts". Parts will contain the data one or more types.
*
* A type may be assigned to one and only one section -- by default a type will be serialized to the main "part".
*
* The optional blob parts are intended to be stored as separate files in the blob store, so that they may be
* retrieved by consumers only when required. Details of how this is accomplished will be dependent upon individual
* implementations of {@link HollowProducer.Publisher} and {@link HollowConsumer.BlobRetriever}.
*/
public class ProducerOptionalBlobPartConfig {
private final Map<String, Set<String>> parts;
public ProducerOptionalBlobPartConfig() {
this.parts = new HashMap<>();
}
public void addTypesToPart(String partName, String... types) {
if(types.length == 0)
return;
Set<String> typeSet = parts.computeIfAbsent(partName, n -> new HashSet<>());
for(String type : types) {
typeSet.add(type);
}
}
public Set<String> getParts() {
return parts.keySet();
}
public OptionalBlobPartOutputStreams newStreams() {
return new OptionalBlobPartOutputStreams();
}
public OptionalBlobPartOutputStreams newStreams(Function<String, OutputStream> streamCreator) {
OptionalBlobPartOutputStreams s = newStreams();
for(String part : getParts()) {
s.addOutputStream(part, streamCreator.apply(part));
}
return s;
}
public class OptionalBlobPartOutputStreams {
private final Map<String, ConfiguredOutputStream> partStreams;
private OptionalBlobPartOutputStreams() {
this.partStreams = new HashMap<>();
}
public void addOutputStream(String partName, OutputStream os) {
Set<String> types = parts.get(partName);
if(types == null)
throw new IllegalArgumentException("There is no blob part named " + partName + " in this configuration");
partStreams.put(partName, new ConfiguredOutputStream(partName, types, new DataOutputStream(os)));
}
public Map<String, DataOutputStream> getStreamsByType() {
if(!allPartsHaveStreams())
throw new IllegalStateException("Not all configured parts have streams!");
Map<String, DataOutputStream> streamsByType = new HashMap<>();
for(Map.Entry<String, ConfiguredOutputStream> entry : partStreams.entrySet()) {
ConfiguredOutputStream cos = entry.getValue();
for(String type : cos.getTypes()) {
streamsByType.put(type, cos.getStream());
}
}
return streamsByType;
}
public Map<String, String> getPartNameByType() {
if(!allPartsHaveStreams())
throw new IllegalStateException("Not all configured parts have streams!");
Map<String, String> streamsByType = new HashMap<>();
for(Map.Entry<String, ConfiguredOutputStream> entry : partStreams.entrySet()) {
ConfiguredOutputStream cos = entry.getValue();
for(String type : cos.getTypes()) {
streamsByType.put(type, cos.getPartName());
}
}
return streamsByType;
}
public Map<String, ConfiguredOutputStream> getPartStreams() {
return Collections.unmodifiableMap(partStreams);
}
public void flush() throws IOException {
for(Map.Entry<String, ConfiguredOutputStream> entry : partStreams.entrySet()) {
entry.getValue().getStream().flush();
}
}
public void close() throws IOException {
for(Map.Entry<String, ConfiguredOutputStream> entry : partStreams.entrySet()) {
entry.getValue().getStream().close();
}
}
private boolean allPartsHaveStreams() {
return parts.keySet().equals(partStreams.keySet());
}
}
public static class ConfiguredOutputStream {
private final String partName;
private final Set<String> types;
private final DataOutputStream stream;
public ConfiguredOutputStream(String partName, Set<String> types, DataOutputStream stream) {
this.partName = partName;
this.types = Collections.unmodifiableSet(types);
this.stream = stream;
}
public String getPartName() {
return partName;
}
public Set<String> getTypes() {
return types;
}
public DataOutputStream getStream() {
return stream;
}
}
}
| 9,218 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/AbstractHollowProducerListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import java.util.concurrent.TimeUnit;
/**
* A trivial implementation of {@link HollowProducerListener} which does nothing.
* Implementations of HollowProducerListenerV2 should subclass this class for convenience.
*
* @author Tim Taylor {@literal<tim@toolbear.io>}
*/
public class AbstractHollowProducerListener implements HollowProducerListener {
// DataModelInitializationListener
@Override public void onProducerInit(long elapsed, TimeUnit unit) {}
// RestoreListener
@Override public void onProducerRestoreStart(long restoreVersion) {}
@Override public void onProducerRestoreComplete(RestoreStatus status, long elapsed, TimeUnit unit) {}
// CycleListener
@Override public void onNewDeltaChain(long version) {}
@Override public void onCycleSkip(CycleSkipReason reason) {}
@Override public void onCycleStart(long version) {}
@Override public void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
// PopulateListener
@Override public void onPopulateStart(long version) {}
@Override public void onPopulateComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
// PublishListener
@Override public void onNoDeltaAvailable(long version) {}
@Override public void onPublishStart(long version) {}
@Override public void onArtifactPublish(PublishStatus publishStatus, long elapsed, TimeUnit unit) {}
@Override public void onPublishComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
// IntegrityCheckListener
@Override public void onIntegrityCheckStart(long version) {}
@Override public void onIntegrityCheckComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
// ValidationListener
@Override public void onValidationStart(long version) {}
@Override public void onValidationComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
// AnnouncementListener
@Override public void onAnnouncementStart(long version) {}
@Override
public void onAnnouncementStart(HollowProducer.ReadState readState) {}
@Override public void onAnnouncementComplete(ProducerStatus status, long elapsed, TimeUnit unit) {}
}
| 9,219 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/HollowProducer.java | /*
* Copyright 2016-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import static com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE;
import com.netflix.hollow.api.consumer.HollowConsumer;
import com.netflix.hollow.api.metrics.HollowMetricsCollector;
import com.netflix.hollow.api.metrics.HollowProducerMetrics;
import com.netflix.hollow.api.producer.enforcer.BasicSingleProducerEnforcer;
import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer;
import com.netflix.hollow.api.producer.fs.HollowFilesystemBlobStager;
import com.netflix.hollow.api.producer.listener.HollowProducerEventListener;
import com.netflix.hollow.api.producer.validation.ValidatorListener;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.util.HollowObjectHashCodeFinder;
import com.netflix.hollow.core.write.HollowBlobWriter;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey;
import com.netflix.hollow.tools.compact.HollowCompactor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
/**
* A HollowProducer is the top-level class used by producers of Hollow data to populate, publish, and announce data states.
* The interactions between the "blob" store and announcement mechanism are defined by this class, and the implementations
* of the data publishing and announcing are abstracted in interfaces which are provided to this class.
* <p>
* To obtain a HollowProducer, you should use a builder pattern, for example:
*
* <pre>
* {@code
*
* HollowProducer producer = HollowProducer.withPublisher(publisher)
* .withAnnouncer(announcer)
* .build();
* }
* </pre>
* <p>
* The following components are injectable, but only an implementation of the HollowProducer.Publisher is
* required to be injected, all other components are optional. :
*
* <dl>
* <dt>{@link HollowProducer.Publisher}</dt>
* <dd>Implementations of this class define how to publish blob data to the blob store.</dd>
*
* <dt>{@link HollowProducer.Announcer}</dt>
* <dd>Implementations of this class define the announcement mechanism, which is used to track the version of the
* currently announced state.</dd>
*
* <dt>One or more event listeners</dt>
* <dd>Listeners are notified about the progress and status of producer cycles throughout the various cycle stages.
* Of special note are {@link ValidatorListener} that allow for semantic validation of the data contained in
* a state prior to announcement. If a {@code RuntimeException} is thrown during validation, the state will not be
* announced, and the producer will be automatically rolled back to the prior state.
* </dd>
*
* <dt>A Blob staging directory</dt>
* <dd>Before blobs are published, they must be written and inspected/validated. A directory may be specified as a File to which
* these "staged" blobs will be written prior to publish. Staged blobs will be cleaned up automatically after publish.</dd>
*
* <dt>{@link HollowProducer.BlobCompressor}</dt>
* <dd>Implementations of this class intercept blob input/output streams to allow for compression in the blob store.</dd>
*
* <dt>{@link HollowProducer.BlobStager}</dt>
* <dd>Implementations will define how to stage blobs, if the default behavior of staging blobs on local disk is not desirable.
* If a {@link BlobStager} is provided, then neither a blob staging directory or {@link BlobCompressor} should be provided.</dd>
*
* <dt>An Executor for publishing snapshots</dt>
* <dd>When consumers start up, if the latest announced version does not have a snapshot, they can load an earlier snapshot
* and follow deltas to get up-to-date. A state can therefore be available and announced prior to the availability of
* the snapshot. If an Executor is supplied here, then it will be used to publish snapshots. This can be useful if
* snapshot publishing takes a long time -- subsequent cycles may proceed while snapshot uploads are still in progress.</dd>
*
* <dt>Number of cycles between snapshots</dt>
* <dd>Because snapshots are not necessary for a data state to be announced, they need not be published every cycle.
* If this parameter is specified, then a snapshot will be produced only every (n+1)th cycle.</dd>
*
* <dt>{@link HollowProducer.VersionMinter}</dt>
* <dd>Allows for a custom version identifier minting strategy.</dd>
*
* <dt>Target max type shard size</dt>
* <dd>Specify a target max type shard size. Defaults to 16MB. See http://hollow.how/advanced-topics/#type-sharding</dd>
* </dl>
*
* @author Tim Taylor {@literal<tim@toolbear.io>}
*/
public class HollowProducer extends AbstractHollowProducer {
/*
* HollowProducer and HollowProducer.Incremental extend from a package protected AbstractHollowProducer
* for sharing common functionality.
* To preserve binary compatibility HollowProducer overrides many methods on AbstractHollowProducer
* and directly defers to them (in effect explicit bridge methods).
*/
@Deprecated
public HollowProducer(
Publisher publisher,
Announcer announcer) {
super(publisher, announcer);
}
// The only constructor should be that which accepts a builder
// This ensures that if the builder modified to include new state that
// extended builders will not require modification to pass on that new state
protected HollowProducer(Builder<?> b) {
super(b);
}
/**
* @return the metrics for this producer
*/
@Override
public HollowProducerMetrics getMetrics() {
return super.getMetrics();
}
/**
* Initializes the data model for the given classes.
* <p>
* Data model initialization is required prior to {@link #restore(long, HollowConsumer.BlobRetriever) restoring}
* the producer.
* This ensures that restoration can correctly compare the producer's current data model
* with the data model of the restored data state and manage any differences in those models
* (such as not restoring state for any types in the restoring data model not present in the
* producer's current data model).
* <p>
* After initialization a data model initialization event will be emitted
* to all registered data model initialization listeners
* {@link com.netflix.hollow.api.producer.listener.DataModelInitializationListener listeners}.
*
* @param classes the data model classes
* @throws IllegalArgumentException if {@code classes} is empty
* @see #restore(long, HollowConsumer.BlobRetriever)
*/
@Override
public void initializeDataModel(Class<?>... classes) {
super.initializeDataModel(classes);
}
/**
* Initializes the producer data model for the given schemas.
* <p>
* Data model initialization is required prior to {@link #restore(long, HollowConsumer.BlobRetriever) restoring}
* the producer.
* This ensures that restoration can correctly compare the producer's current data model
* with the data model of the restored data state and manage any differences in those models
* (such as not restoring state for any types in the restoring data model not present in the
* producer's current data model).
* <p>
* After initialization a data model initialization event will be emitted
* to all registered data model initialization listeners
* {@link com.netflix.hollow.api.producer.listener.DataModelInitializationListener listeners}.
*
* @param schemas the data model classes
* @throws IllegalArgumentException if {@code schemas} is empty
* @see #restore(long, HollowConsumer.BlobRetriever)
*/
@Override
public void initializeDataModel(HollowSchema... schemas) {
super.initializeDataModel(schemas);
}
/**
* Restores the data state to a desired version.
* <p>
* Data model {@link #initializeDataModel(Class[]) initialization} is required prior to
* restoring the producer. This ensures that restoration can correctly compare the producer's
* current data model with the data model of the restored data state and manage any differences
* in those models (such as not restoring state for any types in the restoring data model not
* present in the producer's current data model)
*
* @param versionDesired the desired version
* @param blobRetriever the blob retriever
* @return the read state of the restored state
* @throws IllegalStateException if the producer's data model has not been initialized
* @see #initializeDataModel(Class[])
*/
@Override
public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) {
return super.restore(versionDesired, blobRetriever);
}
@Override
public HollowWriteStateEngine getWriteEngine() {
return super.getWriteEngine();
}
@Override
public HollowObjectMapper getObjectMapper() {
return super.getObjectMapper();
}
/**
* Invoke this method to alter runCycle behavior. If this Producer is not primary, runCycle is a no-op. Note that by default,
* SingleProducerEnforcer is instantiated as BasicSingleProducerEnforcer, which is initialized to return true for isPrimary()
*
* @param doEnable true if enable primary producer, if false
* @return true if the intended action was successful
*/
@Override
public boolean enablePrimaryProducer(boolean doEnable) {
return super.enablePrimaryProducer(doEnable);
}
/**
* Runs a cycle to populate, publish, and announce a new single data state.
*
* @param task the populating task to add complete state
* @return the version identifier of the announced state, otherwise the
* last successful announced version if 1) there were no data changes compared to that version;
* or 2) the producer is not the primary producer
* @throws RuntimeException if the cycle failed
*/
// @@@ Should this be marked as synchronized?
public long runCycle(HollowProducer.Populator task) {
return runCycle(null, task);
}
/**
* Run a compaction cycle, will produce a data state with exactly the same data as currently, but
* reorganized so that ordinal holes are filled. This may need to be run multiple times to arrive
* at an optimal state.
*
* @param config specifies what criteria to use to determine whether a compaction is necessary
* @return the version identifier of the produced state, or AnnouncementWatcher.NO_ANNOUNCEMENT_AVAILABLE if compaction was unnecessary.
*/
public long runCompactionCycle(HollowCompactor.CompactionConfig config) {
if (config != null && readStates.hasCurrent()) {
final HollowCompactor compactor = new HollowCompactor(getWriteEngine(),
readStates.current().getStateEngine(), config);
if (compactor.needsCompaction()) {
return runCycle(newState -> compactor.compact());
}
}
return NO_ANNOUNCEMENT_AVAILABLE;
}
/**
* Adds a listener to this producer.
* <p>
* If the listener was previously added to this consumer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is added, concurrently, during the occurrence of a cycle or restore then the listener will not
* receive events until the next cycle or restore. The listener may also be removed concurrently.
*
* @param listener the listener to add
*/
@Override
public void addListener(HollowProducerListener listener) {
super.addListener(listener);
}
/**
* Adds a listener to this producer.
* <p>
* If the listener was previously added to this consumer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is added, concurrently, during the occurrence of a cycle or restore then the listener will not
* receive events until the next cycle or restore. The listener may also be removed concurrently.
*
* @param listener the listener to add
*/
@Override
public void addListener(HollowProducerEventListener listener) {
super.addListener(listener);
}
/**
* Removes a listener to this producer.
* <p>
* If the listener was not previously added to this producer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is removed, concurrently, during the occurrence of a cycle or restore then the listener will
* receive all events for that cycle or restore but not receive events for a subsequent cycle or restore.
*
* @param listener the listener to remove
*/
@Override
public void removeListener(HollowProducerListener listener) {
super.removeListener(listener);
}
/**
* Removes a listener to this producer.
* <p>
* If the listener was not previously added to this producer, as determined by reference equality or {@code Object}
* equality, then this method does nothing.
* <p>
* If a listener is removed, concurrently, during the occurrence of a cycle or restore then the listener will
* receive all events for that cycle or restore but not receive events for a subsequent cycle or restore.
*
* @param listener the listener to remove
*/
@Override
public void removeListener(HollowProducerEventListener listener) {
super.removeListener(listener);
}
public static final class ChecksumValidationException extends IllegalStateException {
private static final long serialVersionUID = -4399719849669674206L;
ChecksumValidationException(Blob.Type type) {
super(type.name() + " checksum invalid");
}
}
/**
* This exception is thrown when a publishing producer for the current cycle is not primary.
* */
public static final class NotPrimaryMidCycleException extends IllegalStateException {
NotPrimaryMidCycleException(String message) {
super(message);
}
}
public interface VersionMinter {
/**
* Create a new state version.
* <p>
* State versions should be ascending -- later states have greater versions.<p>
*
* @return a new state version
*/
long mint();
}
/**
* Represents a task that populates a new data state within a {@link HollowProducer} cycle.
*
* <p>This is a functional interface whose functional method is
* {@link #populate(HollowProducer.WriteState)}.
*/
@FunctionalInterface
public interface Populator {
/**
* Populates the provided {@link WriteState} with new objects. Often written as a lambda passed in to
* {@link HollowProducer#runCycle(Populator)}:
*
* <pre>{@code
* producer.runCycle(state -> {
* sourceOfTruthA = queryA();
* for (Record r : sourceOfTruthA) {
* Model m = new Model(r);
* state.add(m);
* }
*
* sourceOfTruthB = queryB();
* // ...
* });
* }</pre>
*
* <p>Notes:
*
* <ul>
* <li>all data for the new state must be added; data from previous cycles is <em>not</em> carried
* over automatically</li>
* <li>caught exceptions that are unrecoverable must be rethrown</li>
* <li>the provided {@code WriteState} will be inoperable when this method returns; method
* calls against it will throw {@code IllegalStateException}</li>
* <li>the {@code WriteState} is thread safe</li>
* </ul>
*
* <p>
* Populating asynchronously has these additional requirements:
* <ul>
* <li>MUST NOT return from this method until all workers have completed – either normally
* or exceptionally – or have been cancelled</li>
* <li>MUST throw an exception if any worker completed exceptionally. MAY cancel remaining tasks
* <em>or</em> wait for the remainder to complete.</li>
* </ul>
*
* @param newState the new state to add objects to
* @throws Exception if population fails. If failure occurs the data from the previous cycle is retained.
*/
void populate(HollowProducer.WriteState newState) throws Exception;
}
/**
* Representation of new write state.
*/
public interface WriteState {
/**
* Adds the specified POJO to the state engine. See {@link HollowObjectMapper#add(Object)} for details.
*
* <p>Calling this method after the producer's populate stage has completed is an error.
*
* @param o the POJO to add
* @return the ordinal associated with the added POJO
* @throws IllegalStateException if called after the populate stage has completed (see
* {@link Populator} for details on the contract)
*/
int add(Object o) throws IllegalStateException;
/**
* For advanced use-cases, access the underlying {@link HollowObjectMapper}. Prefer using {@link #add(Object)}
* on this class instead.
*
* <p>Calling this method after the producer's populate stage has completed is an error. Exercise caution when
* saving the returned reference in a local variable that is closed over by an asynchronous task as that
* circumvents this guard. It is safest to call {@code writeState.getObjectMapper()} within the closure.
*
* @return the object mapper
* @throws IllegalStateException if called after the populate stage has completed (see
* {@link Populator} for details on the contract)
*/
HollowObjectMapper getObjectMapper() throws IllegalStateException;
/**
* For advanced use-cases, access the underlying {@link HollowWriteStateEngine}. Prefer using
* {@link #add(Object)} on this class instead.
*
* <p>Calling this method after the producer's populate stage has completed is an error. Exercise caution when
* saving the returned reference in a local variable that is closed over by an asynchronous task as that
* circumvents this guard. It is safest to call {@code writeState.getStateEngine()} within the closure.
*
* @return the write state engine
* @throws IllegalStateException if called after the populate stage has completed (see
* {@link Populator} for details on the contract)
*/
HollowWriteStateEngine getStateEngine() throws IllegalStateException;
/**
* For advanced use-cases, access the ReadState of the prior successful cycle.
*
* <p>Calling this method after the producer's populate stage has completed is an error. Exercise caution when
* saving the returned reference in a local variable that is closed over by an asynchronous task as that
* circumvents this guard. It is safest to call {@code writeState.getPriorState()} within the closure.
*
* @return the prior read state
* @throws IllegalStateException if called after the populate stage has completed (see
* {@link Populator} for details on the contract)
*/
ReadState getPriorState() throws IllegalStateException;
/**
* Returns the version of the current producer cycle being populated.
*
* <p>Calling this method after the producer's populate stage has completed is an error.
*
* @return the version of the current producer cycle
* @throws IllegalStateException if called after the populate stage has completed (see
* {@link Populator} for details on the contract)
*/
long getVersion() throws IllegalStateException;
}
/**
* Representation of read state computed from the population of new write state.
*/
public interface ReadState {
/**
* Returns the version of the read state
*
* @return the version
*/
long getVersion();
/**
* Returns the read state engine
*
* @return the read state engine
*/
HollowReadStateEngine getStateEngine();
}
public interface BlobStager {
/**
* Returns a blob with which a {@code HollowProducer} will write a snapshot for the version specified.
* <p>
* The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(HollowProducer.PublishArtifact)}.
*
* @param version the blob version
* @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version}
*/
HollowProducer.Blob openSnapshot(long version);
/**
* Returns a blob with which a {@code HollowProducer} will write a header for the version specified.
* <p>
* The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(HollowProducer.PublishArtifact)}.
* @param version the blob version
* @return a {@link HollowProducer.HeaderBlob} representing a header for the {@code version}
*/
HollowProducer.HeaderBlob openHeader(long version);
/**
* Returns a blob with which a {@code HollowProducer} will write a forward delta from the version specified to
* the version specified, i.e. {@code fromVersion => toVersion}.
* <p>
* The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(HollowProducer.PublishArtifact)}.
* <p>
* In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}.
*
* @param fromVersion the data state this delta will transition from
* @param toVersion the data state this delta will transition to
* @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version}
*/
HollowProducer.Blob openDelta(long fromVersion, long toVersion);
/**
* Returns a blob with which a {@code HollowProducer} will write a reverse delta from the version specified to
* the version specified, i.e. {@code fromVersion <= toVersion}.
* <p>
* The producer will pass the returned blob back to this publisher when calling {@link Publisher#publish(HollowProducer.PublishArtifact)}.
* <p>
* In the delta chain {@code fromVersion} is the older version such that {@code fromVersion < toVersion}.
*
* @param fromVersion version in the delta chain immediately after {@code toVersion}
* @param toVersion version in the delta chain immediately before {@code fromVersion}
* @return a {@link HollowProducer.Blob} representing a snapshot for the {@code version}
*/
HollowProducer.Blob openReverseDelta(long fromVersion, long toVersion);
}
public interface BlobCompressor {
BlobCompressor NO_COMPRESSION = new BlobCompressor() {
@Override
public OutputStream compress(OutputStream os) {
return os;
}
@Override
public InputStream decompress(InputStream is) {
return is;
}
};
/**
* This method provides an opportunity to wrap the OutputStream used to write the blob (e.g. with a GZIPOutputStream).
*
* @param is the uncompressed output stream
* @return the compressed output stream
*/
OutputStream compress(OutputStream is);
/**
* This method provides an opportunity to wrap the InputStream used to write the blob (e.g. with a GZIPInputStream).
*
* @param is the compressed input stream
* @return the uncompressed input stream
*/
InputStream decompress(InputStream is);
}
public interface Publisher {
/**
* Deprecated - Should use {@link Publisher#publish(PublishArtifact)} instead.<p>
* Publish the blob specified to this publisher's blobstore.
* <p>
* It is guaranteed that {@code blob} was created by calling one of
* {@link BlobStager#openSnapshot(long)}, {@link BlobStager#openDelta(long, long)}, or
* {@link BlobStager#openReverseDelta(long, long)} on this publisher.
*
* @param blob the blob to publish
*/
@Deprecated
default void publish(HollowProducer.Blob blob) {
publish((PublishArtifact)blob);
}
/**
* Publish the blob specified to this publisher's blobstore.
* <p>
* It is guaranteed that {@code blob} was created by calling one of
* {@link BlobStager#openSnapshot(long)}, {@link BlobStager#openDelta(long, long)},
* {@link BlobStager#openReverseDelta(long, long)}, or
* {@link BlobStager#openHeader(long)} on this publisher.
*
* @param publishArtifact the blob to publish
*/
default void publish(HollowProducer.PublishArtifact publishArtifact) {
if (publishArtifact instanceof HollowProducer.Blob) {
publish((HollowProducer.Blob)publishArtifact);
}
}
}
public interface PublishArtifact {
void cleanup();
void write(HollowBlobWriter blobWriter) throws IOException;
InputStream newInputStream() throws IOException;
@Deprecated
default File getFile() {
throw new UnsupportedOperationException("File is not available");
}
default Path getPath() {
throw new UnsupportedOperationException("Path is not available");
}
}
public static abstract class HeaderBlob implements PublishArtifact{
protected final long version;
protected HeaderBlob(long version) {
this.version = version;
}
public long getVersion() {
return version;
}
}
public static abstract class Blob implements PublishArtifact {
protected final long fromVersion;
protected final long toVersion;
protected final Blob.Type type;
protected final ProducerOptionalBlobPartConfig optionalPartConfig;
protected Blob(long fromVersion, long toVersion, Blob.Type type) {
this(fromVersion, toVersion, type, null);
}
protected Blob(long fromVersion, long toVersion, Blob.Type type, ProducerOptionalBlobPartConfig optionalPartConfig) {
this.fromVersion = fromVersion;
this.toVersion = toVersion;
this.type = type;
this.optionalPartConfig = optionalPartConfig;
}
public InputStream newOptionalPartInputStream(String partName) throws IOException {
throw new UnsupportedOperationException("The provided HollowProducer.Blob implementation does not support optional blob parts");
}
public Path getOptionalPartPath(String partName) {
throw new UnsupportedOperationException("The provided HollowProducer.Blob implementation does not support optional blob parts");
}
public Type getType() {
return this.type;
}
public long getFromVersion() {
return this.fromVersion;
}
public long getToVersion() {
return this.toVersion;
}
public ProducerOptionalBlobPartConfig getOptionalPartConfig() {
return optionalPartConfig;
}
/**
* Hollow blob types are {@code SNAPSHOT}, {@code DELTA} and {@code REVERSE_DELTA}.
*/
public enum Type {
SNAPSHOT("snapshot"),
DELTA("delta"),
REVERSE_DELTA("reversedelta");
public final String prefix;
Type(String prefix) {
this.prefix = prefix;
}
}
}
public interface Announcer {
void announce(long stateVersion);
default void announce(long stateVersion, Map<String, String> metadata) {
announce(stateVersion);
}
}
public static HollowProducer.Builder<?> withPublisher(HollowProducer.Publisher publisher) {
Builder<?> builder = new Builder<>();
return builder.withPublisher(publisher);
}
@SuppressWarnings("unchecked")
public static class Builder<B extends HollowProducer.Builder<B>> {
BlobStager stager;
BlobCompressor compressor;
File stagingDir;
Publisher publisher;
Announcer announcer;
List<HollowProducerEventListener> eventListeners = new ArrayList<>();
VersionMinter versionMinter = new VersionMinterWithCounter();
Executor snapshotPublishExecutor = null;
int numStatesBetweenSnapshots = 0;
boolean focusHoleFillInFewestShards = false;
long targetMaxTypeShardSize = DEFAULT_TARGET_MAX_TYPE_SHARD_SIZE;
HollowMetricsCollector<HollowProducerMetrics> metricsCollector;
BlobStorageCleaner blobStorageCleaner = new DummyBlobStorageCleaner();
SingleProducerEnforcer singleProducerEnforcer = new BasicSingleProducerEnforcer();
HollowObjectHashCodeFinder hashCodeFinder = null;
boolean doIntegrityCheck = true;
ProducerOptionalBlobPartConfig optionalPartConfig = null;
public B withBlobStager(HollowProducer.BlobStager stager) {
this.stager = stager;
return (B) this;
}
public B withBlobCompressor(HollowProducer.BlobCompressor compressor) {
this.compressor = compressor;
return (B) this;
}
public B withOptionalPartConfig(ProducerOptionalBlobPartConfig optionalPartConfig) {
this.optionalPartConfig = optionalPartConfig;
return (B) this;
}
public B withBlobStagingDir(File stagingDir) {
this.stagingDir = stagingDir;
return (B) this;
}
public B withPublisher(HollowProducer.Publisher publisher) {
this.publisher = publisher;
return (B) this;
}
public B withAnnouncer(HollowProducer.Announcer announcer) {
this.announcer = announcer;
return (B) this;
}
/**
* Registers an event listener that will receive events in accordance to the event listener
* types that are implemented.
*
* @param listener the event listener
* @return this builder
* @throws IllegalArgumentException if the listener does not implement a recognized event listener type
*/
public B withListener(HollowProducerEventListener listener) {
if (!ProducerListenerSupport.isValidListener(listener)) {
throw new IllegalArgumentException(
"Listener does not implement a recognized event listener type: " + listener);
}
this.eventListeners.add(listener);
return (B) this;
}
/**
* Registers one or more event listeners each of which will receive events in accordance to the
* event listener types that are implemented.
*
* @param listeners one or more event listeners
* @return this builder
* @throws IllegalArgumentException if the listener does not implement a recognized event listener type
*/
public B withListeners(HollowProducerEventListener... listeners) {
for (HollowProducerEventListener listener : listeners) {
if (!ProducerListenerSupport.isValidListener(listener)) {
throw new IllegalArgumentException(
"Listener does not implement a recognized event listener type: " + listener);
}
this.eventListeners.add(listener);
}
return (B) this;
}
/**
* Registers a validator event listener that will receive a validator event
* during the validator stage.
*
* @param validator the validator listener
* @return this builder
* @apiNote This method is equivalent to registering the listener with
* {@link #withListener(HollowProducerEventListener)}.
* @see #withListener(HollowProducerEventListener)
*/
public B withValidator(ValidatorListener validator) {
return withListener(validator);
}
/**
* Register a one or more validator event listeners each of which will receive a validator event
* during the validator stage.
*
* @param validators one or more validator listeners
* @return this builder
* @apiNote This method is equivalent to registering the listeners with
* {@link #withListeners(HollowProducerEventListener...)}.
* @see #withListeners(HollowProducerEventListener...)
*/
public B withValidators(ValidatorListener... validators) {
return withListeners(validators);
}
public B withListener(HollowProducerListener listener) {
return withListener((HollowProducerEventListener) listener);
}
public B withListeners(HollowProducerListener... listeners) {
return withListeners((HollowProducerEventListener[]) listeners);
}
public B withVersionMinter(HollowProducer.VersionMinter versionMinter) {
this.versionMinter = versionMinter;
return (B) this;
}
public B withSnapshotPublishExecutor(Executor executor) {
this.snapshotPublishExecutor = executor;
return (B) this;
}
public B withNumStatesBetweenSnapshots(int numStatesBetweenSnapshots) {
this.numStatesBetweenSnapshots = numStatesBetweenSnapshots;
return (B) this;
}
public B withTargetMaxTypeShardSize(long targetMaxTypeShardSize) {
this.targetMaxTypeShardSize = targetMaxTypeShardSize;
return (B) this;
}
public B withFocusHoleFillInFewestShards(boolean focusHoleFillInFewestShards) {
this.focusHoleFillInFewestShards = focusHoleFillInFewestShards;
return (B) this;
}
public B withMetricsCollector(HollowMetricsCollector<HollowProducerMetrics> metricsCollector) {
this.metricsCollector = metricsCollector;
return (B) this;
}
public B withBlobStorageCleaner(BlobStorageCleaner blobStorageCleaner) {
this.blobStorageCleaner = blobStorageCleaner;
return (B) this;
}
public B withSingleProducerEnforcer(SingleProducerEnforcer singleProducerEnforcer) {
this.singleProducerEnforcer = singleProducerEnforcer;
return (B) this;
}
public B noSingleProducerEnforcer() {
this.singleProducerEnforcer = null;
return (B) this;
}
@Deprecated
public B withHashCodeFinder(HollowObjectHashCodeFinder hashCodeFinder) {
this.hashCodeFinder = hashCodeFinder;
return (B) this;
}
public B noIntegrityCheck() {
this.doIntegrityCheck = false;
return (B) this;
}
protected void checkArguments() {
if (stager != null && compressor != null) {
throw new IllegalArgumentException(
"Both a custom BlobStager and BlobCompressor were specified -- please specify only one of these.");
}
if (stager != null && stagingDir != null) {
throw new IllegalArgumentException(
"Both a custom BlobStager and a staging directory were specified -- please specify only one of these.");
}
if (stager != null && optionalPartConfig != null) {
throw new IllegalArgumentException(
"Both a custom BlobStager and an optional blob part config were specified -- please specify only one of these.");
}
if (this.stager == null) {
BlobCompressor compressor = this.compressor != null ? this.compressor : BlobCompressor.NO_COMPRESSION;
File stagingDir = this.stagingDir != null ? this.stagingDir : new File(System.getProperty("java.io.tmpdir"));
this.stager = new HollowFilesystemBlobStager(stagingDir.toPath(), compressor, optionalPartConfig);
}
}
/**
* Builds a producer where the complete data is populated.
*
* @return a producer.
*/
public HollowProducer build() {
checkArguments();
return new HollowProducer(this);
}
/**
* Builds an incremental producer where changes (additions, modifications, removals) are
* populated.
*
* @return an incremental producer
*/
public HollowProducer.Incremental buildIncremental() {
checkArguments();
return new HollowProducer.Incremental(this);
}
}
/**
* Provides the opportunity to clean the blob storage.
* It allows users to implement logic base on Blob Type.
*/
public static abstract class BlobStorageCleaner {
public void clean(Blob.Type blobType) {
switch (blobType) {
case SNAPSHOT:
cleanSnapshots();
break;
case DELTA:
cleanDeltas();
break;
case REVERSE_DELTA:
cleanReverseDeltas();
break;
}
}
/**
* This method provides an opportunity to remove old snapshots.
*/
public abstract void cleanSnapshots();
/**
* This method provides an opportunity to remove old deltas.
*/
public abstract void cleanDeltas();
/**
* This method provides an opportunity to remove old reverse deltas.
*/
public abstract void cleanReverseDeltas();
}
/**
* A producer of Hollow data that populates with given data changes (addition, modification or removal), termed
* incremental production.
* <p>
* A {@link HollowProducer} populates with all the given data after which changes are determined. Generally in
* other respects {@code HollowProducer} and {@code HollowProducer.Incremental} have the same behaviour when
* publishing and announcing data states.
*/
public static class Incremental extends AbstractHollowProducer {
protected Incremental(Builder<?> b) {
super(b);
}
/**
* Restores the data state to a desired version.
* <p>
* Data model {@link #initializeDataModel(Class[]) initialization} is required prior to
* restoring the producer. This ensures that restoration can correctly compare the producer's
* current data model with the data model of the restored data state and manage any differences
* in those models (such as not restoring state for any types in the restoring data model not
* present in the producer's current data model)
*
* @param versionDesired the desired version
* @param blobRetriever the blob retriever
* @return the read state of the restored state
* @throws IllegalStateException if the producer's data model has not been initialized
* @see #initializeDataModel(Class[])
*/
@Override
public HollowProducer.ReadState restore(long versionDesired, HollowConsumer.BlobRetriever blobRetriever) {
return super.hardRestore(versionDesired, blobRetriever);
}
/**
* Runs a cycle to incrementally populate, publish, and announce a new single data state.
*
* @param task the incremental populating task to add changes (additions, modifications, or deletions)
* @return the version identifier of the announced state, otherwise the
* last successful announced version if 1) there were no data changes compared to that version;
* or 2) the producer is not the primary producer
* @throws RuntimeException if the cycle failed
*/
// @@@ Should this be marked as synchronized?
public long runIncrementalCycle(Incremental.IncrementalPopulator task) {
return runCycle(task, null);
}
/**
* Represents a task that incrementally populates a new data state within a {@link HollowProducer} cycle (
* more specifically within the population stage)
*
* <p>This is a functional interface whose functional method is
* {@link #populate(IncrementalWriteState)}.
*/
@FunctionalInterface
public interface IncrementalPopulator {
/**
* Incrementally populates the provided {@link IncrementalWriteState} with new additions, modifications or
* removals of objects. Often written as a lambda passed in to
* {@link Incremental#runIncrementalCycle(IncrementalPopulator)}:
*
* <pre>{@code
* producer.runIncrementalCycle(incrementalState -> {
* Collection<C> changesA = queryA();
* for (Change c : changesA) {
* if (c.isAddOrModify() {
* incrementalState.addOrModify(c.getObject());
* } else {
* incrementalState.delete(c.getObject());
* }
* }
*
* changesB = queryB();
* // ...
* });
* }</pre>
*
* <p>Notes:
*
* <ul>
* <li>The data from the previous cycle is carried over with changes (additions, modifications or removals).
* <li>caught exceptions that are unrecoverable must be rethrown</li>
* <li>the provided {@code IncrementalWriteState} will be inoperable when this method returns; method
* calls against it will throw {@code IllegalStateException}</li>
* <li>the {@code IncrementalWriteState} is thread safe</li>
* </ul>
*
* <p>
* Incrementally populating asynchronously has these additional requirements:
* <ul>
* <li>MUST NOT return from this method until all workers have completed – either normally
* or exceptionally – or have been cancelled</li>
* <li>MUST throw an exception if any worker completed exceptionally. MAY cancel remaining tasks
* <em>or</em> wait for the remainder to complete.</li>
* </ul>
*
* @param state the state to add, modify or delete objects
* @throws Exception if population fails. If failure occurs the data from the previous cycle is not changed.
*/
void populate(IncrementalWriteState state) throws Exception;
}
/**
* Representation of write state that can be incrementally changed.
*/
public interface IncrementalWriteState {
/**
* Adds a new object or modifies an existing object. The object must define a primary key.
* <p>
* Calling this method after the producer's incremental populate stage has completed is an error.
*
* @param o the object
* @throws IllegalArgumentException if the object does not have primary key defined
*/
void addOrModify(Object o);
/**
* Adds a new object. If the object already exists no action is taken and the object is left unmodified.
* The object must define a primary key.
* <p>
* Calling this method after the producer's incremental populate stage has completed is an error.
*
* @param o the object
* @throws IllegalArgumentException if the object does not have primary key defined
*/
void addIfAbsent(Object o);
/**
* Deletes an object. The object must define a primary key.
* <p>
* This action is ignored if the object does not exist.
* <p>
* Calling this method after the producer's incremental populate stage has completed is an error.
*
* @param o the object
* @throws IllegalArgumentException if the object does not have primary key defined
*/
void delete(Object o);
/**
* Deletes an object given its primary key value.
* <p>
* If the object does not exist (has already been deleted, say) then this action as no effect on the
* write state.
* <p>
* Calling this method after the producer's incremental populate stage has completed is an error.
*
* @param key the primary key value
* @throws IllegalArgumentException if the field path of the primary key is not resolvable
*/
void delete(RecordPrimaryKey key);
}
}
}
| 9,220 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/ProducerListenerSupport.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.stream.Collectors.toList;
import com.netflix.hollow.api.common.ListenerSupport;
import com.netflix.hollow.api.common.Listeners;
import com.netflix.hollow.api.producer.HollowProducerListener.ProducerStatus;
import com.netflix.hollow.api.producer.IncrementalCycleListener.IncrementalCycleStatus;
import com.netflix.hollow.api.producer.listener.AnnouncementListener;
import com.netflix.hollow.api.producer.listener.CycleListener;
import com.netflix.hollow.api.producer.listener.DataModelInitializationListener;
import com.netflix.hollow.api.producer.listener.HollowProducerEventListener;
import com.netflix.hollow.api.producer.listener.IncrementalPopulateListener;
import com.netflix.hollow.api.producer.listener.IntegrityCheckListener;
import com.netflix.hollow.api.producer.listener.PopulateListener;
import com.netflix.hollow.api.producer.listener.PublishListener;
import com.netflix.hollow.api.producer.listener.RestoreListener;
import com.netflix.hollow.api.producer.validation.ValidationStatus;
import com.netflix.hollow.api.producer.validation.ValidationStatusListener;
import com.netflix.hollow.api.producer.validation.ValidatorListener;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
final class ProducerListenerSupport extends ListenerSupport {
private static final Logger LOG = Logger.getLogger(ProducerListenerSupport.class.getName());
private static final Collection<Class<? extends HollowProducerEventListener>> LISTENERS =
Stream.of(DataModelInitializationListener.class,
RestoreListener.class,
CycleListener.class,
PopulateListener.class,
PublishListener.class,
IntegrityCheckListener.class,
AnnouncementListener.class,
ValidatorListener.class,
ValidationStatusListener.class)
.distinct().collect(toList());
static boolean isValidListener(HollowProducerEventListener l) {
return LISTENERS.stream().anyMatch(c -> c.isInstance(l));
}
ProducerListenerSupport() {
// @@@ This is used only by HollowIncrementalProducer, and should be
// separated out
incrementalCycleListeners = new CopyOnWriteArraySet<>();
}
ProducerListenerSupport(List<? extends HollowProducerEventListener> listeners) {
super(listeners);
// @@@ This is used only by HollowIncrementalProducer, and should be
// separated out
incrementalCycleListeners = new CopyOnWriteArraySet<>();
}
ProducerListenerSupport(ProducerListenerSupport that) {
super(that);
// @@@ This is used only by HollowIncrementalProducer, and should be
// separated out
incrementalCycleListeners = new CopyOnWriteArraySet<>(that.incrementalCycleListeners);
}
//
/**
* Copies the collection of listeners so they can be iterated on without changing.
* From the returned copy events may be fired.
* Any addition or removal of listeners will take effect on the next cycle.
*/
ProducerListeners listeners() {
return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0]));
}
static final class ProducerListeners extends Listeners {
ProducerListeners(HollowProducerEventListener[] listeners) {
super(listeners);
}
void fireProducerInit(long elapsedMillis) {
fire(DataModelInitializationListener.class,
l -> l.onProducerInit(Duration.ofMillis(elapsedMillis)));
}
Status.RestoreStageBuilder fireProducerRestoreStart(long version) {
fire(RestoreListener.class,
l -> l.onProducerRestoreStart(version));
return new Status.RestoreStageBuilder();
}
void fireProducerRestoreComplete(Status.RestoreStageBuilder b) {
Status s = b.build();
long versionDesired = b.versionDesired;
long versionReached = b.versionReached;
Duration elapsed = b.elapsed();
fire(RestoreListener.class,
l -> l.onProducerRestoreComplete(s, versionDesired, versionReached, elapsed));
}
void fireNewDeltaChain(long version) {
fire(CycleListener.class,
l -> l.onNewDeltaChain(version));
}
void fireCycleSkipped(CycleListener.CycleSkipReason reason) {
fire(CycleListener.class,
l -> l.onCycleSkip(reason));
}
Status.StageWithStateBuilder fireCycleStart(long version) {
fire(CycleListener.class,
l -> l.onCycleStart(version));
return new Status.StageWithStateBuilder().version(version);
}
void fireCycleComplete(Status.StageWithStateBuilder b) {
Status s = b.build();
HollowProducer.ReadState readState = b.readState;
long version = b.version;
Duration elapsed = b.elapsed();
fire(CycleListener.class,
l -> l.onCycleComplete(s, readState, version, elapsed));
}
Status.IncrementalPopulateBuilder fireIncrementalPopulateStart(long version) {
fire(IncrementalPopulateListener.class,
l -> l.onIncrementalPopulateStart(version));
return new Status.IncrementalPopulateBuilder().version(version);
}
void fireIncrementalPopulateComplete(Status.IncrementalPopulateBuilder b) {
Status s = b.build();
long version = b.version;
Duration elapsed = b.elapsed();
long removed = b.removed;
long addedOrModified = b.addedOrModified;
fire(IncrementalPopulateListener.class,
l -> l.onIncrementalPopulateComplete(s, removed, addedOrModified, version, elapsed));
}
Status.StageBuilder firePopulateStart(long version) {
fire(PopulateListener.class,
l -> l.onPopulateStart(version));
return new Status.StageBuilder().version(version);
}
void firePopulateComplete(Status.StageBuilder b) {
Status s = b.build();
long version = b.version;
Duration elapsed = b.elapsed();
fire(PopulateListener.class,
l -> l.onPopulateComplete(s, version, elapsed));
}
void fireNoDelta(long version) {
fire(PublishListener.class,
l -> l.onNoDeltaAvailable(version));
}
Status.StageBuilder firePublishStart(long version) {
fire(PublishListener.class,
l -> l.onPublishStart(version));
return new Status.StageBuilder().version(version);
}
void fireBlobStage(Status.PublishBuilder b) {
Status s = b.build();
HollowProducer.Blob blob = b.blob;
Duration elapsed = b.elapsed();
fire(PublishListener.class,
l -> l.onBlobStage(s, blob, elapsed));
}
void fireBlobPublishAsync(CompletableFuture<HollowProducer.Blob> f) {
fire(PublishListener.class,
l -> l.onBlobPublishAsync(f));
}
void fireBlobPublish(Status.PublishBuilder b) {
Status s = b.build();
HollowProducer.Blob blob = b.blob;
Duration elapsed = b.elapsed();
fire(PublishListener.class,
l -> l.onBlobPublish(s, blob, elapsed));
}
void firePublishComplete(Status.StageBuilder b) {
Status s = b.build();
long version = b.version;
Duration elapsed = b.elapsed();
fire(PublishListener.class,
l -> l.onPublishComplete(s, version, elapsed));
}
Status.StageWithStateBuilder fireIntegrityCheckStart(HollowProducer.ReadState readState) {
long version = readState.getVersion();
fire(IntegrityCheckListener.class,
l -> l.onIntegrityCheckStart(version));
return new Status.StageWithStateBuilder().readState(readState);
}
void fireIntegrityCheckComplete(Status.StageWithStateBuilder b) {
Status s = b.build();
HollowProducer.ReadState readState = b.readState;
long version = b.version;
Duration elapsed = b.elapsed();
fire(IntegrityCheckListener.class,
l -> l.onIntegrityCheckComplete(s, readState, version, elapsed));
}
Status.StageWithStateBuilder fireValidationStart(HollowProducer.ReadState readState) {
long version = readState.getVersion();
fire(HollowProducerListener.class,
l -> l.onValidationStart(version));
fire(ValidationStatusListener.class,
l -> l.onValidationStatusStart(version));
return new Status.StageWithStateBuilder().readState(readState);
}
void fireValidationComplete(Status.StageWithStateBuilder b, ValidationStatus vs) {
Status s = b.build();
HollowProducer.ReadState readState = b.readState;
long version = b.version;
Duration elapsed = b.elapsed();
fire(HollowProducerListener.class,
l -> l.onValidationComplete(new ProducerStatus(s, readState, version),
elapsed.toMillis(), MILLISECONDS));
fire(ValidationStatusListener.class,
l -> l.onValidationStatusComplete(vs, version, elapsed));
}
Status.StageWithStateBuilder fireAnnouncementStart(HollowProducer.ReadState readState) {
long version = readState.getVersion();
fire(AnnouncementListener.class,
l -> l.onAnnouncementStart(version));
fire(AnnouncementListener.class,
l -> l.onAnnouncementStart(readState));
return new Status.StageWithStateBuilder().readState(readState);
}
void fireAnnouncementComplete(Status.StageWithStateBuilder b) {
Status s = b.build();
HollowProducer.ReadState readState = b.readState;
long version = b.version;
Duration elapsed = b.elapsed();
fire(AnnouncementListener.class,
l -> l.onAnnouncementComplete(s, readState, version, elapsed));
}
}
// @@@ This is used only by HollowIncrementalProducer, and should be
// separated out
private final Set<IncrementalCycleListener> incrementalCycleListeners;
void add(IncrementalCycleListener listener) {
incrementalCycleListeners.add(listener);
}
void remove(IncrementalCycleListener listener) {
incrementalCycleListeners.remove(listener);
}
private <T> void fire(Collection<T> ls, Consumer<? super T> r) {
fire(ls.stream(), r);
}
private <T> void fire(Stream<T> ls, Consumer<? super T> r) {
ls.forEach(l -> {
try {
r.accept(l);
} catch (RuntimeException e) {
LOG.log(Level.WARNING, "Error executing listener", e);
}
});
}
void fireIncrementalCycleComplete(
long version, long recordsAddedOrModified, long recordsRemoved,
Map<String, Object> cycleMetadata) {
// @@@ This behaviour appears incomplete, the build is created and built
// for each listener. The start time (builder creation) and end time (builder built)
// results in an effectively meaningless elasped time.
IncrementalCycleStatus.Builder icsb = new IncrementalCycleStatus.Builder()
.success(version, recordsAddedOrModified, recordsRemoved, cycleMetadata);
fire(incrementalCycleListeners,
l -> l.onCycleComplete(icsb.build(), icsb.elapsed(), MILLISECONDS));
}
void fireIncrementalCycleFail(
Throwable cause, long recordsAddedOrModified, long recordsRemoved,
Map<String, Object> cycleMetadata) {
IncrementalCycleStatus.Builder icsb = new IncrementalCycleStatus.Builder()
.fail(cause, recordsAddedOrModified, recordsRemoved, cycleMetadata);
fire(incrementalCycleListeners,
l -> l.onCycleFail(icsb.build(), icsb.elapsed(), MILLISECONDS));
}
}
| 9,221 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/IncrementalCycleListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer;
import static com.netflix.hollow.api.producer.IncrementalCycleListener.Status.FAIL;
import static com.netflix.hollow.api.producer.IncrementalCycleListener.Status.SUCCESS;
import java.util.EventListener;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Beta API subject to change.
*
* A class should implement {@code IncrementalCycleListener}, if it wants to be notified on start/completion of various stages of the {@link HollowIncrementalProducer}.
*
* @deprecated see {@link com.netflix.hollow.api.producer.listener.IncrementalPopulateListener}
* @see com.netflix.hollow.api.producer.listener.IncrementalPopulateListener
*/
@Deprecated
public interface IncrementalCycleListener extends EventListener {
/**
* Called after {@code HollowIncrementalProducer} has completed a cycle normally or abnormally. A {@code SUCCESS} status indicates that the
* entire cycle was successful and the producer is available to begin another cycle.
*
* @param status IncrementalCycleStatus of this cycle. {@link IncrementalCycleListener.IncrementalCycleStatus#getStatus()} will return {@code SUCCESS}
* when the a new data state has been announced to consumers or when there were no changes to the data.
* @param elapsed duration of the cycle in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
public void onCycleComplete(IncrementalCycleStatus status, long elapsed, TimeUnit unit);
/**
* Called after {@code HollowIncrementalProducer} has completed a cycle normally or abnormally. A {@code FAIL} status indicates that the
* entire cycle failed.
*
* @param status IncrementalCycleStatus of this cycle. {@link IncrementalCycleListener.IncrementalCycleStatus#getStatus()} will return {@code FAIL}
* @param elapsed duration of the cycle in {@code unit} units
* @param unit units of the {@code elapsed} duration
*/
public void onCycleFail(IncrementalCycleStatus status, long elapsed, TimeUnit unit);
public class IncrementalCycleStatus {
private final Status status;
private final long version;
private final long recordsAddedOrModified;
private final long recordsRemoved;
private final Map<String, Object> cycleMetadata;
private final Throwable throwable;
public IncrementalCycleStatus(Status status, long version, Throwable throwable, long recordsAddedOrModified, long recordsRemoved, Map<String, Object> cycleMetadata) {
this.status = status;
this.version = version;
this.recordsAddedOrModified = recordsAddedOrModified;
this.recordsRemoved = recordsRemoved;
this.cycleMetadata = cycleMetadata;
this.throwable = throwable;
}
/**
* This version is currently under process by {@code HollowIncrementalProducer} which matches with version of {@code HollowProducer}.
*
* @return Current version of the {@code HollowIncrementalProducer}.
*/
public long getVersion() {
return version;
}
/**
* Status of the latest stage completed by {@code HollowIncrementalProducer}.
*
* @return SUCCESS or FAIL.
*/
public Status getStatus() {
return status;
}
/**
*
* @return the number of records that potentially were added/modified from the dataset.
*/
public long getRecordsAddedOrModified() {
return recordsAddedOrModified;
}
/**
* @return the number of records that potentially were removed from the dataset.
*/
public long getRecordsRemoved() {
return recordsRemoved;
}
/**
* @return cycle metadata attached before runCycle in {@code HollowIncrementalProducer}
*/
public Map<String, Object> getCycleMetadata() {
return cycleMetadata;
}
/**
* Returns the failure cause if this status represents a {@code HollowProducer} failure that was caused by an exception.
*
* @return Throwable if {@code Status.equals(FAIL)} else null.
*/
public Throwable getCause() {
return throwable;
}
public static final class Builder {
private final long start;
private long end;
private long version = Long.MIN_VALUE;
private Status status = FAIL;
private Throwable cause = null;
private long recordsAddedOrModified;
private long recordsRemoved;
private Map<String, Object> cycleMetadata;
Builder() {
start = System.currentTimeMillis();
}
Builder success(long version, long recordsAddedOrModified, long recordsRemoved, Map<String, Object> cycleMetadata) {
this.status = SUCCESS;
this.version = version;
this.recordsAddedOrModified = recordsAddedOrModified;
this.recordsRemoved = recordsRemoved;
this.cycleMetadata = cycleMetadata;
return this;
}
Builder fail(Throwable cause, long recordsAddedOrModified, long recordsRemoved, Map<String, Object> cycleMetadata) {
this.status = FAIL;
this.cause = cause;
this.recordsAddedOrModified = recordsAddedOrModified;
this.recordsRemoved = recordsRemoved;
this.cycleMetadata = cycleMetadata;
return this;
}
IncrementalCycleStatus build() {
end = System.currentTimeMillis();
return new IncrementalCycleStatus(status, version, cause, recordsAddedOrModified, recordsRemoved, cycleMetadata);
}
long elapsed() {
return end - start;
}
}
}
public enum Status {
SUCCESS, FAIL
}
}
| 9,222 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/metrics/CycleMetrics.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.metrics;
import java.util.Optional;
import java.util.OptionalLong;
public class CycleMetrics {
private long consecutiveFailures;
private OptionalLong cycleDurationMillis; // Cycle start to end duration, only applicable to completed cycles
private Optional<Boolean> isCycleSuccess; // true if cycle was successful, false if cycle failed, N/A if cycle was skipped
private OptionalLong lastCycleSuccessTimeNano; // monotonic time of last successful cycle (no relation to wall clock), N/A until first successful cycle
public long getConsecutiveFailures() {
return consecutiveFailures;
}
public OptionalLong getCycleDurationMillis() {
return cycleDurationMillis;
}
public Optional<Boolean> getIsCycleSuccess() {
return isCycleSuccess;
}
public OptionalLong getLastCycleSuccessTimeNano() {
return lastCycleSuccessTimeNano;
}
private CycleMetrics(Builder builder) {
this.consecutiveFailures = builder.consecutiveFailures;
this.cycleDurationMillis = builder.cycleDurationMillis;
this.isCycleSuccess = builder.isCycleSuccess;
this.lastCycleSuccessTimeNano = builder.lastCycleSuccessTimeNano;
}
public static final class Builder {
private long consecutiveFailures;
private OptionalLong cycleDurationMillis;
private Optional<Boolean> isCycleSuccess;
private OptionalLong lastCycleSuccessTimeNano;
public Builder() {
isCycleSuccess = Optional.empty();
cycleDurationMillis = OptionalLong.empty();
lastCycleSuccessTimeNano = OptionalLong.empty();
}
public Builder setConsecutiveFailures(long consecutiveFailures) {
this.consecutiveFailures = consecutiveFailures;
return this;
}
public Builder setCycleDurationMillis(long cycleDurationMillis) {
this.cycleDurationMillis = OptionalLong.of(cycleDurationMillis);
return this;
}
public Builder setIsCycleSuccess(boolean isCycleSuccess) {
this.isCycleSuccess = Optional.of(isCycleSuccess);
return this;
}
public Builder setLastCycleSuccessTimeNano(long lastCycleSuccessTimeNano) {
this.lastCycleSuccessTimeNano = OptionalLong.of(lastCycleSuccessTimeNano);
return this;
}
public CycleMetrics build() {
return new CycleMetrics(this);
}
}
}
| 9,223 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/metrics/ProducerMetricsReporting.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.metrics;
/**
* Allows implementations to plug in custom reporting of producer metrics, while not enforcing that any or all metrics
* are reported. For example, an implementation might only be insterested in cycle metrics but not announcement metrics, etc.
*/
public interface ProducerMetricsReporting {
default void cycleMetricsReporting(CycleMetrics cycleMetrics) {
// no-op
}
default void announcementMetricsReporting(AnnouncementMetrics announcementMetrics) {
// no-op
}
}
| 9,224 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/metrics/AnnouncementMetrics.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.metrics;
import java.util.OptionalLong;
public class AnnouncementMetrics {
private long dataSizeBytes; // Heap footprint of announced blob in bytes
private long announcementDurationMillis; // Announcement duration in ms, only applicable to completed cycles (skipped cycles dont announce)
private boolean isAnnouncementSuccess; // true if announcement was successful, false if announcement failed
private OptionalLong lastAnnouncementSuccessTimeNano; // monotonic time of last successful announcement (no relation to wall clock), N/A until first successful announcement
public long getDataSizeBytes() {
return dataSizeBytes;
}
public long getAnnouncementDurationMillis() {
return announcementDurationMillis;
}
public boolean getIsAnnouncementSuccess() {
return isAnnouncementSuccess;
}
public OptionalLong getLastAnnouncementSuccessTimeNano() {
return lastAnnouncementSuccessTimeNano;
}
private AnnouncementMetrics(Builder builder) {
this.dataSizeBytes = builder.dataSizeBytes;
this.announcementDurationMillis = builder.announcementDurationMillis;
this.isAnnouncementSuccess = builder.isAnnouncementSuccess;
this.lastAnnouncementSuccessTimeNano = builder.lastAnnouncementSuccessTimeNano;
}
public static final class Builder {
private long dataSizeBytes;
private long announcementDurationMillis;
private boolean isAnnouncementSuccess;
private OptionalLong lastAnnouncementSuccessTimeNano;
public Builder() {
lastAnnouncementSuccessTimeNano = OptionalLong.empty();
}
public Builder setDataSizeBytes(long dataSizeBytes) {
this.dataSizeBytes = dataSizeBytes;
return this;
}
public Builder setAnnouncementDurationMillis(long announcementDurationMillis) {
this.announcementDurationMillis = announcementDurationMillis;
return this;
}
public Builder setIsAnnouncementSuccess(boolean isAnnouncementSuccess) {
this.isAnnouncementSuccess = isAnnouncementSuccess;
return this;
}
public Builder setLastAnnouncementSuccessTimeNano(long lastAnnouncementSuccessTimeNano) {
this.lastAnnouncementSuccessTimeNano = OptionalLong.of(lastAnnouncementSuccessTimeNano);
return this;
}
public AnnouncementMetrics build() {
return new AnnouncementMetrics(this);
}
}
}
| 9,225 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/metrics/AbstractProducerMetricsListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.metrics;
import com.netflix.hollow.api.producer.AbstractHollowProducerListener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import java.time.Duration;
import java.util.OptionalLong;
/**
* A class for computing Hollow Producer metrics, that requires extending subclasses to implement custom metrics reporting.
* <p>
* This class computes Hollow Producer metrics by listening to the stages of a producer's lifecycle. This class implements the
* {@code ProducerMetricsReporting} interface which enforces concrete subclasses to implement custom metrics reporting behavior.
*/
public abstract class AbstractProducerMetricsListener extends AbstractHollowProducerListener implements
ProducerMetricsReporting {
private AnnouncementMetrics.Builder announcementMetricsBuilder;
// visible for testing
private long consecutiveFailures;
OptionalLong lastCycleSuccessTimeNanoOptional;
OptionalLong lastAnnouncementSuccessTimeNanoOptional;
public AbstractProducerMetricsListener() {
consecutiveFailures = 0l;
lastCycleSuccessTimeNanoOptional = OptionalLong.empty();
lastAnnouncementSuccessTimeNanoOptional = OptionalLong.empty();
}
@Override
public void onAnnouncementStart(long version) {
announcementMetricsBuilder = new AnnouncementMetrics.Builder();
}
/**
* Reports metrics for when cycle is skipped due to reasons such as the producer not being the leader in a multiple-producer setting.
* In a multiple producer setting, leader election typically favors long-lived leaders to avoid producer runs from frequently requiring
* to reload the full state before publishing data. When a cycle is skipped because the producer wasn't primary, the current value of
* no. of consecutive failures and most recent cycle success time are retained, and no cycle status (success or fail) is reported.
* @param reason Reason why the run was skipped
*/
@Override
public void onCycleSkip(CycleSkipReason reason) {
CycleMetrics.Builder cycleMetricsBuilder = new CycleMetrics.Builder();
cycleMetricsBuilder.setConsecutiveFailures(consecutiveFailures);
lastCycleSuccessTimeNanoOptional.ifPresent(cycleMetricsBuilder::setLastCycleSuccessTimeNano);
// isCycleSuccess and cycleDurationMillis are not set for skipped cycles
cycleMetricsReporting(cycleMetricsBuilder.build());
}
/**
* Reports announcement-related metrics.
* @param status Indicates whether the announcement succeeded of failed
* @param readState Hollow data state that is being published, used in this method for computing data size
* @param version Version of data that was announced
* @param elapsed Announcement start to end duration
*/
@Override
public void onAnnouncementComplete(com.netflix.hollow.api.producer.Status status, HollowProducer.ReadState readState, long version, Duration elapsed) {
boolean isAnnouncementSuccess = false;
long dataSizeBytes = 0l;
if (status.getType() == com.netflix.hollow.api.producer.Status.StatusType.SUCCESS) {
isAnnouncementSuccess = true;
lastAnnouncementSuccessTimeNanoOptional = OptionalLong.of(System.nanoTime());
}
HollowReadStateEngine stateEngine = readState.getStateEngine();
dataSizeBytes = stateEngine.calcApproxDataSize();
announcementMetricsBuilder
.setDataSizeBytes(dataSizeBytes)
.setIsAnnouncementSuccess(isAnnouncementSuccess)
.setAnnouncementDurationMillis(elapsed.toMillis());
lastAnnouncementSuccessTimeNanoOptional.ifPresent(announcementMetricsBuilder::setLastAnnouncementSuccessTimeNano);
announcementMetricsReporting(announcementMetricsBuilder.build());
}
/**
* On cycle completion this method reports cycle metrics.
* @param status Whether the cycle succeeded or failed
* @param readState Hollow data state published by cycle, not used here because data size is known from when announcement completed
* @param version Version of data that was published in this cycle
* @param elapsed Cycle start to end duration
*/
@Override
public void onCycleComplete(com.netflix.hollow.api.producer.Status status, HollowProducer.ReadState readState, long version, Duration elapsed) {
boolean isCycleSuccess;
long cycleEndTimeNano = System.nanoTime();
if (status.getType() == com.netflix.hollow.api.producer.Status.StatusType.SUCCESS) {
isCycleSuccess = true;
consecutiveFailures = 0l;
lastCycleSuccessTimeNanoOptional = OptionalLong.of(cycleEndTimeNano);
} else {
isCycleSuccess = false;
consecutiveFailures ++;
}
CycleMetrics.Builder cycleMetricsBuilder = new CycleMetrics.Builder()
.setConsecutiveFailures(consecutiveFailures)
.setCycleDurationMillis(elapsed.toMillis())
.setIsCycleSuccess(isCycleSuccess);
lastCycleSuccessTimeNanoOptional.ifPresent(cycleMetricsBuilder::setLastCycleSuccessTimeNano);
cycleMetricsReporting(cycleMetricsBuilder.build());
}
}
| 9,226 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/RestoreListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
/**
* A listener of restore events associated with the producer restore stage.
* <p>
* A cycle listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface RestoreListener extends HollowProducerEventListener {
/**
* Called after the {@code HollowProducer} has restored its data state to the indicated version.
* If previous state is not available to restore from, then this callback will not be called.
*
* @param restoreVersion Version from which the state for {@code HollowProducer} was restored.
*/
void onProducerRestoreStart(long restoreVersion);
/**
* Called after the {@code HollowProducer} has restored its data state to the indicated version.
* If previous state is not available to restore from, then this callback will not be called.
*
* @param status of the restore. {@link Status#getType()} will return {@code SUCCESS} when
* the desired version was reached during restore, otherwise {@code FAIL} will be returned.
* @param versionDesired the desired version to restore to
* @param versionReached the actual version restored to
* @param elapsed duration of the restore in {@code unit} units
*/
void onProducerRestoreComplete(Status status, long versionDesired, long versionReached, Duration elapsed);
}
| 9,227 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/CycleListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import com.netflix.hollow.api.producer.validation.ValidationStatusListener;
import java.time.Duration;
/**
* A listener of cycle events associated with the producer cycle stage.
* <p>
* A cycle listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface CycleListener extends HollowProducerEventListener {
/**
* The reasons for a cycle skip event
*/
enum CycleSkipReason {
/**
* The cycle is skipped because the producer is not a primary producer.
*/
NOT_PRIMARY_PRODUCER
}
/**
* A receiver of a cycle skip event. Called when a cycle is skipped.
* <p>
* If this event occurs then no further cycle events (or any events associated with sub-stages) will occur and
* the cycle stage is complete.
*
* @param reason the reason the cycle is skipped
*/
// See HollowProducerListenerV2
// Can this be merged in to onCycleComplete with status?
void onCycleSkip(CycleSkipReason reason);
/**
* A receiver of a new delta chain event. Called when the next state produced will begin a new delta chain.
* Occurs before the {@link #onCycleStart(long) cycle start} event.
* <p>
* This will be called prior to the next state being produced if
* {@link HollowProducer#restore(long, com.netflix.hollow.api.consumer.HollowConsumer.BlobRetriever)}
* hasn't been called or the restore failed.
*
* @param version the version of the state that will become the first of a new delta chain
*/
// This is called just before onCycleStart, can the two be merged with additional arguments?
void onNewDeltaChain(long version);
/**
* A receiver of a cycle start event. Called when the {@code HollowProducer} has begun a new cycle.
*
* @param version the version produced by the {@code HollowProducer} for new cycle about to start.
*/
void onCycleStart(long version);
/**
* A receiver of a cycle complete event. Called after the {@code HollowProducer} has completed a cycle
* with success or failure. Occurs after the {@link #onCycleStart(long) cycle start} event.
* <p>
* If the cycle is successful then the {@code status} reports
* {@link Status.StatusType#SUCCESS success}. Success indicates that a new state has been as been
* {@link PopulateListener populated},
* {@link PublishListener published},
* {@link IntegrityCheckListener integrity checked},
* {@link ValidationStatusListener validated}, and
* {@link AnnouncementListener announced}.
* Alternatively success may also indicate that population resulted in no changes and therefore there is no new
* state to publish and announce. If so a {@link PublishListener#onNoDeltaAvailable(long) no delta available}
* event of the {@link PublishListener publisher} stage is be emitted after which the cycle complete event is
* emitted.
* <p>
* If the cycle failed then the {@code status} reports {@link Status.StatusType#FAIL failure}.
*
* @param status the status of this cycle.
* @param readState the read state, null if no read state avaulable
* @param version the version
* @param elapsed duration of the cycle
*/
void onCycleComplete(Status status, HollowProducer.ReadState readState, long version, Duration elapsed);
}
| 9,228 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/PopulateListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
/**
* A listener of populate events associated with the populate cycle stage.
* <p>
* A populate listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface PopulateListener extends HollowProducerEventListener {
/**
* Called before starting to execute the task to populate data into Hollow.
*
* @param version current version of the cycle
*/
void onPopulateStart(long version);
/**
* Called once the populating task stage has finished successfully or failed.
* Use {@link Status#getType()} to get status of the task.
*
* @param status A value of {@code SUCCESS} indicates that all data was successfully populated.
* {@code FAIL} status indicates populating hollow with data failed.
* @param version current version of the cycle
* @param elapsed Time taken to populate hollow.
*/
void onPopulateComplete(Status status, long version, Duration elapsed);
}
| 9,229 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/PublishListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
/**
* A listener of publish events associated with the producer publish stage.
* <p>
* A publish listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface PublishListener extends HollowProducerEventListener {
// Called after populateComplete and instead of publish
// Can be merged in to PublishListener?
/**
* Called after the new state has been populated if the {@code HollowProducer} detects that no data has changed,
* thus no snapshot nor delta should be produced.<p>
*
* @param version Current version of the cycle.
*/
void onNoDeltaAvailable(long version);
/**
* Called when the {@code HollowProducer} has begun publishing the {@code HollowBlob}s produced this cycle.
*
* @param version version to be published.
*/
void onPublishStart(long version);
/**
* Called once a blob has been staged successfully or failed to stage.
* This method is called for every {@link HollowProducer.Blob.Type} that
* was staged.
*
* @param status status of staging. {@link Status#getType()} returns {@code SUCCESS} or {@code FAIL}.
* @param blob the blob
* @param elapsed time taken to stage the blob
*/
default void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) {
}
/**
* Called once a blob has been published successfully or failed to published.
* This method is called for every {@link HollowProducer.Blob.Type} that
* was published.
*
* @param status status of publishing. {@link Status#getType()} returns {@code SUCCESS} or {@code FAIL}.
* @param blob the blob
* @param elapsed time taken to publish the blob
*/
void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed);
/**
* Called if a blob is to be published asynchronously.
* This method is called for a {@link HollowProducer.Blob.Type#SNAPSHOT snapshot} blob when the
* producer is {@link HollowProducer.Builder#withSnapshotPublishExecutor(Executor) built} with a snapshot
* publish executor (that enables asynchronous publication).
*
* @param blob the future holding the blob that will be completed successfully when the blob has been published
* or with error if publishing failed. When the blob future completes the contents of the blob are only
* guaranteed to be available if further stages are executed using the default execution mode of this future
* (i.e. use of asynchronous execution could result in a subsequent stage completing after the blob contents have
* been cleaned up).
*/
default void onBlobPublishAsync(CompletableFuture<HollowProducer.Blob> blob) {
}
/**
* Called after the publish stage finishes normally or abnormally. A {@code SUCCESS} status indicates that
* the {@code HollowBlob}s produced this cycle has been published to the blob store.
*
* @param status CycleStatus of the publish stage. {@link Status#getType()} will return {@code SUCCESS}
* when the publish was successful; @{code FAIL} otherwise.
* @param version version that was published.
* @param elapsed duration of the publish stage in {@code unit} units
*/
void onPublishComplete(Status status, long version, Duration elapsed);
}
| 9,230 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/VetoableListener.java | package com.netflix.hollow.api.producer.listener;
/**
* A marker interface to be implemented by a listener which indicates that any runtime exception
* thrown by any of the listener's methods will be rethrown rather than, by default, caught and not
* thrown.
* <p>
* This interface may be used by a listener to veto a cycle and cause the producer to fail.
*/
public interface VetoableListener {
/**
* A listener method may throw this exception which will be rethrown rather than caught and not
* thrown. This exception may be utilized when the listener does not implement {@link VetoableListener}
* and requires finer-grain control over which of the listener's methods may veto a cycle and cause the
* producer to fail.
*/
class ListenerVetoException extends RuntimeException {
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public ListenerVetoException() {
super();
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public ListenerVetoException(String message) {
super(message);
}
/**
* Constructs a new runtime exception with the specified detail message and
* cause.
* <p>
* Note that the detail message associated with {@code cause} is
* <i>not</i> automatically incorporated in this runtime exception's detail
* message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public ListenerVetoException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new runtime exception with the specified cause and a
* detail message of {@code (cause==null ? null : cause.toString())}
* (which typically contains the class and detail message of
* {@code cause<}). This constructor is useful for runtime exceptions
* that are little more than wrappers for other throwables.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
public ListenerVetoException(Throwable cause) {
super(cause);
}
}
}
| 9,231 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/HollowProducerEventListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.common.EventListener;
/**
* The top-level type for all producer-specific listeners.
*/
public interface HollowProducerEventListener extends EventListener {
}
| 9,232 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/IncrementalPopulateListener.java | package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
/**
* A listener of incremental population events associated with the populate cycle stage.
* <p>
* A populate listener instance may be registered when building a incremental
* {@link com.netflix.hollow.api.producer.HollowProducer.Incremental producer}
* (see {@link com.netflix.hollow.api.producer.HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link com.netflix.hollow.api.producer.HollowProducer.Incremental#addListener(HollowProducerEventListener)}.
*/
public interface IncrementalPopulateListener extends HollowProducerEventListener {
/**
* Called before starting to execute the task to incrementally populate data into Hollow.
*
* @param version current version of the cycle
*/
void onIncrementalPopulateStart(long version);
/**
* Called once the incremental populating task stage has finished successfully or failed.
* Use {@link Status#getType()} to get status of the task.
*
* @param status A value of {@code SUCCESS} indicates that all data was successfully populated.
* {@code FAIL} status indicates populating hollow with data failed.
* @param removed the number of records removed
* @param addedOrModified the number of records added or modified
* @param version current version of the cycle
* @param elapsed Time taken to populate hollow.
*/
void onIncrementalPopulateComplete(Status status,
long removed, long addedOrModified,
long version, Duration elapsed);
}
| 9,233 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/DataModelInitializationListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.core.schema.HollowSchema;
import java.time.Duration;
/**
* A listener of data model initialization events.
* <p>
* A producer will emit a data model initialization after the data model is initialized when
* {@link HollowProducer#initializeDataModel(Class[]) registering} top-level data model classes
* or when {@link HollowProducer#initializeDataModel(HollowSchema[]) registering} schemas.
* <p>
* A data model initialization instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface DataModelInitializationListener extends HollowProducerEventListener {
/**
* Called after the {@code HollowProducer} has initialized its data model.
* @param elapsed the elapsed duration
*/
void onProducerInit(Duration elapsed);
}
| 9,234 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/IntegrityCheckListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
/**
* A listener of integrity check events associated with the producer integrity check stage.
* <p>
* An integrity check listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface IntegrityCheckListener extends HollowProducerEventListener {
/**
* Called when the {@code HollowProducer} has begun checking the integrity of the {@code HollowBlob}s produced this cycle.
*
* @param version version to be checked
*/
void onIntegrityCheckStart(long version);
/**
* Called after the integrity check stage finishes normally or abnormally. A {@code SUCCESS} status indicates that
* the previous snapshot, current snapshot, delta, and reverse-delta {@code HollowBlob}s are all internally consistent.
*
* @param status CycleStatus of the integrity check stage. {@link Status#getType()} will return {@code SUCCESS}
* when the blobs are internally consistent; @{code FAIL} otherwise.
* @param readState the read state
* @param version version that was checked
* @param elapsed duration of the integrity check stage in {@code unit} units
*/
void onIntegrityCheckComplete(Status status, HollowProducer.ReadState readState, long version, Duration elapsed);
}
| 9,235 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/listener/AnnouncementListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.listener;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.Status;
import java.time.Duration;
/**
* A listener of announcement events associated with the producer announcement stage.
* <p>
* A announcement listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface AnnouncementListener extends HollowProducerEventListener {
/**
* Called when the {@code HollowProducer} has begun announcing the {@code HollowBlob} published this cycle.
*
* @param version of {@code HollowBlob} that will be announced.
*/
void onAnnouncementStart(long version);
/**
* Called when the {@code HollowProducer} has begun announcing the {@code HollowBlob} published this cycle.
* This method is useful for cases where the read state passed from upstream can be used to compute added,
* removed and updated ordinals.
*
* @param readState the read state
*
*/
default void onAnnouncementStart(HollowProducer.ReadState readState) { };
/**
* Called after the announcement stage finishes normally or abnormally. A {@code SUCCESS} status indicates
* that the {@code HollowBlob} published this cycle has been announced to consumers.
*
* @param status CycleStatus of the announcement stage. {@link Status#getType()} will return {@code SUCCESS}
* when the announce was successful; @{code FAIL} otherwise.
* @param readState the read state
* @param version of {@code HollowBlob} that was announced.
* @param elapsed duration of the announcement stage in {@code unit} units
*/
void onAnnouncementComplete(Status status, HollowProducer.ReadState readState, long version, Duration elapsed);
}
| 9,236 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/enforcer/SingleProducerEnforcer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.enforcer;
/*
* Allow implementations for restricting a single producer in a distributed system.
*/
public interface SingleProducerEnforcer {
/**
* Mark producer to enable processing cycles. Default implementation (BasicSingleProducerEnforcer) is enabled by default.
*/
void enable();
/**
* Relinquish the primary producer status. disable() can be invoked any time, and it gives up producer primary
* status thereby allowing a different producer to acquire primary status. If the current producer is mid-cycle
* then the cycle continues on but will result in an announcement failure.
*/
void disable();
/**
* runCycle() is executed only if isPrimary() is true
* @return boolean
*/
boolean isPrimary();
/**
* Force marking producer to enable processing cycles.
*/
void force();
/**
* Lock local changes to primary status i.e. block enable or disable until unlock is called
*/
default void lock() {}
/**
* Unlock local changes to producer primary status i.e. enable/disable are unblocked
*/
default void unlock() {}
}
| 9,237 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/enforcer/BasicSingleProducerEnforcer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.enforcer;
public class BasicSingleProducerEnforcer extends AbstractSingleProducerEnforcer {
private boolean isPrimary = true;
@Override
protected void _enable() {
isPrimary = true;
}
@Override
protected void _disable() {
isPrimary = false;
}
@Override
protected boolean _isPrimary() {
return isPrimary;
}
@Override
protected void _force() {
isPrimary = true;
}
}
| 9,238 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/enforcer/AbstractSingleProducerEnforcer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.enforcer;
import com.netflix.hollow.api.producer.AbstractHollowProducerListener;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractSingleProducerEnforcer extends AbstractHollowProducerListener implements SingleProducerEnforcer {
private boolean hasCycleStarted = false;
private boolean doStopUponCycleComplete = false;
private boolean wasPrimary = false;
private final Logger logger = Logger.getLogger(AbstractSingleProducerEnforcer.class.getName());
private final Lock lock = new ReentrantLock();
protected abstract void _enable();
protected abstract void _disable();
protected abstract boolean _isPrimary();
protected void _force() {
throw new UnsupportedOperationException("forcing a producer to become primary is not supported");
}
@Override
public void enable() {
if (_isPrimary()) {
return;
}
lock.lock();
try {
_enable();
} finally {
lock.unlock();
}
}
@Override
public void disable() {
if (!hasCycleStarted) {
disableNow();
} else {
doStopUponCycleComplete = true;
}
}
@Override
public boolean isPrimary() {
final boolean primary = _isPrimary();
if (!primary) {
if (wasPrimary) {
logger.log(Level.WARNING, "SingleProducerEnforcer: lost primary producer status");
}
} else {
wasPrimary = true;
}
return primary;
}
@Override
public void force() {
if (_isPrimary()) {
return;
}
_force();
}
@Override
public void lock() {
lock.lock();
}
@Override public void unlock() {
lock.unlock();
}
@Override
public void onCycleStart(long version) {
hasCycleStarted = true;
}
@Override
public void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit) {
hasCycleStarted = false;
if (doStopUponCycleComplete) {
disableNow();
}
}
private void disableNow() {
if (_isPrimary()) {
lock.lock();
try {
_disable();
} finally {
lock.unlock();
}
}
doStopUponCycleComplete = false;
wasPrimary = false;
}
// visible for testing
protected boolean getWasPrimary() {
return wasPrimary;
}
}
| 9,239 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/fs/HollowFilesystemAnnouncer.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.fs;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import com.netflix.hollow.api.producer.HollowProducer;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HollowFilesystemAnnouncer implements HollowProducer.Announcer {
public static final String ANNOUNCEMENT_FILENAME = "announced.version";
public static final String ANNOUNCEMENT_FILENAME_TEMPORARY = "announced.version.tmp";
private final Path publishPath;
/**
* @param publishPath the path to publish to
* @since 2.12.0
*/
public HollowFilesystemAnnouncer(Path publishPath) {
this.publishPath = publishPath;
}
@Override
public void announce(long stateVersion) {
Path announcePath = publishPath.resolve(ANNOUNCEMENT_FILENAME);
Path announcePathTmp = publishPath.resolve(ANNOUNCEMENT_FILENAME_TEMPORARY);
try {
Files.write(announcePathTmp, String.valueOf(stateVersion).getBytes());
Files.move(announcePathTmp, announcePath, REPLACE_EXISTING);
} catch (IOException ex) {
throw new RuntimeException("Unable to write to announcement file; path=" + announcePath, ex);
}
}
}
| 9,240 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/fs/HollowFilesystemBlobStager.java | /*
* Copyright 2016-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.fs;
import static com.netflix.hollow.api.producer.HollowProducer.Blob.Type.DELTA;
import static com.netflix.hollow.api.producer.HollowProducer.Blob.Type.REVERSE_DELTA;
import static com.netflix.hollow.api.producer.HollowProducer.Blob.Type.SNAPSHOT;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.HollowProducer.Blob;
import com.netflix.hollow.api.producer.HollowProducer.BlobCompressor;
import com.netflix.hollow.api.producer.HollowProducer.BlobStager;
import com.netflix.hollow.api.producer.HollowProducer.HeaderBlob;
import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig;
import com.netflix.hollow.core.HollowConstants;
import com.netflix.hollow.core.write.HollowBlobWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class HollowFilesystemBlobStager implements BlobStager {
protected Path stagingPath;
protected BlobCompressor compressor;
protected ProducerOptionalBlobPartConfig optionalPartConfig;
/**
* Constructor to create a new HollowFilesystemBlobStager with default disk path
* (java.io.tmpdir) and no compression for Hollow blobs.
*/
public HollowFilesystemBlobStager() {
this(Paths.get(System.getProperty("java.io.tmpdir")), BlobCompressor.NO_COMPRESSION);
}
/**
* Constructor to create a new HollowFilesystemBlobStager with specified disk
* path and compression for Hollow blobs.
*
* @param stagingPath the path where to stage blobs
* @param compressor the blob compressor
* @throws RuntimeException if errors occur when creating the specified path
*/
public HollowFilesystemBlobStager(Path stagingPath, BlobCompressor compressor) throws RuntimeException {
this(stagingPath, compressor, null);
}
public HollowFilesystemBlobStager(Path stagingPath, BlobCompressor compressor, ProducerOptionalBlobPartConfig optionalPartConfig) throws RuntimeException {
this.stagingPath = stagingPath;
this.compressor = compressor;
this.optionalPartConfig = optionalPartConfig;
try {
if (!Files.exists(stagingPath))
Files.createDirectories(stagingPath);
} catch (IOException e) {
throw new RuntimeException("Could not create folder; path=" + this.stagingPath, e);
}
}
/**
* Constructor to create a new HollowFilesystemBlobStager with specified disk
* path and compression for Hollow blobs.
*
* @param stagingPath directory to use to write hollow blob files.
* @param compressor the {@link HollowProducer.BlobCompressor} to compress blob files with
* @deprecated Use Path instead
* @since 2.12.0
*/
@Deprecated
public HollowFilesystemBlobStager(File stagingPath, BlobCompressor compressor) {
this(stagingPath.toPath(), compressor);
}
@Override
public HollowProducer.Blob openSnapshot(long version) {
return new FilesystemBlob(HollowConstants.VERSION_NONE, version, SNAPSHOT, stagingPath, compressor, optionalPartConfig);
}
@Override
public HollowProducer.Blob openDelta(long fromVersion, long toVersion) {
return new FilesystemBlob(fromVersion, toVersion, DELTA, stagingPath, compressor, optionalPartConfig);
}
@Override
public HollowProducer.Blob openReverseDelta(long fromVersion, long toVersion) {
return new FilesystemBlob(fromVersion, toVersion, REVERSE_DELTA, stagingPath, compressor, optionalPartConfig);
}
@Override
public HollowProducer.HeaderBlob openHeader(long version) {
return new FilesystemHeaderBlob(version, stagingPath, compressor);
}
public static class FilesystemHeaderBlob extends HeaderBlob {
protected final Path path;
private final BlobCompressor compressor;
protected FilesystemHeaderBlob(long version, Path dirPath, BlobCompressor compressor) {
super(version);
this.compressor = compressor;
int randomExtension = new Random().nextInt() & Integer.MAX_VALUE;
this.path = dirPath.resolve(String.format("header-%d.%s", version, Integer.toHexString(randomExtension)));
}
@Override
public void cleanup() {
if (path != null) {
try {
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException("Could not cleanup file: " + this.path, e);
}
}
}
@Override
public void write(HollowBlobWriter blobWriter) throws IOException {
Path parent = this.path.getParent();
if (!Files.exists(parent))
Files.createDirectories(parent);
if (!Files.exists(path))
Files.createFile(path);
try (OutputStream os = new BufferedOutputStream(compressor.compress(Files.newOutputStream(path)))) {
blobWriter.writeHeader(os, null);
}
}
@Override
public InputStream newInputStream() throws IOException {
return new BufferedInputStream(compressor.decompress(Files.newInputStream(this.path)));
}
@Override
public File getFile() {
return path.toFile();
}
@Override
public Path getPath() {
return path;
}
}
public static class FilesystemBlob extends Blob {
protected final Path path;
protected final Map<String, Path> optionalPartPaths;
private final BlobCompressor compressor;
private FilesystemBlob(long fromVersion, long toVersion, Type type, Path dirPath, BlobCompressor compressor, ProducerOptionalBlobPartConfig optionalPartConfig) {
super(fromVersion, toVersion, type, optionalPartConfig);
this.optionalPartPaths = optionalPartConfig == null ? Collections.emptyMap() : new HashMap<>();
this.compressor = compressor;
int randomExtension = new Random().nextInt() & Integer.MAX_VALUE;
switch (type) {
case SNAPSHOT:
this.path = dirPath.resolve(String.format("%s-%d.%s", type.prefix, toVersion, Integer.toHexString(randomExtension)));
break;
case DELTA:
case REVERSE_DELTA:
this.path = dirPath.resolve(String.format("%s-%d-%d.%s", type.prefix, fromVersion, toVersion, Integer.toHexString(randomExtension)));
break;
default:
throw new IllegalStateException("unknown blob type, type=" + type);
}
if (optionalPartConfig != null) {
for (String part : optionalPartConfig.getParts()) {
Path partPath;
switch (type) {
case SNAPSHOT:
partPath = dirPath.resolve(String.format("%s_%s-%d.%s", type.prefix, part, toVersion, Integer.toHexString(randomExtension)));
break;
case DELTA:
case REVERSE_DELTA:
partPath = dirPath.resolve(String.format("%s_%s-%d-%d.%s", type.prefix, part, fromVersion, toVersion, Integer.toHexString(randomExtension)));
break;
default:
throw new IllegalStateException("unknown blob type, type=" + type);
}
optionalPartPaths.put(part, partPath);
}
}
}
@Override
public File getFile() {
return path.toFile();
}
@Override
public Path getPath() {
return path;
}
@Override
public void write(HollowBlobWriter writer) throws IOException {
Path parent = this.path.getParent();
if (!Files.exists(parent))
Files.createDirectories(parent);
if (!Files.exists(path))
Files.createFile(path);
ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams optionalPartStreams = null;
if (optionalPartConfig != null) {
optionalPartStreams = optionalPartConfig.newStreams();
for (Map.Entry<String, Path> partPathEntry : optionalPartPaths.entrySet()) {
String partName = partPathEntry.getKey();
Path partPath = partPathEntry.getValue();
optionalPartStreams.addOutputStream(partName, new BufferedOutputStream(compressor.compress(Files.newOutputStream(partPath))));
}
}
try (OutputStream os = new BufferedOutputStream(compressor.compress(Files.newOutputStream(path)))) {
switch (type) {
case SNAPSHOT:
writer.writeSnapshot(os, optionalPartStreams);
break;
case DELTA:
writer.writeDelta(os, optionalPartStreams);
break;
case REVERSE_DELTA:
writer.writeReverseDelta(os, optionalPartStreams);
break;
default:
throw new IllegalStateException("unknown type, type=" + type);
}
} finally {
if (optionalPartStreams != null)
optionalPartStreams.close();
}
}
@Override
public InputStream newInputStream() throws IOException {
return new BufferedInputStream(compressor.decompress(Files.newInputStream(this.path)));
}
@Override
public InputStream newOptionalPartInputStream(String partName) throws IOException {
Path partPath = optionalPartPaths.get(partName);
if (partPath == null)
throw new IllegalArgumentException("Path for part " + partName + " does not exist.");
return new BufferedInputStream(compressor.decompress(Files.newInputStream(partPath)));
}
@Override
public Path getOptionalPartPath(String partName) {
Path partPath = optionalPartPaths.get(partName);
if (partPath == null)
throw new IllegalArgumentException("Path for part " + partName + " does not exist.");
return partPath;
}
@Override
public void cleanup() {
cleanupFile(path);
for (Map.Entry<String, Path> entry : optionalPartPaths.entrySet()) {
cleanupFile(entry.getValue());
}
}
private void cleanupFile(Path path) {
try {
if (path != null)
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException("Could not cleanup file: " + this.path.toString(), e);
}
}
}
}
| 9,241 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/fs/HollowFilesystemPublisher.java | /*
* Copyright 2016-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.fs;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class HollowFilesystemPublisher implements HollowProducer.Publisher {
private final Path blobStorePath;
/**
* @param blobStorePath the path to store blobs
* @since 2.12.0
*/
public HollowFilesystemPublisher(Path blobStorePath) {
this.blobStorePath = blobStorePath;
try {
if (!Files.exists(this.blobStorePath)){
Files.createDirectories(this.blobStorePath);
}
} catch (IOException e) {
throw new RuntimeException("Could not create folder for publisher; path=" + this.blobStorePath, e);
}
}
@Override
// For backwards compatability.
public void publish(HollowProducer.Blob blob) {
publishBlob(blob);
}
@Override
public void publish(HollowProducer.PublishArtifact publishArtifact) {
if (publishArtifact instanceof HollowProducer.HeaderBlob) {
publishHeader((HollowProducer.HeaderBlob) publishArtifact);
} else {
publishBlob((HollowProducer.Blob) publishArtifact);
}
}
private void publishContent(HollowProducer.PublishArtifact publishArtifact, Path destination) {
try (
InputStream is = publishArtifact.newInputStream();
OutputStream os = Files.newOutputStream(destination)
) {
byte buf[] = new byte[4096];
int n;
while (-1 != (n = is.read(buf)))
os.write(buf, 0, n);
} catch (IOException e) {
throw new RuntimeException("Unable to publish file!", e);
}
}
private void publishHeader(HollowProducer.HeaderBlob headerBlob) {
Path destination = blobStorePath.resolve(String.format("header-%d", headerBlob.getVersion()));
publishContent(headerBlob, destination);
}
private void publishBlob(HollowProducer.Blob blob) {
Path destination = null;
switch(blob.getType()) {
case SNAPSHOT:
destination = blobStorePath.resolve(String.format("%s-%d", blob.getType().prefix, blob.getToVersion()));
break;
case DELTA:
case REVERSE_DELTA:
destination = blobStorePath.resolve(String.format("%s-%d-%d", blob.getType().prefix, blob.getFromVersion(), blob.getToVersion()));
break;
}
publishContent(blob, destination);
ProducerOptionalBlobPartConfig optionalPartConfig = blob.getOptionalPartConfig();
if(optionalPartConfig != null) {
for(String partName : optionalPartConfig.getParts()) {
Path partDestination = null;
switch(blob.getType()) {
case SNAPSHOT:
partDestination = blobStorePath.resolve(String.format("%s_%s-%d", blob.getType().prefix, partName, blob.getToVersion()));
break;
case DELTA:
case REVERSE_DELTA:
partDestination = blobStorePath.resolve(String.format("%s_%s-%d-%d", blob.getType().prefix, partName, blob.getFromVersion(), blob.getToVersion()));
break;
}
try(
InputStream is = blob.newOptionalPartInputStream(partName);
OutputStream os = Files.newOutputStream(partDestination)
) {
byte buf[] = new byte[4096];
int n;
while (-1 != (n = is.read(buf)))
os.write(buf, 0, n);
} catch(IOException e) {
throw new RuntimeException("Unable to publish optional part file: " + partName, e);
}
}
}
}
}
| 9,242 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/fs/HollowInMemoryBlobStager.java | /*
* Copyright 2016-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.fs;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.HollowProducer.Blob;
import com.netflix.hollow.api.producer.HollowProducer.HeaderBlob;
import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig;
import com.netflix.hollow.core.HollowConstants;
import com.netflix.hollow.core.write.HollowBlobWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class HollowInMemoryBlobStager implements HollowProducer.BlobStager {
private final ProducerOptionalBlobPartConfig optionalPartConfig;
public HollowInMemoryBlobStager() {
this(null);
}
public HollowInMemoryBlobStager(ProducerOptionalBlobPartConfig optionalPartConfig) {
this.optionalPartConfig = optionalPartConfig;
}
@Override
public Blob openSnapshot(long version) {
return new InMemoryBlob(HollowConstants.VERSION_NONE, version, Blob.Type.SNAPSHOT, optionalPartConfig);
}
@Override
public Blob openDelta(long fromVersion, long toVersion) {
return new InMemoryBlob(fromVersion, toVersion, Blob.Type.DELTA, optionalPartConfig);
}
@Override
public Blob openReverseDelta(long fromVersion, long toVersion) {
return new InMemoryBlob(fromVersion, toVersion, Blob.Type.REVERSE_DELTA, optionalPartConfig);
}
@Override
public HollowProducer.HeaderBlob openHeader(long version) {
return new InMemoryHeaderBlob(version);
}
public static class InMemoryHeaderBlob extends HeaderBlob {
private byte[] data;
protected InMemoryHeaderBlob(long version) {
super(version);
}
@Override
public void cleanup() {
}
@Override
public void write(HollowBlobWriter blobWriter) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
blobWriter.writeHeader(baos, null);
data = baos.toByteArray();
}
@Override
public InputStream newInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
}
public static class InMemoryBlob extends Blob {
private byte[] data;
private Map<String, byte[]> optionalParts;
protected InMemoryBlob(long fromVersion, long toVersion, Type type) {
super(fromVersion, toVersion, type);
}
protected InMemoryBlob(long fromVersion, long toVersion, Type type, ProducerOptionalBlobPartConfig optionalPartConfig) {
super(fromVersion, toVersion, type, optionalPartConfig);
}
@Override
public void write(HollowBlobWriter writer) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ProducerOptionalBlobPartConfig.OptionalBlobPartOutputStreams optionalPartStreams = null;
Map<String, ByteArrayOutputStream> optionalPartData = null;
if(optionalPartConfig != null) {
optionalPartStreams = optionalPartConfig.newStreams();
optionalPartData = new HashMap<>();
for(String part : optionalPartConfig.getParts()) {
ByteArrayOutputStream partBaos = new ByteArrayOutputStream();
optionalPartStreams.addOutputStream(part, partBaos);
optionalPartData.put(part, partBaos);
}
}
switch(type) {
case SNAPSHOT:
writer.writeSnapshot(baos, optionalPartStreams);
break;
case DELTA:
writer.writeDelta(baos, optionalPartStreams);
break;
case REVERSE_DELTA:
writer.writeReverseDelta(baos, optionalPartStreams);
break;
}
data = baos.toByteArray();
if(optionalPartConfig != null) {
optionalParts = new HashMap<>();
for(Map.Entry<String, ByteArrayOutputStream> partEntry : optionalPartData.entrySet()) {
optionalParts.put(partEntry.getKey(), partEntry.getValue().toByteArray());
}
}
}
@Override
public InputStream newInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
@Override
public InputStream newOptionalPartInputStream(String partName) throws IOException {
return new ByteArrayInputStream(optionalParts.get(partName));
}
@Override
public Path getOptionalPartPath(String partName) {
throw new UnsupportedOperationException("Path is not available");
}
@Override
public void cleanup() { }
}
}
| 9,243 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/fs/HollowFilesystemBlobStorageCleaner.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.fs;
import com.netflix.hollow.api.producer.HollowProducer;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.logging.Logger;
public class HollowFilesystemBlobStorageCleaner extends HollowProducer.BlobStorageCleaner {
private final Logger log = Logger.getLogger(HollowFilesystemBlobStorageCleaner.class.getName());
private int numOfSnapshotsToKeep;
private final File blobStoreDir;
public HollowFilesystemBlobStorageCleaner(File blobStoreDir) {
this(blobStoreDir,5);
}
public HollowFilesystemBlobStorageCleaner(File blobStoreDir, int numOfSnapshotsToKeep) {
this.blobStoreDir = blobStoreDir;
this.numOfSnapshotsToKeep = numOfSnapshotsToKeep;
}
/**
* Cleans snapshot to keep the last 'n' snapshots. Defaults to 5.
*/
@Override
public void cleanSnapshots() {
File[] files = getFilesByType(HollowProducer.Blob.Type.SNAPSHOT.prefix);
if(files == null || files.length <= numOfSnapshotsToKeep) {
return;
}
sortByLastModified(files);
for(int i= numOfSnapshotsToKeep; i < files.length; i++){
File file = files[i];
boolean deleted = file.delete();
if(!deleted) {
log.warning("Could not delete snapshot " + file.getPath());
}
}
}
@Override
public void cleanDeltas() { }
@Override
public void cleanReverseDeltas() { }
private void sortByLastModified(File[] files) {
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
Long lastModifiedF2 = f2.lastModified();
Long lastModifiedF1 = f1.lastModified();
return lastModifiedF2.compareTo(lastModifiedF1);
}
});
Arrays.sort(files, Collections.reverseOrder());
}
private File[] getFilesByType(final String blobType) {
return blobStoreDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.contains(blobType);
}
});
}
}
| 9,244 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidationStatusListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.listener.AnnouncementListener;
import com.netflix.hollow.api.producer.listener.HollowProducerEventListener;
import java.time.Duration;
/**
* A listener of validation status events associated with the producer validation status stage.
* <p>
* A validation status listener instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withListener(HollowProducerEventListener)}} or by
* registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface ValidationStatusListener extends HollowProducerEventListener {
/**
* A receiver of a validation status start event. Called when validation has started and before
* a {@link ValidatorListener#onValidate(HollowProducer.ReadState) validator} event is emitted to all
* registered {@link ValidatorListener validator} listeners.
*
* @param version the version
*/
void onValidationStatusStart(long version);
/**
* A receiver of a validation status complete event. Called when validation has completed and after a
* {@link ValidatorListener#onValidate(HollowProducer.ReadState) validator} event was emitted to all registered
* {@link ValidatorListener validator} listeners.
* <p>
* The validation {@code status} holds the list validation results accumulated from the calling of all
* registered validator listeners. If validation {@link ValidationStatus#failed() fails} (one or more
* validation results failed) then the cycle stage completes with failure and no
* {@link AnnouncementListener announcement} occurs.
* The status of the cycle complete event will contain a {@code cause} that is an instance of
* {@link ValidationStatusException} holding the validation results reported by the validation {@code status}.
*
* @param status the validation status
* @param version the version
* @param elapsed the time elapsed between this event and {@link #onValidationStatusStart}
*/
void onValidationStatusComplete(ValidationStatus status, long version, Duration elapsed);
}
| 9,245 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/DuplicateDataDetectionValidator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.HollowProducer.ReadState;
import com.netflix.hollow.core.index.HollowPrimaryKeyIndex;
import com.netflix.hollow.core.index.key.PrimaryKey;
import com.netflix.hollow.core.read.engine.HollowReadStateEngine;
import com.netflix.hollow.core.read.engine.HollowTypeReadState;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSchema.SchemaType;
import com.netflix.hollow.core.write.HollowTypeWriteState;
import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey;
import com.netflix.hollow.core.write.objectmapper.HollowTypeMapper;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* A validator that fails if two or more records of the same type are present and they have the same primary key.
* <p>
* The primary key may be declared on a data model class using the {@link HollowPrimaryKey} annotation, may be
* declared more directly using {@link PrimaryKey} with {@link HollowObjectSchema}, or declared explicitly when
* instantiating this validator.
*
* @apiNote If all a record's fields are associated with a primary key (in other words, the record has no
* fields that are not associated the primary key) then any duplicates added during the population
* stage will be naturally de-duped resulting in just one record present. Therefore a validator created for such a
* record's type will never fail.
*/
public class DuplicateDataDetectionValidator implements ValidatorListener {
private static final String DUPLICATE_KEYS_FOUND_ERRRO_MSG_FORMAT =
"Duplicate keys found for type %s. Primarykey in schema is %s. "
+ "Duplicate IDs are: %s";
private static final String NO_PRIMARY_KEY_ERROR_MSG_FORMAT =
"DuplicateDataDetectionValidator defined but unable to find primary key "
+ "for data type %s. Please check schema definition.";
private static final String NO_SCHEMA_FOUND_MSG_FORMAT =
"DuplicateDataDetectionValidator defined for data type %s but schema not found."
+ "Please check that the HollowProducer is initialized with the data type's schema "
+ "(see initializeDataModel)";
private static final String NOT_AN_OBJECT_ERROR_MSG_FORMAT =
"DuplicateDataDetectionValidator is defined but schema type of %s "
+ "is not Object. This validation cannot be done.";
private static final String FIELD_PATH_NAME = "FieldPaths";
private static final String DATA_TYPE_NAME = "Typename";
private static final String NAME = DuplicateDataDetectionValidator.class.getName();
private final String dataTypeName;
private final String[] fieldPathNames;
/**
* Creates a validator to detect duplicate records of the type that corresponds to the given data type class
* annotated with {@link HollowPrimaryKey}.
*
* @param dataType the data type class
* @throws IllegalArgumentException if the data type class is not annotated with {@link HollowPrimaryKey}
*/
public DuplicateDataDetectionValidator(Class<?> dataType) {
Objects.requireNonNull(dataType);
if (!dataType.isAnnotationPresent(HollowPrimaryKey.class)) {
throw new IllegalArgumentException("The data class " +
dataType.getName() +
" must be annotated with @HollowPrimaryKey");
}
this.dataTypeName = HollowTypeMapper.getDefaultTypeName(dataType);
this.fieldPathNames = null;
}
/**
* Creates a validator to detect duplicate records of the type that corresponds to the given data type name.
* <p>
* The validator will fail, when {@link #onValidate validating}, if a schema with a primary key definition does not
* exist for the given data type name.
*
* @param dataTypeName the data type name
*/
public DuplicateDataDetectionValidator(String dataTypeName) {
this.dataTypeName = Objects.requireNonNull(dataTypeName);
this.fieldPathNames = null;
}
/**
* Creates a validator to detect duplicate records of the type that corresponds to the given data type name
* with a primary key composed from the given field paths.
* <p>
* The validator will fail, when {@link #onValidate validating}, if a schema does not exist for the given data
* type name or any field path is incorrectly specified.
*
* @param dataTypeName the data type name
* @param fieldPathNames the field paths defining the primary key
*/
public DuplicateDataDetectionValidator(String dataTypeName, String[] fieldPathNames) {
this.dataTypeName = Objects.requireNonNull(dataTypeName);
this.fieldPathNames = fieldPathNames.clone();
}
@Override
public String getName() {
return NAME + "_" + dataTypeName;
}
@Override
public ValidationResult onValidate(ReadState readState) {
ValidationResult.ValidationResultBuilder vrb = ValidationResult.from(this);
vrb.detail(DATA_TYPE_NAME, dataTypeName);
PrimaryKey primaryKey;
if (fieldPathNames == null) {
HollowSchema schema = readState.getStateEngine().getSchema(dataTypeName);
if (schema == null) {
return vrb.failed(String.format(NO_SCHEMA_FOUND_MSG_FORMAT, dataTypeName));
}
if (schema.getSchemaType() != SchemaType.OBJECT) {
return vrb.failed(String.format(NOT_AN_OBJECT_ERROR_MSG_FORMAT, dataTypeName));
}
HollowObjectSchema oSchema = (HollowObjectSchema) schema;
primaryKey = oSchema.getPrimaryKey();
if (primaryKey == null) {
return vrb.failed(String.format(NO_PRIMARY_KEY_ERROR_MSG_FORMAT, dataTypeName));
}
} else {
primaryKey = new PrimaryKey(dataTypeName, fieldPathNames);
}
String fieldPaths = Arrays.toString(primaryKey.getFieldPaths());
vrb.detail(FIELD_PATH_NAME, fieldPaths);
Collection<Object[]> duplicateKeys = getDuplicateKeys(readState.getStateEngine(), primaryKey);
if (!duplicateKeys.isEmpty()) {
String message = String.format(DUPLICATE_KEYS_FOUND_ERRRO_MSG_FORMAT, dataTypeName, fieldPaths,
duplicateKeysToString(duplicateKeys));
return vrb.failed(message);
}
return vrb.passed();
}
private Collection<Object[]> getDuplicateKeys(HollowReadStateEngine stateEngine, PrimaryKey primaryKey) {
HollowTypeReadState typeState = stateEngine.getTypeState(dataTypeName);
HollowPrimaryKeyIndex hollowPrimaryKeyIndex = typeState.getListener(HollowPrimaryKeyIndex.class);
if (hollowPrimaryKeyIndex == null) {
hollowPrimaryKeyIndex = new HollowPrimaryKeyIndex(stateEngine, primaryKey);
}
return hollowPrimaryKeyIndex.getDuplicateKeys();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DuplicateDataDetectionValidator that = (DuplicateDataDetectionValidator) o;
return dataTypeName.equals(that.dataTypeName) &&
Arrays.equals(fieldPathNames, that.fieldPathNames);
}
@Override
public int hashCode() {
int result = Objects.hash(dataTypeName);
result = 31 * result + Arrays.hashCode(fieldPathNames);
return result;
}
private String duplicateKeysToString(Collection<Object[]> duplicateKeys) {
return duplicateKeys.stream().map(Arrays::toString).collect(Collectors.joining(","));
}
/**
* Registers {@code DuplicateDataDetectionValidator} validators with the given {@link HollowProducer producer} for
* all object schema declared with a primary key.
* <p>
* This requires that the producer's data model has been initialized
* (see {@link HollowProducer#initializeDataModel(Class[])} or a prior run cycle has implicitly initialized
* the data model.
* <p>
* For each {@link HollowTypeWriteState write state} that has a {@link HollowObjectSchema object schema}
* declared with a {@link PrimaryKey primary key} a {@code DuplicateDataDetectionValidator} validator
* is instantiated, with the primary key type name, and registered with the given producer (if a
* {@code DuplicateDataDetectionValidator} validator is not already registered for the same primary key type name).
*
* @param producer the producer
* @apiNote This method registers a {@code DuplicateDataDetectionValidator} validator with only the primary key type
* name and not, in addition, the primary key fields. This is to ensure, for the common case, duplicate listeners
* are not registered by this method if listeners with the same type names were explicitly registered when
* building the producer.
* @see HollowProducer#initializeDataModel(Class[])
*/
public static void addValidatorsForSchemaWithPrimaryKey(HollowProducer producer) {
producer.getWriteEngine().getOrderedTypeStates().stream()
.filter(ts -> ts.getSchema().getSchemaType() == SchemaType.OBJECT)
.map(ts -> (HollowObjectSchema) ts.getSchema())
.filter(hos -> hos.getPrimaryKey() != null)
.map(HollowObjectSchema::getPrimaryKey)
.forEach(k -> producer.addListener(new DuplicateDataDetectionValidator(k.getType())));
}
}
| 9,246 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidationResult.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/**
* The result of validation performed by a {@link ValidatorListener validator}.
*/
public final class ValidationResult {
private final ValidationResultType type;
private final String name;
private final Throwable ex; // set for status == ERROR or FAILED
private final String message;
private final Map<String, String> details;
ValidationResult(
ValidationResultType type,
String name,
Throwable ex,
String message,
Map<String, String> details) {
if (type == ValidationResultType.ERROR && ex == null) {
throw new IllegalArgumentException();
}
// @@@ For the moment allow a throwable to be associated with FAILED state
// This is for compatibility with HollowProducer.Validator.ValidationException
if (type == ValidationResultType.PASSED && ex != null) {
throw new IllegalArgumentException();
}
assert name != null; // builder checks
this.name = name;
this.type = type;
assert type != null; // builder ensures
this.ex = ex;
this.message = message;
this.details = Collections.unmodifiableMap(details);
}
/**
* Returns the validation result type.
*
* @return the validation result type
*/
public ValidationResultType getResultType() {
return type;
}
/**
* Returns the name of the validation performed.
*
* @return the name of the validation performed
*/
public String getName() {
return name;
}
/**
* Returns the {@code Throwable} associated with a validator that
* failed with an unexpected {@link ValidationResultType#ERROR error}.
*
* @return the {@code Throwable} associated with an erroneous validator, otherwise
* {@code null}
*/
public Throwable getThrowable() {
return ex;
}
/**
* Returns a message associated with the validation.
*
* @return a message associated with the validation. may be {@code null}
*/
public String getMessage() {
return message;
}
/**
* Returns details associated with the validation.
*
* @return details associated with the validation. The details are unmodifiable and may be empty.
*/
public Map<String, String> getDetails() {
return details;
}
/**
* Returns true if validation passed, otherwise {@code false}.
*
* @return true if validation passed, otherwise {@code false}
*/
public boolean isPassed() {
return type == ValidationResultType.PASSED;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ValidationResult[")
.append("name=\"").append(name).append("\" ")
.append("result=").append(type).append(" ");
if (message == null) {
sb.append("message=null ");
} else {
sb.append("message=\"").append(message).append("\" ");
}
sb.append("details=").append(details).append(" ")
.append("throwable=").append(ex).append(" ")
.append("]");
return sb.toString();
}
/**
* Initiates the building of a result from a validation listener.
* The {@link ValidationResult#getName name} of the validation result with be
* set to the {@link ValidatorListener#getName name} of the validator
*
* @param v the validation listener
* @return the validation builder
* @throws NullPointerException if {@code v} is {@code null}
*/
public static ValidationResultBuilder from(ValidatorListener v) {
return from(v.getName());
}
/**
* Initiates the building of a result from a name.
*
* @param name the validation result
* @return the validation builder
* @throws NullPointerException if {@code name} is {@code null}
*/
public static ValidationResultBuilder from(String name) {
return new ValidationResultBuilder(name);
}
/**
* A builder of a {@link ValidationResult}.
* <p>
* The builder may be reused after it has built a validation result, but the details will be reset
* to contain no entries.
*/
static public class ValidationResultBuilder {
private final String name;
private Map<String, String> details;
ValidationResultBuilder(String name) {
this.name = Objects.requireNonNull(name);
this.details = new LinkedHashMap<>();
}
/**
* Sets a detail.
*
* @param name the detail name
* @param value the detail value, which will be converted to a {@code String}
* using {@link String#valueOf(Object)}
* @return the validation builder
* @throws NullPointerException if {@code name} or {@code value} are {@code null}
*/
public ValidationResultBuilder detail(String name, Object value) {
Objects.requireNonNull(name);
Objects.requireNonNull(value);
details.put(name, String.valueOf(value));
return this;
}
/**
* Builds a result that has {@link ValidationResultType#PASSED passed} with no message.
*
* @return a validation result that has passed.
*/
public ValidationResult passed() {
return new ValidationResult(
ValidationResultType.PASSED,
name,
null,
null,
details
);
}
/**
* Builds a result that has {@link ValidationResultType#PASSED passed} with a message.
*
* @param message the message, may be {@code null}
* @return a validation result that has passed.
*/
public ValidationResult passed(String message) {
return build(
ValidationResultType.PASSED,
name,
null,
message,
details
);
}
/**
* Builds a result that has {@link ValidationResultType#FAILED failed} with a message.
*
* @param message the message
* @return a validation result that has failed.
* @throws NullPointerException if {@code message} is {@code null}
*/
public ValidationResult failed(String message) {
return build(
ValidationResultType.FAILED,
name,
null,
message,
details
);
}
/**
* Builds a result for a validator that produced an unexpected {@link ValidationResultType#ERROR error}
* with a {@code Throwable}.
*
* @param t the {@code Throwable}
* @return a validation result for a validator that produced an unexpected error
* @throws NullPointerException if {@code t} is {@code null}
*/
// @@@ This could be made package private as it is questionable if validators should use this,
// however for testing purposes of status listeners it's useful.
public ValidationResult error(Throwable t) {
return build(
ValidationResultType.ERROR,
name,
t,
t.getMessage(),
details
);
}
private ValidationResult build(
ValidationResultType type,
String name,
Throwable ex,
String message,
Map<String, String> details) {
reset();
return new ValidationResult(type, name, ex, message, details);
}
private void reset() {
this.details = new LinkedHashMap<>();
}
}
}
| 9,247 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidationResultType.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
/**
* The type of validation result.
*/
public enum ValidationResultType {
/**
* The validation passed.
*/
// @@@ Skipping might be considered a sub-state of PASSED with details in ValidationResult
PASSED,
/**
* The validation failed.
*/
FAILED,
/**
* The validator failed with an unexpected error and could not perform the validation
*/
ERROR
}
| 9,248 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidatorListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import com.netflix.hollow.api.producer.HollowProducer;
import com.netflix.hollow.api.producer.listener.HollowProducerEventListener;
/**
* A validator of {@link com.netflix.hollow.api.producer.HollowProducer.ReadState read state}. This type is a
* listener of a validator event associated with the producer validator stage.
* <p>
* A validator instance may be registered when building a {@link HollowProducer producer}
* (see {@link HollowProducer.Builder#withValidator(ValidatorListener)}} or by registering on the producer itself
* (see {@link HollowProducer#addListener(HollowProducerEventListener)}.
*/
public interface ValidatorListener extends HollowProducerEventListener {
/**
* Gets the name of the validator.
*
* @return the name
*/
String getName();
/**
* A receiver of a validation event. Called when validation is to be performed on read state.
* <p>
* If a {@code RuntimeException} is thrown by the validator then validation has failed with an unexpected error.
* A {@link ValidationResult result} will be built from this validator as if by a call to
* {@link ValidationResult.ValidationResultBuilder#error(Throwable)} with the {@code RuntimeException} as the
* argument. The validator is considered to have returned that result.
*
* @param readState the read state.
* @return the validation result
*/
ValidationResult onValidate(HollowProducer.ReadState readState);
}
| 9,249 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ObjectModificationValidator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import com.netflix.hollow.api.custom.HollowAPI;
import com.netflix.hollow.api.objects.HollowObject;
import com.netflix.hollow.api.producer.HollowProducer.ReadState;
import com.netflix.hollow.core.HollowConstants;
import com.netflix.hollow.core.index.HollowPrimaryKeyIndex;
import com.netflix.hollow.core.index.key.PrimaryKey;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.engine.HollowTypeReadState;
import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState;
import com.netflix.hollow.core.schema.HollowSchema.SchemaType;
import java.util.Arrays;
import java.util.BitSet;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
/**
* This validator runs a provided {@link BiPredicate} on every instance of an object that was
* modified in a cycle. This "filter" function is called with the old object as the first argument
* and the new object as the second argument. If the function returns false, this validator is
* marked as failed and the producer cycle fails.
* Note that the filter function is not called with any objects that were added or removed.
* Also note that this validator can only be used on types that have a primary key.
*
* @apiNote Example construction - note that {@code Movie} and {@code MovieAPI} are generated classes:
* <pre>{@code
* new ObjectModificationValidator<MovieAPI, Movie>(
* "Movie",
* (oldMovie, newMovie) -> oldMovie.getName().equals(newMovie.getName()),
* MovieAPI::new,
* (api, ordinal) -> api.getMovie(ordinal));
* }</pre>
*/
public class ObjectModificationValidator<A extends HollowAPI, T extends HollowObject>
implements ValidatorListener {
private final String typeName;
private final Function<HollowDataAccess, A> apiFunction;
private final BiFunction<A, Integer, T> hollowObjectFunction;
private final BiPredicate<T, T> filter;
@SuppressWarnings("WeakerAccess")
public ObjectModificationValidator(
String typeName, BiPredicate<T, T> filter,
Function<HollowDataAccess, A> apiFunction,
BiFunction<A, Integer, T> hollowObjectFunction) {
this.typeName = typeName;
this.filter = filter;
this.apiFunction = apiFunction;
this.hollowObjectFunction = hollowObjectFunction;
}
@Override
public String getName() {
return getClass().getSimpleName() + "_" + typeName;
}
@Override
public ValidationResult onValidate(ReadState readState) {
ValidationResult.ValidationResultBuilder vrb = ValidationResult.from(this)
.detail("Typename", typeName);
HollowTypeReadState typeState = readState.getStateEngine().getTypeState(typeName);
if (typeState == null) {
return vrb.failed("Cannot execute ObjectModificationValidator on missing type " + typeName);
} else if (typeState.getSchema().getSchemaType() != SchemaType.OBJECT) {
return vrb.failed("Cannot execute ObjectModificationValidator on type " + typeName
+ " because it is not a HollowObjectSchema - it is a "
+ typeState.getSchema().getSchemaType());
}
BitSet latestOrdinals = typeState.getPopulatedOrdinals();
BitSet previousOrdinals = typeState.getPreviousOrdinals();
if (previousOrdinals.isEmpty()) {
return vrb.detail("skipped", Boolean.TRUE)
.passed("Nothing to do because previous cycle has no " + typeName);
}
BitSet removedAndModified = calculateRemovedAndModifiedOrdinals(latestOrdinals, previousOrdinals);
if (removedAndModified.isEmpty()) {
return vrb.detail("skipped", Boolean.TRUE)
.passed("Nothing to do because " + typeName + " has no removals or modifications");
}
A hollowApi = apiFunction.apply(readState.getStateEngine());
HollowObjectTypeReadState objectTypeState = (HollowObjectTypeReadState) typeState;
PrimaryKey key = objectTypeState.getSchema().getPrimaryKey();
// this is guaranteed to give us items from the most recent cycle, not the last one
HollowPrimaryKeyIndex index = new HollowPrimaryKeyIndex(readState.getStateEngine(), key);
int fromOrdinal = removedAndModified.nextSetBit(0);
while (fromOrdinal != HollowConstants.ORDINAL_NONE) {
Object[] candidateKey = index.getRecordKey(fromOrdinal);
int matchedOrdinal = index.getMatchingOrdinal(candidateKey);
if (matchedOrdinal != HollowConstants.ORDINAL_NONE) {
T fromObject = hollowObjectFunction.apply(hollowApi, fromOrdinal);
T toObject = hollowObjectFunction.apply(hollowApi, matchedOrdinal);
if (!filter.test(fromObject, toObject)) {
return vrb.detail("candidateKey", Arrays.toString(candidateKey))
.detail("fromOrdinal", fromOrdinal)
.detail("toOrdinal", matchedOrdinal)
.failed("Validation failed for candidate key");
}
}
fromOrdinal = removedAndModified.nextSetBit(fromOrdinal + 1);
}
return vrb.passed();
}
private static BitSet calculateRemovedAndModifiedOrdinals(BitSet latestOrdinals, BitSet previousOrdinals) {
// make sure we don't modify previousOrdinals or latestOrdinals
BitSet removedAndModified = new BitSet();
removedAndModified.or(previousOrdinals);
removedAndModified.andNot(latestOrdinals);
return removedAndModified;
}
}
| 9,250 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/RecordCountVarianceValidator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import com.netflix.hollow.api.producer.HollowProducer.ReadState;
import com.netflix.hollow.core.read.engine.HollowTypeReadState;
/**
* Used to validate if the cardinality change in current cycle is with in the allowed percent for a given typeName.
* Ex: 0% allowableVariancePercent ensures type cardinality does not vary at all for cycle to cycle.
* Ex: Number of state in United States.
* 10% allowableVariancePercent: from previous cycle any addition or removal within 10% cardinality is valid.
* Anything more results in failure of validation.
*
* @author lkanchanapalli {@literal<lavanya65@yahoo.com>}
*/
public class RecordCountVarianceValidator implements ValidatorListener {
private static final String ZERO_PREVIOUS_COUNT_WARN_MSG_FORMAT =
"Previous record count is 0. Not running RecordCountVarianceValidator for type %s. "
+ "This scenario is not expected except when starting a new namespace.";
private static final String FAILED_RECORD_COUNT_VALIDATION =
"Record count validation for type %s has failed as actual change percent %s "
+ "is greater than allowed change percent %s.";
private static final String DATA_TYPE_NAME = "Typename";
private static final String ALLOWABLE_VARIANCE_PERCENT_NAME = "AllowableVariancePercent";
private static final String LATEST_CARDINALITY_NAME = "LatestRecordCount";
private static final String PREVIOUS_CARDINALITY_NAME = "PreviousRecordCount";
private static final String ACTUAL_CHANGE_PERCENT_NAME = "ActualChangePercent";
private static final String NAME = RecordCountVarianceValidator.class.getName();
private final String typeName;
private final float allowableVariancePercent;
/**
* @param typeName type name
* @param allowableVariancePercent: Used to validate if the cardinality change in current cycle is with in the
* allowed percent.
* Ex: 0% allowableVariancePercent ensures type cardinality does not vary at all for cycle to cycle.
* Ex: Number of state in United States.
* 10% allowableVariancePercent: from previous cycle any addition or removal within 10% cardinality is valid.
* Anything more results in failure of validation.
*/
public RecordCountVarianceValidator(String typeName, float allowableVariancePercent) {
this.typeName = typeName;
if (allowableVariancePercent < 0) {
throw new IllegalArgumentException("RecordCountVarianceValidator for type " + typeName
+ ": cannot have allowableVariancePercent less than 0. Value provided: "
+ allowableVariancePercent);
}
this.allowableVariancePercent = allowableVariancePercent;
}
@Override
public String getName() {
return NAME + "_" + typeName;
}
@Override
public ValidationResult onValidate(ReadState readState) {
ValidationResult.ValidationResultBuilder vrb = ValidationResult.from(this);
vrb.detail(ALLOWABLE_VARIANCE_PERCENT_NAME, allowableVariancePercent)
.detail(DATA_TYPE_NAME, typeName);
HollowTypeReadState typeState = readState.getStateEngine().getTypeState(typeName);
int latestCardinality = typeState.getPopulatedOrdinals().cardinality();
int previousCardinality = typeState.getPreviousOrdinals().cardinality();
vrb.detail(LATEST_CARDINALITY_NAME, latestCardinality)
.detail(PREVIOUS_CARDINALITY_NAME, previousCardinality);
if (previousCardinality == 0) {
return vrb.detail("skipped", Boolean.TRUE).
passed(String.format(ZERO_PREVIOUS_COUNT_WARN_MSG_FORMAT, typeName));
}
float actualChangePercent = getChangePercent(latestCardinality, previousCardinality);
vrb.detail(ACTUAL_CHANGE_PERCENT_NAME, actualChangePercent);
if (Float.compare(actualChangePercent, allowableVariancePercent) > 0) {
String message = String.format(FAILED_RECORD_COUNT_VALIDATION, typeName, actualChangePercent,
allowableVariancePercent);
return vrb.failed(message);
}
return vrb.passed();
}
// protected for tests
float getChangePercent(int latestCardinality, int previousCardinality) {
int diff = Math.abs(latestCardinality - previousCardinality);
return (100.0f * diff) / previousCardinality;
}
}
| 9,251 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidationStatus.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The overall status of a sequence of validation results.
* <p>
* A status accumulated from the results of validators will be passed to registered
* {@link ValidationStatusListener validation status} listeners after validation status has completed.
*/
public final class ValidationStatus {
private final List<ValidationResult> results;
private final boolean passed;
/**
* Creates a new validation status from a list of validation results.
*
* @param results the validation results
* @throws NullPointerException if {@code results} is {@code null}
*/
public ValidationStatus(List<ValidationResult> results) {
this.results = Collections.unmodifiableList(new ArrayList<>(results));
this.passed = this.results.stream().allMatch(ValidationResult::isPassed);
}
/**
* Returns true if all validation results have passed, otherwise false if one or more results
* failed or a validator was erroneous.
*
* @return true if all validation results have passed, otherwise false
*/
public boolean passed() {
return passed;
}
/**
* Returns true if one or more validation results failed or was erroneous, otherwise false if all results
* passed.
*
* @return true if one or more validation results failed or was erroneous, otherwise false
*/
public boolean failed() {
return !passed;
}
/**
* Returns the validation results.
*
* @return the validation results. The results are unmodifiable.
*/
public List<ValidationResult> getResults() {
return results;
}
}
| 9,252 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/producer/validation/ValidationStatusException.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.producer.validation;
import java.util.Objects;
/**
* A validation status exception holding a validation status.
*/
public final class ValidationStatusException extends RuntimeException {
private final ValidationStatus status;
/**
* Creates a validation status exception.
*
* @param status the status
* @param message the message
* @throws IllegalArgumentException if {@code status} contains results that all passed
* @throws NullPointerException if {@code status} is {@code null}
*/
public ValidationStatusException(ValidationStatus status, String message) {
super(message);
if (status.passed()) {
throw new IllegalArgumentException("A validation status exception was created "
+ "with a status containing results that all passed");
}
this.status = Objects.requireNonNull(status);
}
/**
* Returns the validation status.
*
* @return the validation status.
*/
public ValidationStatus getValidationStatus() {
return status;
}
}
| 9,253 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/SampleResult.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
public class SampleResult implements Comparable<SampleResult> {
private final String identifier;
private final long numSamples;
public SampleResult(String identifier, long numSamples) {
this.identifier = identifier;
this.numSamples = numSamples;
}
public String getIdentifier() {
return identifier;
}
public long getNumSamples() {
return numSamples;
}
@Override
public int compareTo(SampleResult o) {
if(o.numSamples == numSamples)
return identifier.compareTo(o.identifier);
return Long.compare(o.numSamples, numSamples);
}
@Override
public String toString() {
return identifier + ": " + numSamples;
}
}
| 9,254 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/TimeSliceSamplingDirector.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import static com.netflix.hollow.core.util.Threads.daemonThread;
import java.util.ArrayList;
import java.util.List;
public class TimeSliceSamplingDirector extends HollowSamplingDirector {
private final List<SamplingStatusListener> listeners = new ArrayList<SamplingStatusListener>();
private int msOff;
private int msOn;
private boolean isInPlay = false;
private boolean record = false;
public TimeSliceSamplingDirector() {
this(1000, 1);
}
public TimeSliceSamplingDirector(int msOff, int msOn) {
this.msOff = msOff;
this.msOn = msOn;
}
@Override
public boolean shouldRecord() {
return record && !isUpdateThread();
}
public void startSampling() {
if(!isInPlay) {
isInPlay = true;
daemonThread(new SampleToggler(), getClass(), "toggler")
.start();
}
}
public void setTiming(int msOff, int msOn) {
this.msOff = msOff;
this.msOn = msOn;
}
public void stopSampling() {
isInPlay = false;
}
private class SampleToggler implements Runnable {
@Override
public void run() {
while(isInPlay) {
record = false;
notifyListeners();
sleep(msOff);
record = isInPlay;
notifyListeners();
sleep(msOn);
}
record = false;
notifyListeners();
}
private void sleep(int ms) {
try {
Thread.sleep(ms);
} catch(InterruptedException ignore) { }
}
}
private void notifyListeners() {
for(int i=0;i<listeners.size();i++) {
listeners.get(i).samplingStatusChanged(record);
}
}
public void addSamplingStatusListener(SamplingStatusListener listener) {
listener.samplingStatusChanged(record);
listeners.add(listener);
}
}
| 9,255 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowMapSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class HollowMapSampler implements HollowSampler {
public static final HollowMapSampler NULL_SAMPLER = new HollowMapSampler("", DisabledSamplingDirector.INSTANCE);
private final String typeName;
private HollowSamplingDirector director;
private long sizeSamples;
private long getSamples;
private long bucketRetrievalSamples;
private long iteratorSamples;
public HollowMapSampler(String typeName, HollowSamplingDirector director) {
this.typeName = typeName;
this.director = director;
}
public void setSamplingDirector(HollowSamplingDirector director) {
if(!"".equals(typeName))
this.director = director;
}
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director) {
if(!"".equals(typeName) && fieldSpec.doesIncludeType(typeName))
this.director = director;
}
@Override
public void setUpdateThread(Thread t) {
director.setUpdateThread(t);
}
public void recordSize() {
if(director.shouldRecord())
sizeSamples++;
}
public void recordBucketRetrieval() {
if(director.shouldRecord())
bucketRetrievalSamples++;
}
public void recordGet() {
if(director.shouldRecord())
getSamples++;
}
public void recordIterator() {
if(director.shouldRecord())
iteratorSamples++;
}
@Override
public boolean hasSampleResults() {
return sizeSamples > 0 || getSamples > 0 || iteratorSamples > 0 || bucketRetrievalSamples > 0;
}
@Override
public Collection<SampleResult> getSampleResults() {
List<SampleResult> sampleResults = new ArrayList<SampleResult>(4);
sampleResults.add(new SampleResult(typeName + ".size()", sizeSamples));
sampleResults.add(new SampleResult(typeName + ".get()", getSamples));
sampleResults.add(new SampleResult(typeName + ".iterator()", iteratorSamples));
sampleResults.add(new SampleResult(typeName + ".bucketValue()", bucketRetrievalSamples));
return sampleResults;
}
@Override
public void reset() {
sizeSamples = 0;
getSamples = 0;
iteratorSamples = 0;
bucketRetrievalSamples = 0;
}
}
| 9,256 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowObjectCreationSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class HollowObjectCreationSampler implements HollowSampler {
private final String typeNames[];
private final long creationSamples[];
private final HollowSamplingDirector typeDirectors[];
public HollowObjectCreationSampler(String... typeNames) {
this.typeNames = typeNames;
this.creationSamples = new long[typeNames.length];
HollowSamplingDirector[] typeDirectors = new HollowSamplingDirector[typeNames.length];
Arrays.fill(typeDirectors, DisabledSamplingDirector.INSTANCE);
this.typeDirectors = typeDirectors;
}
public void recordCreation(int index) {
if(typeDirectors[index].shouldRecord())
creationSamples[index]++;
}
@Override
public void setSamplingDirector(HollowSamplingDirector director) {
Arrays.fill(typeDirectors, director);
}
@Override
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director) {
for(int i=0;i<typeNames.length;i++) {
if(fieldSpec.doesIncludeType(typeNames[i]))
typeDirectors[i] = director;
}
}
@Override
public void setUpdateThread(Thread t) {
for(int i=0;i<typeDirectors.length;i++)
typeDirectors[i].setUpdateThread(t);
}
@Override
public boolean hasSampleResults() {
for(int i=0;i<creationSamples.length;i++)
if(creationSamples[i] > 0)
return true;
return false;
}
@Override
public Collection<SampleResult> getSampleResults() {
List<SampleResult> results = new ArrayList<SampleResult>(typeNames.length);
for(int i=0;i<typeNames.length;i++) {
results.add(new SampleResult(typeNames[i], creationSamples[i]));
}
Collections.sort(results);
return results;
}
@Override
public void reset() {
Arrays.fill(creationSamples, 0L);
}
}
| 9,257 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowSetSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class HollowSetSampler implements HollowSampler {
public static final HollowSetSampler NULL_SAMPLER = new HollowSetSampler("", DisabledSamplingDirector.INSTANCE);
private final String typeName;
private HollowSamplingDirector director;
private long sizeSamples;
private long getSamples;
private long iteratorSamples;
public HollowSetSampler(String typeName, HollowSamplingDirector director) {
this.typeName = typeName;
this.director = director;
}
public void setSamplingDirector(HollowSamplingDirector director) {
if(!"".equals(typeName))
this.director = director;
}
@Override
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director) {
if(!"".equals(typeName) && fieldSpec.doesIncludeType(typeName))
this.director = director;
}
@Override
public void setUpdateThread(Thread t) {
director.setUpdateThread(t);
}
public void recordGet() {
if(director.shouldRecord())
getSamples++;
}
public void recordSize() {
if(director.shouldRecord())
sizeSamples++;
}
public void recordIterator() {
if(director.shouldRecord())
iteratorSamples++;
}
@Override
public boolean hasSampleResults() {
return sizeSamples > 0 || getSamples > 0 || iteratorSamples > 0;
}
@Override
public Collection<SampleResult> getSampleResults() {
List<SampleResult> results = new ArrayList<SampleResult>(3);
results.add(new SampleResult(typeName + ".size()", sizeSamples));
results.add(new SampleResult(typeName + ".get()", getSamples));
results.add(new SampleResult(typeName + ".iterator()", iteratorSamples));
return results;
}
@Override
public void reset() {
sizeSamples = 0;
getSamples = 0;
iteratorSamples = 0;
}
}
| 9,258 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowObjectSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import com.netflix.hollow.core.read.filter.HollowFilterConfig.ObjectFilterConfig;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class HollowObjectSampler implements HollowSampler {
public static final HollowObjectSampler NULL_SAMPLER = new HollowObjectSampler(
new HollowObjectSchema("test", 0), DisabledSamplingDirector.INSTANCE);
private final String typeName;
private final String fieldNames[];
private final long sampleCounts[];
private final HollowSamplingDirector samplingDirectors[];
private boolean isSamplingDisabled;
public HollowObjectSampler(HollowObjectSchema schema, HollowSamplingDirector director) {
this.typeName = schema.getName();
this.sampleCounts = new long[schema.numFields()];
this.isSamplingDisabled = director == DisabledSamplingDirector.INSTANCE;
HollowSamplingDirector[] samplingDirectors = new HollowSamplingDirector[schema.numFields()];
Arrays.fill(samplingDirectors, director);
String fieldNames[] = new String[schema.numFields()];
for(int i=0;i<fieldNames.length;i++) {
fieldNames[i] = schema.getFieldName(i);
}
this.fieldNames = fieldNames;
this.samplingDirectors = samplingDirectors;
}
public void setSamplingDirector(HollowSamplingDirector director) {
if(!"".equals(typeName)) {
this.isSamplingDisabled = director == DisabledSamplingDirector.INSTANCE;
Arrays.fill(samplingDirectors, director);
}
}
@Override
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director) {
ObjectFilterConfig typeConfig = fieldSpec.getObjectTypeConfig(typeName);
for(int i=0;i<fieldNames.length;i++) {
if(typeConfig.includesField(fieldNames[i])) {
this.isSamplingDisabled = false;
samplingDirectors[i] = director;
}
}
}
public void setUpdateThread(Thread t) {
for(int i=0;i<samplingDirectors.length;i++)
samplingDirectors[i].setUpdateThread(t);
}
public void recordFieldAccess(int fieldPosition) {
if (this.isSamplingDisabled) return;
if(samplingDirectors[fieldPosition].shouldRecord())
sampleCounts[fieldPosition]++;
}
public boolean hasSampleResults() {
for(int i=0;i<sampleCounts.length;i++)
if(sampleCounts[i] > 0)
return true;
return false;
}
@Override
public Collection<SampleResult> getSampleResults() {
List<SampleResult> sampleResults = new ArrayList<SampleResult>(sampleCounts.length);
for(int i=0;i<sampleCounts.length;i++) {
sampleResults.add(new SampleResult(typeName + "." + fieldNames[i], sampleCounts[i]));
}
return sampleResults;
}
@Override
public void reset() {
Arrays.fill(sampleCounts, 0L);
}
}
| 9,259 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/EnabledSamplingDirector.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
public class EnabledSamplingDirector extends HollowSamplingDirector {
public EnabledSamplingDirector() { }
@Override
public boolean shouldRecord() {
return !isUpdateThread();
}
}
| 9,260 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowSamplingDirector.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
public abstract class HollowSamplingDirector {
private Thread updateThread;
public abstract boolean shouldRecord();
public void setUpdateThread(Thread t) {
this.updateThread = t;
}
protected boolean isUpdateThread() {
return updateThread != null && updateThread == Thread.currentThread();
}
}
| 9,261 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowListSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class HollowListSampler implements HollowSampler {
public static final HollowListSampler NULL_SAMPLER = new HollowListSampler("", DisabledSamplingDirector.INSTANCE);
private final String typeName;
private HollowSamplingDirector director;
private long sizeSamples;
private long getSamples;
private long iteratorSamples;
public HollowListSampler(String typeName, HollowSamplingDirector director) {
this.typeName = typeName;
this.director = director;
}
public void setSamplingDirector(HollowSamplingDirector director) {
if(!"".equals(typeName))
this.director = director;
}
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director) {
if(!"".equals(typeName) && fieldSpec.doesIncludeType(typeName))
this.director = director;
}
@Override
public void setUpdateThread(Thread t) {
director.setUpdateThread(t);
}
public void recordSize() {
if(director.shouldRecord())
sizeSamples++;
}
public void recordGet() {
if(director.shouldRecord())
getSamples++;
}
public void recordIterator() {
if(director.shouldRecord())
iteratorSamples++;
}
public boolean hasSampleResults() {
return sizeSamples > 0 || getSamples > 0 || iteratorSamples > 0;
}
@Override
public Collection<SampleResult> getSampleResults() {
List<SampleResult> results = new ArrayList<SampleResult>();
results.add(new SampleResult(typeName + ".size()", sizeSamples));
results.add(new SampleResult(typeName + ".get()", getSamples));
results.add(new SampleResult(typeName + ".iterator()", iteratorSamples));
return results;
}
@Override
public void reset() {
sizeSamples = 0;
getSamples = 0;
iteratorSamples = 0;
}
}
| 9,262 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/DisabledSamplingDirector.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
public class DisabledSamplingDirector extends HollowSamplingDirector {
public static final DisabledSamplingDirector INSTANCE = new DisabledSamplingDirector();
private DisabledSamplingDirector() { }
@Override
public boolean shouldRecord() {
return false;
}
@Override
public void setUpdateThread(Thread t) { }
}
| 9,263 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/SamplingStatusListener.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
public interface SamplingStatusListener {
public void samplingStatusChanged(boolean samplingOn);
}
| 9,264 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/sampling/HollowSampler.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.sampling;
import com.netflix.hollow.core.read.filter.HollowFilterConfig;
import java.util.Collection;
public interface HollowSampler {
public void setSamplingDirector(HollowSamplingDirector director);
public void setFieldSpecificSamplingDirector(HollowFilterConfig fieldSpec, HollowSamplingDirector director);
public void setUpdateThread(Thread t);
public boolean hasSampleResults();
public Collection<SampleResult> getSampleResults();
public void reset();
}
| 9,265 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/HollowObject.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects;
import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.schema.HollowObjectSchema;
/**
* A HollowObject provides an interface for accessing data from an OBJECT record in
* a hollow dataset.
*/
public abstract class HollowObject implements HollowRecord {
protected final int ordinal;
protected final HollowObjectDelegate delegate;
public HollowObject(HollowObjectDelegate delegate, int ordinal) {
this.ordinal = ordinal;
this.delegate = delegate;
}
@Override
public final int getOrdinal() {
return ordinal;
}
public final boolean isNull(String fieldName) {
return delegate.isNull(ordinal, fieldName);
}
public final boolean getBoolean(String fieldName) {
return delegate.getBoolean(ordinal, fieldName);
}
public final int getOrdinal(String fieldName) {
return delegate.getOrdinal(ordinal, fieldName);
}
public final int getInt(String fieldName) {
return delegate.getInt(ordinal, fieldName);
}
public final long getLong(String fieldName) {
return delegate.getLong(ordinal, fieldName);
}
public final float getFloat(String fieldName) {
return delegate.getFloat(ordinal, fieldName);
}
public final double getDouble(String fieldName) {
return delegate.getDouble(ordinal, fieldName);
}
public final String getString(String fieldName) {
return delegate.getString(ordinal, fieldName);
}
public final boolean isStringFieldEqual(String fieldName, String testValue) {
return delegate.isStringFieldEqual(ordinal, fieldName, testValue);
}
public final byte[] getBytes(String fieldName) {
return delegate.getBytes(ordinal, fieldName);
}
@Override
public HollowObjectSchema getSchema() {
return delegate.getSchema();
}
@Override
public HollowObjectTypeDataAccess getTypeDataAccess() {
return delegate.getTypeDataAccess();
}
@Override
public int hashCode() {
return ordinal;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof HollowObject) {
HollowObject hollowObj = (HollowObject)obj;
if(ordinal == hollowObj.getOrdinal()) {
String otherType = hollowObj.getSchema().getName();
String myType = getSchema().getName();
return myType.equals(otherType);
}
}
return false;
}
@Override
public String toString() {
return "Hollow Object: " + getSchema().getName() + " (" + ordinal + ")";
}
@Override
public HollowRecordDelegate getDelegate() {
return delegate;
}
} | 9,266 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/HollowSet.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.api.objects.delegate.HollowSetDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator;
import com.netflix.hollow.core.schema.HollowSetSchema;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A HollowSet provides an implementation of the {@link java.util.Set} interface over
* a SET record in a Hollow dataset.
*
* Also provides the findElement() method, which allows for searching the set for elements with matching hash keys.
*/
public abstract class HollowSet<T> extends AbstractSet<T> implements HollowRecord {
protected final int ordinal;
protected final HollowSetDelegate<T> delegate;
public HollowSet(HollowSetDelegate<T> delegate, int ordinal) {
this.ordinal = ordinal;
this.delegate = delegate;
}
@Override
public final int getOrdinal() {
return ordinal;
}
@Override
public final int size() {
return delegate.size(ordinal);
}
@Override
public boolean contains(Object o) {
return delegate.contains(this, ordinal, o);
}
/**
* Find an element with the specified hash key.
*
* @param hashKey The hash key to match.
* @return The element if discovered, null otherwise.
*/
public T findElement(Object... hashKey) {
return delegate.findElement(this, ordinal, hashKey);
}
public abstract T instantiateElement(int elementOrdinal);
public abstract boolean equalsElement(int elementOrdinal, Object testObject);
@Override
public HollowSetSchema getSchema() {
return delegate.getSchema();
}
@Override
public HollowSetTypeDataAccess getTypeDataAccess() {
return delegate.getTypeDataAccess();
}
@Override
public final Iterator<T> iterator() {
return new Itr();
}
@Override
public HollowRecordDelegate getDelegate() {
return delegate;
}
@Override
public boolean equals(Object o) {
// Note: hashCode is computed from the set's contents, see AbstractSet.hashCode
if (this == o) {
return true;
}
// If type state is the same then compare ordinals
if (o instanceof HollowSet) {
HollowSet<?> that = (HollowSet<?>) o;
if (delegate.getTypeDataAccess() == that.delegate.getTypeDataAccess()) {
return ordinal == that.ordinal;
}
}
// Otherwise, compare the contents
return super.equals(o);
}
private final class Itr implements Iterator<T> {
private final HollowOrdinalIterator ordinalIterator;
private T next;
Itr() {
this.ordinalIterator = delegate.iterator(ordinal);
positionNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T current = next;
positionNext();
return current;
}
private void positionNext() {
int currentOrdinal = ordinalIterator.next();
if(currentOrdinal != HollowOrdinalIterator.NO_MORE_ORDINALS)
next = instantiateElement(currentOrdinal);
else
next = null;
}
}
}
| 9,267 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/HollowRecord.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
import com.netflix.hollow.core.schema.HollowSchema;
/**
* A HollowRecord is the base interface for accessing data from any kind of record
* in a Hollow dataset.
*/
public interface HollowRecord {
public int getOrdinal();
public HollowSchema getSchema();
public HollowTypeDataAccess getTypeDataAccess();
public HollowRecordDelegate getDelegate();
}
| 9,268 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/HollowMap.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects;
import com.netflix.hollow.api.objects.delegate.HollowMapDelegate;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator;
import com.netflix.hollow.core.schema.HollowMapSchema;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
/**
* A HollowMap provides an implementation of the {@link java.util.Map} interface over
* a MAP record in a Hollow dataset.
*/
public abstract class HollowMap<K, V> extends AbstractMap<K, V> implements HollowRecord {
protected final int ordinal;
protected final HollowMapDelegate<K, V> delegate;
public HollowMap(HollowMapDelegate<K, V> delegate, int ordinal) {
this.ordinal = ordinal;
this.delegate = delegate;
}
@Override
public final int getOrdinal() {
return ordinal;
}
@Override
public final int size() {
return delegate.size(ordinal);
}
@Override
public final Set<Map.Entry<K, V>> entrySet() {
return new EntrySet();
}
@Override
public final V get(Object key) {
return delegate.get(this, ordinal, key);
}
@Override
public final boolean containsKey(Object key) {
return delegate.containsKey(this, ordinal, key);
}
@Override
public final boolean containsValue(Object value) {
return delegate.containsValue(this, ordinal, value);
}
public final K findKey(Object... hashKey) {
return delegate.findKey(this, ordinal, hashKey);
}
public final V findValue(Object... hashKey) {
return delegate.findValue(this, ordinal, hashKey);
}
public final Map.Entry<K, V> findEntry(Object... hashKey) {
return delegate.findEntry(this, ordinal, hashKey);
}
public abstract K instantiateKey(int keyOrdinal);
public abstract V instantiateValue(int valueOrdinal);
public abstract boolean equalsKey(int keyOrdinal, Object testObject);
public abstract boolean equalsValue(int valueOrdinal, Object testObject);
@Override
public HollowMapSchema getSchema() {
return delegate.getSchema();
}
@Override
public HollowMapTypeDataAccess getTypeDataAccess() {
return delegate.getTypeDataAccess();
}
@Override
public HollowRecordDelegate getDelegate() {
return delegate;
}
@Override
public boolean equals(Object o) {
// Note: hashCode is computed from the map's contents, see AbstractMap.hashCode
if (this == o) {
return true;
}
// If type state is the same then compare ordinals
if (o instanceof HollowMap) {
HollowMap<?, ?> that = (HollowMap<?, ?>) o;
if (delegate.getTypeDataAccess() == that.delegate.getTypeDataAccess()) {
return ordinal == that.ordinal;
}
}
// Otherwise, compare the contents
return super.equals(o);
}
private final class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryItr();
}
@Override
public int size() {
return delegate.size(ordinal);
}
}
private final class EntryItr implements Iterator<Map.Entry<K, V>> {
private final HollowMapEntryOrdinalIterator ordinalIterator;
private Map.Entry<K, V> next;
EntryItr() {
this.ordinalIterator = delegate.iterator(ordinal);
positionNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Map.Entry<K, V> current = next;
positionNext();
return current;
}
private void positionNext() {
if(ordinalIterator.next()) {
next = new OrdinalEntry<>(HollowMap.this, ordinalIterator.getKey(), ordinalIterator.getValue());
} else {
next = null;
}
}
}
private final static class OrdinalEntry<K, V> implements Map.Entry<K, V> {
private final HollowMap<K, V> map;
private final int keyOrdinal;
private final int valueOrdinal;
OrdinalEntry(HollowMap<K, V> map, int keyOrdinal, int valueOrdinal) {
this.map = map;
this.keyOrdinal = keyOrdinal;
this.valueOrdinal = valueOrdinal;
}
@Override
public K getKey() {
return map.instantiateKey(keyOrdinal);
}
@Override
public V getValue() {
return map.instantiateValue(valueOrdinal);
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Map.Entry)) {
return false;
}
if (o instanceof OrdinalEntry) {
OrdinalEntry<?, ?> that = (OrdinalEntry) o;
if (map.delegate.getTypeDataAccess() == that.map.delegate.getTypeDataAccess()) {
return keyOrdinal == that.keyOrdinal &&
valueOrdinal == that.valueOrdinal;
}
}
Map.Entry<?, ?> that = (Map.Entry) o;
return Objects.equals(getKey(),that.getKey()) &&
Objects.equals(getValue(),that.getValue());
}
}
}
| 9,269 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/HollowList.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects;
import com.netflix.hollow.api.objects.delegate.HollowListDelegate;
import com.netflix.hollow.api.objects.delegate.HollowRecordDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.core.schema.HollowListSchema;
import java.util.AbstractList;
/**
* A HollowList provides an implementation of the {@link java.util.List} interface over
* a LIST record in a Hollow dataset.
*/
public abstract class HollowList<T> extends AbstractList<T> implements HollowRecord {
protected final int ordinal;
protected final HollowListDelegate<T> delegate;
public HollowList(HollowListDelegate<T> delegate, int ordinal) {
this.ordinal = ordinal;
this.delegate = delegate;
}
@Override
public final int getOrdinal() {
return ordinal;
}
@Override
public final int size() {
return delegate.size(ordinal);
}
@Override
public final T get(int index) {
return delegate.get(this, ordinal, index);
}
@Override
public final boolean contains(Object o) {
return delegate.contains(this, ordinal, o);
}
@Override
public final int indexOf(Object o) {
return delegate.indexOf(this, ordinal, o);
}
@Override
public final int lastIndexOf(Object o) {
return delegate.lastIndexOf(this, ordinal, o);
}
public abstract T instantiateElement(int elementOrdinal);
public abstract boolean equalsElement(int elementOrdinal, Object testObject);
@Override
public HollowListSchema getSchema() {
return delegate.getSchema();
}
@Override
public HollowListTypeDataAccess getTypeDataAccess() {
return delegate.getTypeDataAccess();
}
@Override
public HollowRecordDelegate getDelegate() {
return delegate;
}
@Override
public boolean equals(Object o) {
// Note: hashCode is computed from the list's contents, see AbstractList.hashCode
if (this == o) {
return true;
}
// If type state is the same then compare ordinals
if (o instanceof HollowList) {
HollowList<?> that = (HollowList<?>) o;
if (delegate.getTypeDataAccess() == that.delegate.getTypeDataAccess()) {
return ordinal == that.ordinal;
}
}
// Otherwise, compare the contents
return super.equals(o);
}
}
| 9,270 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/provider/HollowFactory.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.provider;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
/**
* A HollowFactory is responsible for returning objects in a generated Hollow Object API. The HollowFactory for individual
* types can be overridden to return hand-coded implementations of specific record types.
*/
public abstract class HollowFactory<T> {
public abstract T newHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal);
public T newCachedHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) {
return newHollowObject(dataAccess, typeAPI, ordinal);
}
}
| 9,271 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/provider/HollowObjectCacheProvider.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.provider;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowCachedDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
import com.netflix.hollow.core.read.engine.HollowTypeReadState;
import com.netflix.hollow.core.read.engine.HollowTypeStateListener;
import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A HollowObjectCacheProvider caches and returns Object representations (presumably {@link HollowRecord}s) of
* records of a specific type.
*/
public class HollowObjectCacheProvider<T> extends HollowObjectProvider<T> implements HollowTypeStateListener {
private static final Logger log = Logger.getLogger(HollowObjectCacheProvider.class.getName());
private volatile List<T> cachedItems;
private volatile HollowFactory<T> factory;
private volatile HollowTypeAPI typeAPI;
private volatile HollowTypeReadState typeReadState;
public HollowObjectCacheProvider(HollowTypeDataAccess typeDataAccess, HollowTypeAPI typeAPI, HollowFactory<T> factory) {
this(typeDataAccess, typeAPI, factory, null);
}
public HollowObjectCacheProvider(HollowTypeDataAccess typeDataAccess, HollowTypeAPI typeAPI, HollowFactory<T> factory, HollowObjectCacheProvider<T> previous) {
if(typeDataAccess != null) {
PopulatedOrdinalListener listener = typeDataAccess.getTypeState().getListener(PopulatedOrdinalListener.class);
BitSet populatedOrdinals = listener.getPopulatedOrdinals();
BitSet previousOrdinals = listener.getPreviousOrdinals();
int length = Math.max(populatedOrdinals.length(), previousOrdinals.length());
List<T> arr = new ArrayList<T>(length);
for(int ordinal = 0; ordinal < length; ordinal++) {
while(ordinal >= arr.size())
arr.add(null);
if(previous != null && previousOrdinals.get(ordinal) && populatedOrdinals.get(ordinal)) {
T cached = previous.getHollowObject(ordinal);
arr.set(ordinal, cached);
if(cached instanceof HollowRecord)
((HollowCachedDelegate)((HollowRecord)cached).getDelegate()).updateTypeAPI(typeAPI);
} else if(populatedOrdinals.get(ordinal)){
arr.set(ordinal, instantiateCachedObject(factory, typeDataAccess, typeAPI, ordinal));
}
}
if(typeDataAccess instanceof HollowTypeReadState) {
this.factory = factory;
this.typeAPI = typeAPI;
this.typeReadState = (HollowTypeReadState)typeDataAccess;
this.typeReadState.addListener(this);
}
this.cachedItems = arr;
} else {
this.cachedItems = Collections.emptyList();
}
}
@Override
public T getHollowObject(int ordinal) {
List<T> refCachedItems = cachedItems;
if (refCachedItems == null) {
throw new IllegalStateException(String.format("HollowObjectCacheProvider for type %s has been detached or was not initialized", typeReadState == null ? null : typeReadState.getSchema().getName()));
}
if (refCachedItems.size() <= ordinal) {
throw new IllegalStateException(String.format("Ordinal %s is out of bounds for pojo cache array of size %s.", ordinal, refCachedItems.size()));
}
return refCachedItems.get(ordinal);
}
public void detach() {
cachedItems = null;
factory = null;
typeAPI = null;
typeReadState = null;
}
@Override
public void addedOrdinal(int ordinal) {
// guard against being detached (or constructed without a HollowTypeReadState)
if (factory == null) {
return;
}
for (int i = cachedItems.size(); i <= ordinal; ++i)
cachedItems.add(null);
cachedItems.set(ordinal, instantiateCachedObject(factory, typeReadState, typeAPI, ordinal));
}
private T instantiateCachedObject(HollowFactory<T> factory, HollowTypeDataAccess typeDataAccess, HollowTypeAPI typeAPI, int ordinal) {
try {
return factory.newCachedHollowObject(typeDataAccess, typeAPI, ordinal);
} catch(Throwable th) {
log.log(Level.SEVERE, "Cached object instantiation failed", th);
return null;
}
}
@Override public void beginUpdate() { }
@Override public void removedOrdinal(int ordinal) { }
@Override public void endUpdate() { }
}
| 9,272 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/provider/HollowObjectProvider.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.provider;
/**
* A HollowObjectProvider, either one of {@link HollowObjectFactoryProvider} or {@link HollowObjectCacheProvider},
* depending on whether the specific type is "cached".
*/
public abstract class HollowObjectProvider<T> {
public abstract T getHollowObject(int ordinal);
}
| 9,273 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/provider/HollowObjectFactoryProvider.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.provider;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
/**
* A HollowObjectFactoryProvider recreates Hollow objects each time they are called for.
*/
public class HollowObjectFactoryProvider<T> extends HollowObjectProvider<T> {
private final HollowTypeDataAccess dataAccess;
private final HollowTypeAPI typeAPI;
private final HollowFactory<T> factory;
public HollowObjectFactoryProvider(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, HollowFactory<T> factory) {
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
this.factory = factory;
}
@Override
public T getHollowObject(int ordinal) {
return factory.newHollowObject(dataAccess, typeAPI, ordinal);
}
}
| 9,274 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowListLookupDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowListTypeAPI;
import com.netflix.hollow.api.objects.HollowList;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.core.schema.HollowListSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for lookup LIST type records.
*
* @see HollowRecordDelegate
*/
public class HollowListLookupDelegate<T> implements HollowListDelegate<T> {
private final HollowListTypeDataAccess dataAccess;
protected final HollowListTypeAPI typeAPI;
public HollowListLookupDelegate(HollowListTypeDataAccess dataAccess) {
this(dataAccess, null);
}
public HollowListLookupDelegate(HollowListTypeAPI typeAPI) {
this(typeAPI.getTypeDataAccess(), typeAPI);
}
private HollowListLookupDelegate(HollowListTypeDataAccess dataAccess, HollowListTypeAPI typeAPI) {
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return dataAccess.size(ordinal);
}
@Override
public T get(HollowList<T> list, int ordinal, int index) {
int elementOrdinal = dataAccess.getElementOrdinal(ordinal, index);
return list.instantiateElement(elementOrdinal);
}
@Override
public final boolean contains(HollowList<T> list, int ordinal, Object o) {
return indexOf(list, ordinal, o) != -1;
}
@Override
public final int indexOf(HollowList<T> list, int ordinal, Object o) {
int size = size(ordinal);
for(int i=0;i<size;i++) {
int elementOrdinal = dataAccess.getElementOrdinal(ordinal, i);
if(list.equalsElement(elementOrdinal, o))
return i;
}
return -1;
}
@Override
public final int lastIndexOf(HollowList<T> list, int ordinal, Object o) {
int size = size(ordinal);
for(int i=size - 1; i>=0; i--) {
int elementOrdinal = dataAccess.getElementOrdinal(ordinal, i);
if(list.equalsElement(elementOrdinal, o))
return i;
}
return -1;
}
@Override
public HollowListSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowListTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowListTypeAPI getTypeAPI() {
return typeAPI;
}
}
| 9,275 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowListDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowListTypeAPI;
import com.netflix.hollow.api.objects.HollowList;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.core.schema.HollowListSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for LIST type records.
*
* @see HollowRecordDelegate
*/
public interface HollowListDelegate<T> extends HollowRecordDelegate {
public int size(int ordinal);
public T get(HollowList<T> list, int ordinal, int index);
public boolean contains(HollowList<T> list, int ordinal, Object o);
public int indexOf(HollowList<T> list, int ordinal, Object o);
public int lastIndexOf(HollowList<T> list, int ordinal, Object o);
public HollowListSchema getSchema();
public HollowListTypeDataAccess getTypeDataAccess();
public HollowListTypeAPI getTypeAPI();
}
| 9,276 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowObjectAbstractDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.read.missing.MissingDataHandler;
/**
* Contains some basic convenience access methods for OBJECT record fields.
*
* @see HollowRecordDelegate
*/
public abstract class HollowObjectAbstractDelegate implements HollowObjectDelegate {
@Override
public boolean isNull(int ordinal, String fieldName) {
try {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleIsNull(getSchema().getName(), ordinal, fieldName);
return dataAccess.isNull(ordinal, fieldIndex);
} catch(Exception ex) {
throw new RuntimeException(String.format("Unable to handle ordinal=%s, fieldName=%s", ordinal, fieldName), ex);
}
}
@Override
public boolean getBoolean(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
Boolean bool = (fieldIndex != -1) ?
dataAccess.readBoolean(ordinal, fieldIndex)
: missingDataHandler().handleBoolean(getSchema().getName(), ordinal, fieldName);
return bool == null ? false : bool.booleanValue();
}
@Override
public int getOrdinal(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleReferencedOrdinal(getSchema().getName(), ordinal, fieldName);
return dataAccess.readOrdinal(ordinal, fieldIndex);
}
@Override
public int getInt(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleInt(getSchema().getName(), ordinal, fieldName);
return dataAccess.readInt(ordinal, fieldIndex);
}
@Override
public long getLong(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleLong(getSchema().getName(), ordinal, fieldName);
return dataAccess.readLong(ordinal, fieldIndex);
}
@Override
public float getFloat(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleFloat(getSchema().getName(), ordinal, fieldName);
return dataAccess.readFloat(ordinal, fieldIndex);
}
@Override
public double getDouble(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleDouble(getSchema().getName(), ordinal, fieldName);
return dataAccess.readDouble(ordinal, fieldIndex);
}
@Override
public String getString(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1)
return missingDataHandler().handleString(getSchema().getName(), ordinal, fieldName);
return dataAccess.readString(ordinal, fieldIndex);
}
@Override
public boolean isStringFieldEqual(int ordinal, String fieldName, String testValue) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1) {
return missingDataHandler().handleStringEquals(getSchema().getName(), ordinal, fieldName, testValue);
}
return dataAccess.isStringFieldEqual(ordinal, fieldIndex, testValue);
}
@Override
public byte[] getBytes(int ordinal, String fieldName) {
HollowObjectTypeDataAccess dataAccess = getTypeDataAccess();
int fieldIndex = getSchema().getPosition(fieldName);
if(fieldIndex == -1) {
return missingDataHandler().handleBytes(getSchema().getName(), ordinal, fieldName);
}
return dataAccess.readBytes(ordinal, fieldIndex);
}
private MissingDataHandler missingDataHandler() {
return getTypeDataAccess().getDataAccess().getMissingDataHandler();
}
}
| 9,277 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowMapCachedDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowMapTypeAPI;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.HollowMap;
import com.netflix.hollow.core.memory.encoding.HashCodes;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator;
import com.netflix.hollow.core.schema.HollowMapSchema;
import java.util.Map;
import java.util.Map.Entry;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for cached MAP type records.
*
* @see HollowRecordDelegate
*/
public class HollowMapCachedDelegate<K, V> implements HollowMapDelegate<K, V>, HollowCachedDelegate {
private final int ordinals[];
private final int hashMask;
private final int size;
protected HollowMapTypeAPI typeAPI;
private HollowMapTypeDataAccess dataAccess;
public HollowMapCachedDelegate(HollowMapTypeDataAccess dataAccess, int ordinal) {
this(dataAccess, null, ordinal);
}
public HollowMapCachedDelegate(HollowMapTypeAPI typeAPI, int ordinal) {
this(typeAPI.getTypeDataAccess(), typeAPI, ordinal);
}
private HollowMapCachedDelegate(HollowMapTypeDataAccess dataAccess, HollowMapTypeAPI typeAPI, int ordinal) {
int size = dataAccess.size(ordinal);
int ordinals[] = new int[HashCodes.hashTableSize(size) * 2];
for(int i=0;i<ordinals.length;i+=2) {
long bucketData = dataAccess.relativeBucket(ordinal, i/2);
ordinals[i] = (int)(bucketData >> 32);
ordinals[i + 1] = (int)bucketData;
}
this.ordinals = ordinals;
this.hashMask = (ordinals.length / 2) - 1;
this.size = size;
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return size;
}
@Override
public V get(HollowMap<K, V> map, int ordinal, Object key) {
if(getSchema().getHashKey() != null) {
for(int i=0;i<ordinals.length;i+=2) {
if(ordinals[i] != -1 && map.equalsKey(ordinals[i], key))
return map.instantiateValue(ordinals[i+1]);
}
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(key);
int bucket = (HashCodes.hashInt(hashCode) & hashMask) * 2;
while(ordinals[bucket] != -1) {
if(map.equalsKey(ordinals[bucket], key)) {
return map.instantiateValue(ordinals[bucket + 1]);
}
bucket += 2;
bucket &= ordinals.length - 1;
}
}
return null;
}
@Override
public boolean containsKey(HollowMap<K, V> map, int ordinal, Object key) {
if(getSchema().getHashKey() != null) {
for(int i=0;i<ordinals.length;i+=2) {
if(ordinals[i] != -1 && map.equalsKey(ordinals[i], key))
return true;
}
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(key);
int bucket = (HashCodes.hashInt(hashCode) & hashMask) * 2;
while(ordinals[bucket] != -1) {
if(map.equalsKey(ordinals[bucket], key)) {
return true;
}
bucket += 2;
bucket &= ordinals.length - 1;
}
}
return false;
}
@Override
public boolean containsValue(HollowMap<K, V> map, int ordinal, Object value) {
HollowMapEntryOrdinalIterator iter = iterator(ordinal);
while(iter.next()) {
if(map.equalsValue(iter.getValue(), value))
return true;
}
return false;
}
@Override
public K findKey(HollowMap<K, V> map, int ordinal, Object... hashKey) {
int keyOrdinal = dataAccess.findKey(ordinal, hashKey);
if(keyOrdinal != -1)
return map.instantiateKey(keyOrdinal);
return null;
}
@Override
public V findValue(HollowMap<K, V> map, int ordinal, Object... hashKey) {
int valueOrdinal = dataAccess.findValue(ordinal, hashKey);
if(valueOrdinal != -1)
return map.instantiateValue(valueOrdinal);
return null;
}
@Override
public Entry<K, V> findEntry(final HollowMap<K, V> map, int ordinal, Object... hashKey) {
final long entryOrdinals = dataAccess.findEntry(ordinal, hashKey);
if(entryOrdinals != -1L)
return new Map.Entry<K, V>() {
@Override
public K getKey() {
return map.instantiateKey((int)(entryOrdinals >> 32));
}
@Override
public V getValue() {
return map.instantiateValue((int)entryOrdinals);
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
};
return null;
}
@Override
public HollowMapEntryOrdinalIterator iterator(int ordinal) {
return new HollowMapEntryOrdinalIterator() {
private int bucket = -2;
@Override
public boolean next() {
do {
bucket += 2;
} while(bucket < ordinals.length && ordinals[bucket] == -1);
return bucket < ordinals.length;
}
@Override
public int getValue() {
return ordinals[bucket + 1];
}
@Override
public int getKey() {
return ordinals[bucket];
}
};
}
@Override
public HollowMapSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowMapTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowMapTypeAPI getTypeAPI() {
return typeAPI;
}
@Override
public void updateTypeAPI(HollowTypeAPI typeAPI) {
this.typeAPI = (HollowMapTypeAPI) typeAPI;
this.dataAccess = this.typeAPI.getTypeDataAccess();
}
}
| 9,278 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowSetLookupDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowSetTypeAPI;
import com.netflix.hollow.api.objects.HollowSet;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator;
import com.netflix.hollow.core.schema.HollowSetSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for lookup LIST type records.
*
* @see HollowRecordDelegate
*/
public class HollowSetLookupDelegate<T> implements HollowSetDelegate<T> {
private final HollowSetTypeDataAccess dataAccess;
protected final HollowSetTypeAPI typeAPI;
public HollowSetLookupDelegate(HollowSetTypeDataAccess dataAccess) {
this(dataAccess, null);
}
public HollowSetLookupDelegate(HollowSetTypeAPI typeAPI) {
this(typeAPI.getTypeDataAccess(), typeAPI);
}
private HollowSetLookupDelegate(HollowSetTypeDataAccess dataAccess, HollowSetTypeAPI typeAPI) {
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return dataAccess.size(ordinal);
}
@Override
public boolean contains(HollowSet<T> set, int ordinal, Object o) {
HollowOrdinalIterator iter;
if(getSchema().getHashKey() != null) {
iter = dataAccess.ordinalIterator(ordinal);
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(o);
iter = dataAccess.potentialMatchOrdinalIterator(ordinal, hashCode);
}
int potentialOrdinal = iter.next();
while(potentialOrdinal != HollowOrdinalIterator.NO_MORE_ORDINALS) {
if(set.equalsElement(potentialOrdinal, o))
return true;
potentialOrdinal = iter.next();
}
return false;
}
@Override
public T findElement(HollowSet<T> set, int ordinal, Object... keys) {
int elementOrdinal = dataAccess.findElement(ordinal, keys);
if(elementOrdinal != -1)
return set.instantiateElement(elementOrdinal);
return null;
}
@Override
public HollowOrdinalIterator iterator(int ordinal) {
return dataAccess.ordinalIterator(ordinal);
}
@Override
public HollowSetSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowSetTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowSetTypeAPI getTypeAPI() {
return typeAPI;
}
}
| 9,279 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowCachedDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.provider.HollowObjectCacheProvider;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for cached delegates.
*
* @see HollowRecordDelegate
*/
public interface HollowCachedDelegate extends HollowRecordDelegate {
/**
* Called by the {@link HollowObjectCacheProvider} when the api is updated.
* @param typeAPI the type api that is updated
*/
void updateTypeAPI(HollowTypeAPI typeAPI);
}
| 9,280 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowSetDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowSetTypeAPI;
import com.netflix.hollow.api.objects.HollowSet;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator;
import com.netflix.hollow.core.schema.HollowSetSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for SET type records.
*
* @see HollowRecordDelegate
*/
public interface HollowSetDelegate<T> extends HollowRecordDelegate {
public int size(int ordinal);
public boolean contains(HollowSet<T> set, int ordinal, Object o);
public T findElement(HollowSet<T> set, int ordinal, Object... keys);
public HollowOrdinalIterator iterator(int ordinal);
public HollowSetSchema getSchema();
public HollowSetTypeDataAccess getTypeDataAccess();
public HollowSetTypeAPI getTypeAPI();
}
| 9,281 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowListCachedDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowListTypeAPI;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.HollowList;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.core.schema.HollowListSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for cached LIST type records.
*
* @see HollowRecordDelegate
*/
public class HollowListCachedDelegate<T> implements HollowListDelegate<T>, HollowCachedDelegate {
private final int ordinals[];
protected HollowListTypeAPI typeAPI;
private HollowListTypeDataAccess dataAccess;
public HollowListCachedDelegate(HollowListTypeDataAccess dataAccess, int ordinal) {
this(dataAccess, null, ordinal);
}
public HollowListCachedDelegate(HollowListTypeAPI typeAPI, int ordinal) {
this(typeAPI.getTypeDataAccess(), typeAPI, ordinal);
}
private HollowListCachedDelegate(HollowListTypeDataAccess dataAccess, HollowListTypeAPI typeAPI, int ordinal) {
int ordinals[] = new int[dataAccess.size(ordinal)];
for(int i=0;i<ordinals.length;i++)
ordinals[i] = dataAccess.getElementOrdinal(ordinal, i);
this.ordinals = ordinals;
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return ordinals.length;
}
@Override
public T get(HollowList<T> list, int ordinal, int idx) {
return list.instantiateElement(ordinals[idx]);
}
@Override
public final boolean contains(HollowList<T> list, int ordinal, Object o) {
return indexOf(list, ordinal, o) != -1;
}
@Override
public final int indexOf(HollowList<T> list, int ordinal, Object o) {
for(int i=0;i<ordinals.length;i++) {
if(list.equalsElement(ordinals[i], o))
return i;
}
return -1;
}
@Override
public final int lastIndexOf(HollowList<T> list, int ordinal, Object o) {
for(int i=ordinals.length - 1; i>=0; i--) {
if(list.equalsElement(ordinals[i], o))
return i;
}
return -1;
}
@Override
public HollowListSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowListTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowListTypeAPI getTypeAPI() {
return typeAPI;
}
@Override
public void updateTypeAPI(HollowTypeAPI typeAPI) {
this.typeAPI = (HollowListTypeAPI) typeAPI;
this.dataAccess = this.typeAPI.getTypeDataAccess();
}
}
| 9,282 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowRecordDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
/**
* A HollowRecordDelegate is used by a generated Hollow Objects API to access data from the data model.
* <p>
* Two flavors of delegate currently exist -- lookup and cached.
* <p>
* The lookup delegate reads directly from a HollowDataAccess. The cached delegate will copy the data from a HollowDataAccess,
* then read from the copy of the data. The intention is that the cached delegate has the performance profile of a POJO, while
* the lookup delegate imposes the minor performance penalty incurred by reading directly from Hollow.
* <p>
* The performance penalty of a lookup delegate is minor enough that it doesn't usually matter except in the tightest of loops.
* If a type exists which has a low cardinality but is accessed disproportionately frequently, then it may be a good candidate
* to be represented with a cached delegate.
*
*/
public interface HollowRecordDelegate {
}
| 9,283 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowMapLookupDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowMapTypeAPI;
import com.netflix.hollow.api.objects.HollowMap;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator;
import com.netflix.hollow.core.schema.HollowMapSchema;
import java.util.Map;
import java.util.Map.Entry;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for lookup MAP type records.
*
* @see HollowRecordDelegate
*/
public class HollowMapLookupDelegate<K, V> implements HollowMapDelegate<K, V> {
private final HollowMapTypeDataAccess dataAccess;
protected final HollowMapTypeAPI typeAPI;
public HollowMapLookupDelegate(HollowMapTypeDataAccess dataAccess) {
this(dataAccess, null);
}
public HollowMapLookupDelegate(HollowMapTypeAPI typeAPI) {
this(typeAPI.getTypeDataAccess(), typeAPI);
}
private HollowMapLookupDelegate(HollowMapTypeDataAccess dataAccess, HollowMapTypeAPI typeAPI) {
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return dataAccess.size(ordinal);
}
@Override
public V get(HollowMap<K, V> map, int ordinal, Object key) {
HollowMapEntryOrdinalIterator iter;
if(getSchema().getHashKey() != null) {
iter = dataAccess.ordinalIterator(ordinal);
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(key);
iter = dataAccess.potentialMatchOrdinalIterator(ordinal, hashCode);
}
while(iter.next()) {
if(map.equalsKey(iter.getKey(), key))
return map.instantiateValue(iter.getValue());
}
return null;
}
@Override
public boolean containsKey(HollowMap<K, V> map, int ordinal, Object key) {
HollowMapEntryOrdinalIterator iter;
if(getSchema().getHashKey() != null) {
iter = dataAccess.ordinalIterator(ordinal);
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(key);
iter = dataAccess.potentialMatchOrdinalIterator(ordinal, hashCode);
}
while(iter.next()) {
if(map.equalsKey(iter.getKey(), key))
return true;
}
return false;
}
@Override
public boolean containsValue(HollowMap<K, V> map, int ordinal, Object value) {
HollowMapEntryOrdinalIterator iter = iterator(ordinal);
while(iter.next()) {
if(map.equalsValue(iter.getValue(), value))
return true;
}
return false;
}
@Override
public K findKey(HollowMap<K, V> map, int ordinal, Object... hashKey) {
int keyOrdinal = dataAccess.findKey(ordinal, hashKey);
if(keyOrdinal != -1)
return map.instantiateKey(keyOrdinal);
return null;
}
@Override
public V findValue(HollowMap<K, V> map, int ordinal, Object... hashKey) {
int valueOrdinal = dataAccess.findValue(ordinal, hashKey);
if(valueOrdinal != -1)
return map.instantiateValue(valueOrdinal);
return null;
}
@Override
public Entry<K, V> findEntry(final HollowMap<K, V> map, int ordinal, Object... hashKey) {
final long entryOrdinals = dataAccess.findEntry(ordinal, hashKey);
if(entryOrdinals != -1L)
return new Map.Entry<K, V>() {
@Override
public K getKey() {
return map.instantiateKey((int)(entryOrdinals >> 32));
}
@Override
public V getValue() {
return map.instantiateValue((int)entryOrdinals);
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
};
return null;
}
@Override
public HollowMapEntryOrdinalIterator iterator(int ordinal) {
return dataAccess.ordinalIterator(ordinal);
}
@Override
public HollowMapSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowMapTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowMapTypeAPI getTypeAPI() {
return typeAPI;
}
}
| 9,284 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowSetCachedDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowSetTypeAPI;
import com.netflix.hollow.api.custom.HollowTypeAPI;
import com.netflix.hollow.api.objects.HollowSet;
import com.netflix.hollow.core.memory.encoding.HashCodes;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator;
import com.netflix.hollow.core.schema.HollowSetSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for cached SET type records.
*
* @see HollowRecordDelegate
*/
public class HollowSetCachedDelegate<T> implements HollowSetDelegate<T>, HollowCachedDelegate {
private final int ordinals[];
private final int size;
private final int hashMask;
protected HollowSetTypeAPI typeAPI;
private HollowSetTypeDataAccess dataAccess;
public HollowSetCachedDelegate(HollowSetTypeDataAccess dataAccess, int ordinal) {
this(dataAccess, null, ordinal);
}
public HollowSetCachedDelegate(HollowSetTypeAPI typeAPI, int ordinal) {
this(typeAPI.getTypeDataAccess(), typeAPI, ordinal);
}
private HollowSetCachedDelegate(HollowSetTypeDataAccess dataAccess, HollowSetTypeAPI typeAPI, int ordinal) {
int size = dataAccess.size(ordinal);
int ordinals[] = new int[HashCodes.hashTableSize(size)];
for(int i=0;i<ordinals.length;i++) {
ordinals[i] = dataAccess.relativeBucketValue(ordinal, i);
}
this.ordinals = ordinals;
this.size = size;
this.hashMask = ordinals.length - 1;
this.dataAccess = dataAccess;
this.typeAPI = typeAPI;
}
@Override
public int size(int ordinal) {
return size;
}
@Override
public boolean contains(HollowSet<T> set, int ordinal, Object o) {
if(getSchema().getHashKey() != null) {
for(int i=0;i<ordinals.length;i++) {
if(ordinals[i] != -1 && set.equalsElement(ordinals[i], o))
return true;
}
} else {
int hashCode = dataAccess.getDataAccess().getHashCodeFinder().hashCode(o);
int bucket = HashCodes.hashInt(hashCode) & hashMask;
while(ordinals[bucket] != -1) {
if(set.equalsElement(ordinals[bucket], o))
return true;
bucket ++;
bucket &= hashMask;
}
}
return false;
}
@Override
public T findElement(HollowSet<T> set, int ordinal, Object... keys) {
int elementOrdinal = dataAccess.findElement(ordinal, keys);
if(elementOrdinal != -1)
return set.instantiateElement(elementOrdinal);
return null;
}
@Override
public HollowOrdinalIterator iterator(int ordinal) {
return new HollowOrdinalIterator() {
private int bucket = -1;
@Override
public int next() {
do {
bucket++;
} while(bucket < ordinals.length && ordinals[bucket] == -1);
if(bucket >= ordinals.length)
return NO_MORE_ORDINALS;
return ordinals[bucket];
}
};
}
@Override
public HollowSetSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowSetTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowSetTypeAPI getTypeAPI() {
return typeAPI;
}
@Override
public void updateTypeAPI(HollowTypeAPI typeAPI) {
this.typeAPI = (HollowSetTypeAPI) typeAPI;
this.dataAccess = this.typeAPI.getTypeDataAccess();
}
}
| 9,285 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowObjectDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowObjectTypeAPI;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.schema.HollowObjectSchema;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for OBJECT type records.
*
* @see HollowRecordDelegate
*/
public interface HollowObjectDelegate extends HollowRecordDelegate {
public boolean isNull(int ordinal, String fieldName);
public boolean getBoolean(int ordinal, String fieldName);
public int getOrdinal(int ordinal, String fieldName);
public int getInt(int ordinal, String fieldName);
public long getLong(int ordinal, String fieldName);
public float getFloat(int ordinal, String fieldName);
public double getDouble(int ordinal, String fieldName);
public String getString(int ordinal, String fieldName);
public boolean isStringFieldEqual(int ordinal, String fieldName, String testValue);
public byte[] getBytes(int ordinal, String fieldName);
public HollowObjectSchema getSchema();
public HollowObjectTypeDataAccess getTypeDataAccess();
public HollowObjectTypeAPI getTypeAPI();
}
| 9,286 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowObjectGenericDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowObjectTypeAPI;
import com.netflix.hollow.api.objects.generic.GenericHollowObject;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.schema.HollowObjectSchema;
/**
* A delegate used by the {@link GenericHollowObject} of the Generic Hollow Object API.
*
* @see HollowRecordDelegate
*/
public class HollowObjectGenericDelegate extends HollowObjectAbstractDelegate {
private final HollowObjectTypeDataAccess dataAccess;
public HollowObjectGenericDelegate(HollowObjectTypeDataAccess dataAccess) {
this.dataAccess = dataAccess;
}
@Override
public HollowObjectSchema getSchema() {
return dataAccess.getSchema();
}
@Override
public HollowObjectTypeDataAccess getTypeDataAccess() {
return dataAccess;
}
@Override
public HollowObjectTypeAPI getTypeAPI() {
return null;
}
}
| 9,287 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/delegate/HollowMapDelegate.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.delegate;
import com.netflix.hollow.api.custom.HollowMapTypeAPI;
import com.netflix.hollow.api.objects.HollowMap;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator;
import com.netflix.hollow.core.schema.HollowMapSchema;
import java.util.Map;
/**
* This is the extension of the {@link HollowRecordDelegate} interface for MAP type records.
*
* @see HollowRecordDelegate
*/
public interface HollowMapDelegate<K, V> extends HollowRecordDelegate {
public int size(int ordinal);
public V get(HollowMap<K, V> map, int ordinal, Object key);
public boolean containsKey(HollowMap<K, V> map, int ordinal, Object key);
public boolean containsValue(HollowMap<K, V> map, int ordinal, Object value);
public K findKey(HollowMap<K, V> map, int ordinal, Object... hashKey);
public V findValue(HollowMap<K, V> map, int ordinal, Object... hashKey);
public Map.Entry<K, V> findEntry(HollowMap<K, V> map, int ordinal, Object... hashKey);
public HollowMapEntryOrdinalIterator iterator(int ordinal);
public HollowMapSchema getSchema();
public HollowMapTypeDataAccess getTypeDataAccess();
public HollowMapTypeAPI getTypeAPI();
}
| 9,288 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowSet.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.HollowSet;
import com.netflix.hollow.api.objects.delegate.HollowSetDelegate;
import com.netflix.hollow.api.objects.delegate.HollowSetLookupDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.tools.stringifier.HollowRecordStringifier;
/**
* This is a generic handle to a SET type record.
*
* The Generic Hollow Object API can be used to programmatically inspect a dataset (referenced by a {@link HollowDataAccess})
* without a custom-generated API.
*/
public class GenericHollowSet extends HollowSet<HollowRecord> {
public GenericHollowSet(HollowDataAccess dataAccess, String type, int ordinal) {
this((HollowSetTypeDataAccess)dataAccess.getTypeDataAccess(type, ordinal), ordinal);
}
public GenericHollowSet(HollowSetTypeDataAccess dataAccess, int ordinal) {
this(new HollowSetLookupDelegate<HollowRecord>(dataAccess), ordinal);
}
public GenericHollowSet(HollowSetDelegate<HollowRecord> delegate, int ordinal) {
super(delegate, ordinal);
}
public Iterable<GenericHollowObject> objects() {
return new GenericHollowIterable<GenericHollowObject>(this);
}
public Iterable<GenericHollowList> lists() {
return new GenericHollowIterable<GenericHollowList>(this);
}
public Iterable<GenericHollowSet> sets() {
return new GenericHollowIterable<GenericHollowSet>(this);
}
public Iterable<GenericHollowMap> maps() {
return new GenericHollowIterable<GenericHollowMap>(this);
}
@Override
public HollowRecord instantiateElement(int elementOrdinal) {
return GenericHollowRecordHelper.instantiate(getTypeDataAccess().getDataAccess(), getSchema().getElementType(), elementOrdinal);
}
@Override
public boolean equalsElement(int elementOrdinal, Object testObject) {
return GenericHollowRecordHelper.equalObject(getSchema().getElementType(), elementOrdinal, testObject);
}
@Override
public String toString() {
return new HollowRecordStringifier().stringify(this);
}
}
| 9,289 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowObject.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowObject;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate;
import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.tools.stringifier.HollowRecordStringifier;
/**
* This is a generic handle to an OBJECT type record.
*
* The Generic Hollow Object API can be used to programmatically inspect a dataset (referenced by a {@link HollowDataAccess})
* without a custom-generated API.
*/
public class GenericHollowObject extends HollowObject {
public GenericHollowObject(HollowDataAccess dataAccess, String typeName, int ordinal) {
this((HollowObjectTypeDataAccess)dataAccess.getTypeDataAccess(typeName, ordinal), ordinal);
}
public GenericHollowObject(HollowObjectTypeDataAccess dataAccess, int ordinal) {
this(new HollowObjectGenericDelegate(dataAccess), ordinal);
}
public GenericHollowObject(HollowObjectDelegate delegate, int ordinal) {
super(delegate, ordinal);
}
public GenericHollowObject getObject(String fieldName) {
return (GenericHollowObject) getReferencedGenericRecord(fieldName);
}
public GenericHollowList getList(String fieldName) {
return (GenericHollowList) getReferencedGenericRecord(fieldName);
}
public GenericHollowSet getSet(String fieldName) {
return (GenericHollowSet) getReferencedGenericRecord(fieldName);
}
public GenericHollowMap getMap(String fieldName) {
return (GenericHollowMap) getReferencedGenericRecord(fieldName);
}
public final HollowRecord getReferencedGenericRecord(String fieldName) {
String referencedType = getSchema().getReferencedType(fieldName);
if(referencedType == null) {
try {
HollowObjectSchema hollowObjectSchema = (HollowObjectSchema)getTypeDataAccess().getDataAccess().getMissingDataHandler().handleSchema(getSchema().getName());
referencedType = hollowObjectSchema.getReferencedType(fieldName);
if(referencedType == null)
return null;
} catch(Exception e) {
return null;
}
}
int ordinal = getOrdinal(fieldName);
if(ordinal == -1)
return null;
return GenericHollowRecordHelper.instantiate(getTypeDataAccess().getDataAccess(), referencedType, ordinal);
}
@Override
public String toString() {
return new HollowRecordStringifier().stringify(this);
}
} | 9,290 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowList.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowList;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowListDelegate;
import com.netflix.hollow.api.objects.delegate.HollowListLookupDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.tools.stringifier.HollowRecordStringifier;
/**
* This is a generic handle to a LIST type record.
*
* The Generic Hollow Object API can be used to programmatically inspect a dataset (referenced by a {@link HollowDataAccess})
* without a custom-generated API.
*/
public class GenericHollowList extends HollowList<HollowRecord> {
public GenericHollowList(HollowDataAccess dataAccess, String type, int ordinal) {
this((HollowListTypeDataAccess)dataAccess.getTypeDataAccess(type, ordinal), ordinal);
}
public GenericHollowList(HollowListTypeDataAccess dataAccess, int ordinal) {
this(new HollowListLookupDelegate<HollowRecord>(dataAccess), ordinal);
}
public GenericHollowList(HollowListDelegate<HollowRecord> delegate, int ordinal) {
super(delegate, ordinal);
}
public GenericHollowObject getObject(int idx) {
return (GenericHollowObject)get(idx);
}
public Iterable<GenericHollowObject> objects() {
return new GenericHollowIterable<GenericHollowObject>(this);
}
public Iterable<GenericHollowList> lists() {
return new GenericHollowIterable<GenericHollowList>(this);
}
public Iterable<GenericHollowSet> sets() {
return new GenericHollowIterable<GenericHollowSet>(this);
}
public Iterable<GenericHollowMap> maps() {
return new GenericHollowIterable<GenericHollowMap>(this);
}
@Override
public HollowRecord instantiateElement(int elementOrdinal) {
return GenericHollowRecordHelper.instantiate(getTypeDataAccess().getDataAccess(), getSchema().getElementType(), elementOrdinal);
}
@Override
public boolean equalsElement(int elementOrdinal, Object testObject) {
return GenericHollowRecordHelper.equalObject(getSchema().getElementType(), elementOrdinal, testObject);
}
@Override
public String toString() {
return new HollowRecordStringifier().stringify(this);
}
}
| 9,291 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowRecordHelper.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowListLookupDelegate;
import com.netflix.hollow.api.objects.delegate.HollowMapLookupDelegate;
import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate;
import com.netflix.hollow.api.objects.delegate.HollowSetLookupDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowListTypeDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess;
import com.netflix.hollow.core.read.dataaccess.missing.HollowListMissingDataAccess;
import com.netflix.hollow.core.read.dataaccess.missing.HollowMapMissingDataAccess;
import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess;
import com.netflix.hollow.core.read.dataaccess.missing.HollowSetMissingDataAccess;
import com.netflix.hollow.core.schema.HollowListSchema;
import com.netflix.hollow.core.schema.HollowMapSchema;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSetSchema;
/**
* Contains some useful methods for interacting with the Generic Hollow Objects API.
*/
public class GenericHollowRecordHelper {
public static HollowRecord instantiate(HollowDataAccess dataAccess, String typeName, int ordinal) {
HollowTypeDataAccess typeState = dataAccess.getTypeDataAccess(typeName, ordinal);
if(typeState != null) {
if(typeState instanceof HollowObjectTypeDataAccess)
return new GenericHollowObject(new HollowObjectGenericDelegate((HollowObjectTypeDataAccess)typeState), ordinal);
if(typeState instanceof HollowListTypeDataAccess)
return new GenericHollowList(new HollowListLookupDelegate<HollowRecord>((HollowListTypeDataAccess)typeState), ordinal);
if(typeState instanceof HollowSetTypeDataAccess)
return new GenericHollowSet(new HollowSetLookupDelegate<HollowRecord>((HollowSetTypeDataAccess)typeState), ordinal);
if(typeState instanceof HollowMapTypeDataAccess)
return new GenericHollowMap(new HollowMapLookupDelegate<HollowRecord, HollowRecord>((HollowMapTypeDataAccess)typeState), ordinal);
} else {
HollowSchema schema = dataAccess.getMissingDataHandler().handleSchema(typeName);
if(schema instanceof HollowObjectSchema)
return new GenericHollowObject(new HollowObjectGenericDelegate(new HollowObjectMissingDataAccess(dataAccess, typeName)), ordinal);
if(schema instanceof HollowListSchema)
return new GenericHollowList(new HollowListLookupDelegate<HollowRecord>(new HollowListMissingDataAccess(dataAccess, typeName)), ordinal);
if(schema instanceof HollowSetSchema)
return new GenericHollowSet(new HollowSetLookupDelegate<HollowRecord>(new HollowSetMissingDataAccess(dataAccess, typeName)), ordinal);
if(schema instanceof HollowMapSchema)
return new GenericHollowMap(new HollowMapLookupDelegate<HollowRecord, HollowRecord>(new HollowMapMissingDataAccess(dataAccess, typeName)), ordinal);
}
throw new UnsupportedOperationException("I don't know how to instantiate a generic object given a " + typeState.getClass().getSimpleName());
}
public static boolean equalObject(String typeName, int ordinal, Object testObject) {
if(testObject instanceof HollowRecord) {
HollowRecord testRec = (HollowRecord)testObject;
if(testRec.getOrdinal() == ordinal) {
String otherType = testRec.getSchema().getName();
return otherType.equals(typeName);
}
}
return false;
}
}
| 9,292 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowIterable.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowRecord;
import java.util.Iterator;
class GenericHollowIterable<T extends HollowRecord> implements Iterable<T> {
private final Iterable<HollowRecord> wrappedIterable;
GenericHollowIterable(Iterable<HollowRecord> wrap) {
this.wrappedIterable = wrap;
}
@Override
public Iterator<T> iterator() {
final Iterator<HollowRecord> iter = wrappedIterable.iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@SuppressWarnings("unchecked")
public T next() {
return (T) iter.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
| 9,293 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/objects/generic/GenericHollowMap.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.objects.generic;
import com.netflix.hollow.api.objects.HollowMap;
import com.netflix.hollow.api.objects.HollowRecord;
import com.netflix.hollow.api.objects.delegate.HollowMapDelegate;
import com.netflix.hollow.api.objects.delegate.HollowMapLookupDelegate;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import com.netflix.hollow.core.read.dataaccess.HollowMapTypeDataAccess;
import com.netflix.hollow.tools.stringifier.HollowRecordStringifier;
import java.util.Iterator;
import java.util.Map;
/**
* This is a generic handle to a MAP type record.
*
* The Generic Hollow Object API can be used to programmatically inspect a dataset (referenced by a {@link HollowDataAccess})
* without a custom-generated API.
*/
public class GenericHollowMap extends HollowMap<HollowRecord, HollowRecord>{
public GenericHollowMap(HollowDataAccess dataAccess, String type, int ordinal) {
this((HollowMapTypeDataAccess)dataAccess.getTypeDataAccess(type, ordinal), ordinal);
}
public GenericHollowMap(HollowMapTypeDataAccess dataAccess, int ordinal) {
this(new HollowMapLookupDelegate<HollowRecord, HollowRecord>(dataAccess), ordinal);
}
public GenericHollowMap(HollowMapDelegate<HollowRecord, HollowRecord> typeState, int ordinal) {
super(typeState, ordinal);
}
@Override
public HollowRecord instantiateKey(int keyOrdinal) {
return GenericHollowRecordHelper.instantiate(getTypeDataAccess().getDataAccess(), getSchema().getKeyType(), keyOrdinal);
}
@Override
public HollowRecord instantiateValue(int valueOrdinal) {
return GenericHollowRecordHelper.instantiate(getTypeDataAccess().getDataAccess(), getSchema().getValueType(), valueOrdinal);
}
@Override
public boolean equalsKey(int keyOrdinal, Object testObject) {
return GenericHollowRecordHelper.equalObject(getSchema().getKeyType(), keyOrdinal, testObject);
}
@Override
public boolean equalsValue(int valueOrdinal, Object testObject) {
return GenericHollowRecordHelper.equalObject(getSchema().getValueType(), valueOrdinal, testObject);
}
public <K extends HollowRecord, V extends HollowRecord> Iterable<Map.Entry<K, V>>entries() {
return new GenericHollowMapEntryIterable<K, V>(entrySet());
}
@Override
public String toString() {
return new HollowRecordStringifier().stringify(this);
}
static class GenericHollowMapEntryIterable<K extends HollowRecord, V extends HollowRecord> implements Iterable<Map.Entry<K, V>> {
private final Iterable<Map.Entry<HollowRecord, HollowRecord>> wrappedIterable;
public GenericHollowMapEntryIterable(Iterable<Map.Entry<HollowRecord, HollowRecord>> wrap) {
this.wrappedIterable = wrap;
}
@Override
public Iterator<Map.Entry<K, V>> iterator() {
final Iterator<Map.Entry<HollowRecord, HollowRecord>> iter = wrappedIterable.iterator();
return new Iterator<Map.Entry<K,V>>() {
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@SuppressWarnings("unchecked")
public Entry<K, V> next() {
Map.Entry<HollowRecord, HollowRecord> entry = iter.next();
return new GenericHollowMapEntry((K) entry.getKey(), (V) entry.getValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
private class GenericHollowMapEntry implements Map.Entry<K, V> {
private final K key;
private final V value;
public GenericHollowMapEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
}
}
| 9,294 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/codegen/ArgumentParser.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hollow.api.codegen;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArgumentParser<T extends Enum> {
public class ParsedArgument {
private final T key;
private final String value;
public ParsedArgument(T key, String value) {
this.key = key;
this.value = value;
}
public T getKey() {
return key;
}
public String getValue() {
return value;
}
}
private static final Pattern COMMAND_LINE_ARG_PATTERN = Pattern.compile("--(\\w+)=([\\w, ./-]+)");
private final List<ParsedArgument> parsedArguments = new ArrayList<>();
public ArgumentParser(Class<T> validArguments, String[] args) {
for (String arg : args) {
Matcher matcher = COMMAND_LINE_ARG_PATTERN.matcher(arg);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid argument " + arg);
}
String argK = matcher.group(1);
String argV = matcher.group(2);
try {
T key = (T) Enum.valueOf(validArguments, argK);
parsedArguments.add(new ParsedArgument(key, argV));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid argument " + arg);
}
}
}
public List<ParsedArgument> getParsedArguments() {
return this.parsedArguments;
}
}
| 9,295 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/codegen/CodeGeneratorConfig.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hollow.api.codegen;
public class CodeGeneratorConfig {
private String classPostfix = "";
private String getterPrefix = "";
private boolean useAggressiveSubstitutions = false;
// @TODO: Need to default this to be true in next major version of Hollow
private boolean usePackageGrouping = false;
private boolean useBooleanFieldErgonomics = false;
private boolean reservePrimaryKeyIndexForTypeWithPrimaryKey = false;
private boolean useHollowPrimitiveTypes = false;
private boolean restrictApiToFieldType = false;
private boolean useVerboseToString = false;
public CodeGeneratorConfig() {}
public CodeGeneratorConfig(String classPostfix, String getterPrefix) {
this.classPostfix = classPostfix;
this.getterPrefix = getterPrefix;
}
// Make it easier to automatically use defaults for next major version
public void initWithNextMajorVersionDefaults_V3() {
usePackageGrouping = true;
useBooleanFieldErgonomics = true;
reservePrimaryKeyIndexForTypeWithPrimaryKey = true;
useHollowPrimitiveTypes = true;
restrictApiToFieldType = true;
useVerboseToString = true;
}
public String getClassPostfix() {
return classPostfix;
}
public void setClassPostfix(String classPostfix) {
this.classPostfix = classPostfix;
}
public String getGetterPrefix() {
return getterPrefix;
}
public void setGetterPrefix(String getterPrefix) {
this.getterPrefix = getterPrefix;
}
public boolean isUsePackageGrouping() {
return usePackageGrouping;
}
public void setUsePackageGrouping(boolean usePackageGrouping) {
this.usePackageGrouping = usePackageGrouping;
}
public boolean isUseAggressiveSubstitutions() {
return useAggressiveSubstitutions;
}
public void setUseAggressiveSubstitutions(boolean useAggressiveSubstitutions) {
this.useAggressiveSubstitutions = useAggressiveSubstitutions;
}
public boolean isUseBooleanFieldErgonomics() {
return useBooleanFieldErgonomics;
}
public void setUseBooleanFieldErgonomics(boolean useBooleanFieldErgonomics) {
this.useBooleanFieldErgonomics = useBooleanFieldErgonomics;
}
public boolean isReservePrimaryKeyIndexForTypeWithPrimaryKey() {
return reservePrimaryKeyIndexForTypeWithPrimaryKey;
}
public void setReservePrimaryKeyIndexForTypeWithPrimaryKey(boolean reservePrimaryKeyIndexForTypeWithPrimaryKey) {
this.reservePrimaryKeyIndexForTypeWithPrimaryKey = reservePrimaryKeyIndexForTypeWithPrimaryKey;
}
public boolean isListenToDataRefresh() {
return !reservePrimaryKeyIndexForTypeWithPrimaryKey; // NOTE: to be backwards compatible
}
public boolean isUseHollowPrimitiveTypes() {
return useHollowPrimitiveTypes;
}
public void setUseHollowPrimitiveTypes(boolean useHollowPrimitiveTypes) {
this.useHollowPrimitiveTypes = useHollowPrimitiveTypes;
}
public boolean isRestrictApiToFieldType() {
return restrictApiToFieldType;
}
public void setRestrictApiToFieldType(boolean restrictApiToFieldType) {
this.restrictApiToFieldType = restrictApiToFieldType;
}
public boolean isUseVerboseToString() {
return useVerboseToString;
}
public void setUseVerboseToString(boolean useVerboseToString) {
this.useVerboseToString = useVerboseToString;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((classPostfix == null) ? 0 : classPostfix.hashCode());
result = prime * result + ((getterPrefix == null) ? 0 : getterPrefix.hashCode());
result = prime * result + (reservePrimaryKeyIndexForTypeWithPrimaryKey ? 1231 : 1237);
result = prime * result + (restrictApiToFieldType ? 1231 : 1237);
result = prime * result + (useAggressiveSubstitutions ? 1231 : 1237);
result = prime * result + (useBooleanFieldErgonomics ? 1231 : 1237);
result = prime * result + (useHollowPrimitiveTypes ? 1231 : 1237);
result = prime * result + (usePackageGrouping ? 1231 : 1237);
result = prime * result + (useVerboseToString ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CodeGeneratorConfig other = (CodeGeneratorConfig) obj;
if (classPostfix == null) {
if (other.classPostfix != null)
return false;
} else if (!classPostfix.equals(other.classPostfix))
return false;
if (getterPrefix == null) {
if (other.getterPrefix != null)
return false;
} else if (!getterPrefix.equals(other.getterPrefix))
return false;
if (reservePrimaryKeyIndexForTypeWithPrimaryKey != other.reservePrimaryKeyIndexForTypeWithPrimaryKey)
return false;
if (restrictApiToFieldType != other.restrictApiToFieldType)
return false;
if (useAggressiveSubstitutions != other.useAggressiveSubstitutions)
return false;
if (useBooleanFieldErgonomics != other.useBooleanFieldErgonomics)
return false;
if (useHollowPrimitiveTypes != other.useHollowPrimitiveTypes)
return false;
if (usePackageGrouping != other.usePackageGrouping)
return false;
if (useVerboseToString != other.useVerboseToString)
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CodeGeneratorConfig [classPostfix=");
builder.append(classPostfix);
builder.append(", getterPrefix=");
builder.append(getterPrefix);
builder.append(", usePackageGrouping=");
builder.append(usePackageGrouping);
builder.append(", useAggressiveSubstitutions=");
builder.append(useAggressiveSubstitutions);
builder.append(", useBooleanFieldErgonomics=");
builder.append(useBooleanFieldErgonomics);
builder.append(", reservePrimaryKeyIndexForTypeWithPrimaryKey=");
builder.append(reservePrimaryKeyIndexForTypeWithPrimaryKey);
builder.append(", useHollowPrimitiveTypes=");
builder.append(useHollowPrimitiveTypes);
builder.append(", restrictApiToFieldType=");
builder.append(restrictApiToFieldType);
builder.append(", useVerboseToString=");
builder.append(useVerboseToString);
builder.append("]");
return builder.toString();
}
} | 9,296 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowErgonomicAPIShortcuts.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.codegen;
import com.netflix.hollow.core.HollowDataset;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSchema.SchemaType;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HollowErgonomicAPIShortcuts {
public static final HollowErgonomicAPIShortcuts NO_SHORTCUTS = new HollowErgonomicAPIShortcuts();
private final Map<String, Shortcut> shortcutFieldPaths;
private HollowErgonomicAPIShortcuts() {
this.shortcutFieldPaths = Collections.emptyMap();
}
HollowErgonomicAPIShortcuts(HollowDataset dataset) {
this.shortcutFieldPaths = new HashMap<String, Shortcut>();
populatePaths(dataset);
}
public Shortcut getShortcut(String typeField) {
return shortcutFieldPaths.get(typeField);
}
int numShortcuts() {
return shortcutFieldPaths.size();
}
private void populatePaths(HollowDataset dataset) {
for(HollowSchema schema : dataset.getSchemas()) {
if(schema.getSchemaType() == SchemaType.OBJECT) {
HollowObjectSchema objSchema = (HollowObjectSchema)schema;
for(int i=0;i<objSchema.numFields();i++) {
if(objSchema.getFieldType(i) == FieldType.REFERENCE) {
HollowSchema refSchema = dataset.getSchema(objSchema.getReferencedType(i));
if(refSchema != null) {
Shortcut shortcut = getShortcutFieldPath(dataset, refSchema);
if(shortcut != null) {
String key = objSchema.getName() + "." + objSchema.getFieldName(i);
shortcutFieldPaths.put(key, shortcut);
}
}
}
}
}
}
}
private Shortcut getShortcutFieldPath(HollowDataset dataset, HollowSchema schema) {
if(schema.getSchemaType() == SchemaType.OBJECT) {
HollowObjectSchema objSchema = (HollowObjectSchema)schema;
if(objSchema.numFields() == 1) {
if(objSchema.getFieldType(0) == FieldType.REFERENCE) {
HollowSchema refSchema = dataset.getSchema(objSchema.getReferencedType(0));
if(refSchema != null) {
Shortcut childShortcut = getShortcutFieldPath(dataset, refSchema);
if(childShortcut != null) {
String[] shortcutPathTypes = new String[childShortcut.getPathTypes().length+1];
String[] shortcutPath = new String[childShortcut.getPath().length+1];
shortcutPathTypes[0] = objSchema.getName();
shortcutPath[0] = objSchema.getFieldName(0);
System.arraycopy(childShortcut.getPath(), 0, shortcutPath, 1, childShortcut.getPath().length);
System.arraycopy(childShortcut.getPathTypes(), 0, shortcutPathTypes, 1, childShortcut.getPathTypes().length);
return new Shortcut(shortcutPathTypes, shortcutPath, childShortcut.getType());
}
}
} else {
return new Shortcut(new String[] { objSchema.getName() }, new String[] { objSchema.getFieldName(0) }, objSchema.getFieldType(0));
}
}
}
return null;
}
public String toString() {
StringBuilder builder = new StringBuilder();
for(Map.Entry<String, Shortcut> entry : shortcutFieldPaths.entrySet()) {
builder.append(entry.getKey() + ": " + entry.getValue()).append("\n");
}
return builder.toString();
}
public static class Shortcut {
public final String[] pathTypes;
public final String[] path;
public final FieldType type;
public Shortcut(String[] pathTypes, String[] path, FieldType type) {
this.pathTypes = pathTypes;
this.path = path;
this.type = type;
}
public String[] getPath() {
return path;
}
public String[] getPathTypes() {
return pathTypes;
}
public FieldType getType() {
return type;
}
public String toString() {
return Arrays.toString(path) + " (" + type.toString() + ")";
}
}
}
| 9,297 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIFactoryJavaGenerator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.codegen;
import com.netflix.hollow.api.client.HollowAPIFactory;
import com.netflix.hollow.api.custom.HollowAPI;
import com.netflix.hollow.api.objects.provider.HollowFactory;
import com.netflix.hollow.core.HollowDataset;
import com.netflix.hollow.core.read.dataaccess.HollowDataAccess;
import java.util.Collections;
import java.util.Set;
/**
* This class contains template logic for generating a {@link HollowAPIFactory} implementation. Not intended for external consumption.
*
* @see HollowAPIGenerator
*
*/
public class HollowAPIFactoryJavaGenerator extends HollowConsumerJavaFileGenerator {
public static final String SUB_PACKAGE_NAME = "core";
private final String apiClassname;
public HollowAPIFactoryJavaGenerator(String packageName, String apiClassname, HollowDataset dataset,
CodeGeneratorConfig config) {
super(packageName, SUB_PACKAGE_NAME, dataset, config);
this.apiClassname = apiClassname;
this.className = apiClassname + "Factory";
}
@Override
public String generate() {
StringBuilder builder = new StringBuilder();
appendPackageAndCommonImports(builder, apiClassname);
builder.append("import ").append(HollowAPIFactory.class.getName()).append(";\n");
builder.append("import ").append(HollowAPI.class.getName()).append(";\n");
builder.append("import ").append(HollowFactory.class.getName()).append(";\n");
builder.append("import ").append(HollowDataAccess.class.getName()).append(";\n");
builder.append("import ").append(Collections.class.getName()).append(";\n");
builder.append("import ").append(Set.class.getName()).append(";\n");
builder.append("\n@SuppressWarnings(\"all\")\n");
builder.append("public class ").append(className).append(" implements HollowAPIFactory {\n\n");
builder.append(" private final Set<String> cachedTypes;\n\n");
builder.append(" public ").append(className).append("() {\n");
builder.append(" this(Collections.<String>emptySet());\n");
builder.append(" }\n\n");
builder.append(" public ").append(className).append("(Set<String> cachedTypes) {\n");
builder.append(" this.cachedTypes = cachedTypes;\n");
builder.append(" }\n\n");
builder.append(" @Override\n");
builder.append(" public HollowAPI createAPI(HollowDataAccess dataAccess) {\n");
builder.append(" return new ").append(apiClassname).append("(dataAccess, cachedTypes);\n");
builder.append(" }\n\n");
builder.append(" @Override\n");
builder.append(" public HollowAPI createAPI(HollowDataAccess dataAccess, HollowAPI previousCycleAPI) {\n");
builder.append(" if (!(previousCycleAPI instanceof ").append(apiClassname).append(")) {\n");
builder.append(" throw new ClassCastException(previousCycleAPI.getClass() + \" not instance of ").append(apiClassname).append("\");");
builder.append(" }\n");
builder.append(" return new ").append(apiClassname).append("(dataAccess, cachedTypes, Collections.<String, HollowFactory<?>>emptyMap(), (").append(apiClassname).append(") previousCycleAPI);\n");
builder.append(" }\n\n");
builder.append("}");
return builder.toString();
}
}
| 9,298 |
0 | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api | Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/api/codegen/HollowAPIGenerator.java | /*
* Copyright 2016-2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.hollow.api.codegen;
import com.netflix.hollow.api.codegen.api.HollowDataAccessorGenerator;
import com.netflix.hollow.api.codegen.api.TypeAPIListJavaGenerator;
import com.netflix.hollow.api.codegen.api.TypeAPIMapJavaGenerator;
import com.netflix.hollow.api.codegen.api.TypeAPIObjectJavaGenerator;
import com.netflix.hollow.api.codegen.api.TypeAPISetJavaGenerator;
import com.netflix.hollow.api.codegen.delegate.HollowObjectDelegateCachedImplGenerator;
import com.netflix.hollow.api.codegen.delegate.HollowObjectDelegateInterfaceGenerator;
import com.netflix.hollow.api.codegen.delegate.HollowObjectDelegateLookupImplGenerator;
import com.netflix.hollow.api.codegen.indexes.HollowHashIndexGenerator;
import com.netflix.hollow.api.codegen.indexes.HollowPrimaryKeyIndexGenerator;
import com.netflix.hollow.api.codegen.indexes.HollowUniqueKeyIndexGenerator;
import com.netflix.hollow.api.codegen.indexes.LegacyHollowPrimaryKeyIndexGenerator;
import com.netflix.hollow.api.codegen.objects.HollowFactoryJavaGenerator;
import com.netflix.hollow.api.codegen.objects.HollowListJavaGenerator;
import com.netflix.hollow.api.codegen.objects.HollowMapJavaGenerator;
import com.netflix.hollow.api.codegen.objects.HollowObjectJavaGenerator;
import com.netflix.hollow.api.codegen.objects.HollowSetJavaGenerator;
import com.netflix.hollow.api.custom.HollowAPI;
import com.netflix.hollow.core.HollowDataset;
import com.netflix.hollow.core.schema.HollowListSchema;
import com.netflix.hollow.core.schema.HollowMapSchema;
import com.netflix.hollow.core.schema.HollowObjectSchema;
import com.netflix.hollow.core.schema.HollowSchema;
import com.netflix.hollow.core.schema.HollowSchema.SchemaType;
import com.netflix.hollow.core.schema.HollowSetSchema;
import com.netflix.hollow.core.util.HollowWriteStateCreator;
import com.netflix.hollow.core.write.HollowWriteStateEngine;
import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Set;
/**
* This class is used to generate java code which defines an implementation of a {@link HollowAPI}.
*
* The generated java code is based on a data model (defined by a set of {@link HollowSchema}), and will
* contain convenience methods for traversing a dataset, based on the specific fields in the data model.
*
* You may also run the main() method directly.
*/
public class HollowAPIGenerator {
/**
* An enumeration of possible arguments to the code generator when being called via the main
* function. Not expected to be used outside the library itself, except for documentation
* purposes.
* Unless otherwise noted, having repeated parameters results in the previous value being
* overwritten.
*/
public enum GeneratorArguments {
/**
* Add a class to the data model. Takes the fully qualified class name. This class must be
* available on the classpath. Having multiple of this parameter results in multiple classes
* being added to the data model.
*/
addToDataModel,
/**
* Add schema from a schema file to the data model. The schema file must be available on the
* classpath. Having multiple of this parameter results in multiple schemas being added to
* the data model.
*/
addSchemaFileToDataModel,
/**
* Sets the API class name.
*/
apiClassName,
/**
* Sets the class postfix for the generated types.
*/
classPostfix,
/**
* Sets the getter prefix to the provided string.
*/
getterPrefix,
/**
* Sets the package name for the generated files.
*/
packageName,
/**
* Sets the path the files with be generated in.
*/
pathToGeneratedFiles,
/**
* Parameterizes all methods that return a HollowObject.
*/
parameterizeAllClassNames;
}
protected final String apiClassname;
protected final String packageName;
protected final Path destinationPath;
protected final HollowDataset dataset;
protected final Set<String> parameterizedTypes;
protected final boolean parameterizeClassNames;
protected final boolean hasCollectionsInDataSet;
protected final HollowErgonomicAPIShortcuts ergonomicShortcuts;
protected CodeGeneratorConfig config = new CodeGeneratorConfig("Hollow", "_"); // NOTE: to be backwards compatible
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
*
* @deprecated use {@link #HollowAPIGenerator(String, String, HollowDataset, Path)} and use {@link #generateSourceFiles()}
*/
public HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset) {
this(apiClassname, packageName, dataset, Collections.<String>emptySet(), false, false);
}
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
* @param destinationPath the directory under which the source files will be generated
*/
public HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset, Path destinationPath) {
this(apiClassname, packageName, dataset, Collections.<String>emptySet(), false, false, destinationPath);
}
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
* @param parameterizeAllClassNames if true, all methods which return a Hollow Object will be parameterized. This is useful when
* alternate implementations are desired for some types.
*
* @deprecated use {@link #HollowAPIGenerator(String, String, HollowDataset, boolean, Path)} and use {@link #generateSourceFiles()}
*/
public HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset, boolean parameterizeAllClassNames) {
this(apiClassname, packageName, dataset, Collections.<String>emptySet(), parameterizeAllClassNames, false);
}
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
* @param parameterizeAllClassNames if true, all methods which return a Hollow Object will be parameterized. This is useful when
* alternate implementations are desired for some types.
* @param destinationPath the directory under which the source files will be generated
*/
public HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset, boolean parameterizeAllClassNames, Path destinationPath) {
this(apiClassname, packageName, dataset, Collections.<String>emptySet(), parameterizeAllClassNames, false, destinationPath);
}
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
* @param parameterizeSpecificTypeNames methods with matching names which return a Hollow Object will be parameterized. This is useful when
* alternate implementations are desired for some types.
*
* @deprecated use {@link #HollowAPIGenerator(String, String, HollowDataset, Set, Path)} and use {@link #generateSourceFiles()}
*/
public HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset, Set<String> parameterizeSpecificTypeNames) {
this(apiClassname, packageName, dataset, parameterizeSpecificTypeNames, false, false);
}
/**
* @param apiClassname the class name of the generated implementation of {@link HollowAPI}
* @param packageName the package name under which all generated classes will be placed
* @param dataset a HollowStateEngine containing the schemas which define the data model.
* @param parameterizedTypes the parameterized types
* @param destinationPath the directory under which the source files will be generated
*/
public HollowAPIGenerator(String apiClassname,
String packageName,
HollowDataset dataset,
Set<String> parameterizedTypes,
Path destinationPath) {
this(apiClassname, packageName, dataset, parameterizedTypes, false, false, destinationPath);
}
/**
* @param apiClassname the api class name
* @param packageName the api package name
* @param dataset the data set
* @param parameterizedTypes the set of parameterized types
* @param parameterizeAllClassNames true if class names should be parameterized
* @param useErgonomicShortcuts true if ergonomic shortcuts should be used
* @deprecated construct with a {@code destinationPath} and use {@link #generateSourceFiles()}
*/
protected HollowAPIGenerator(String apiClassname, String packageName, HollowDataset dataset, Set<String> parameterizedTypes, boolean parameterizeAllClassNames, boolean useErgonomicShortcuts) {
this(apiClassname, packageName, dataset, parameterizedTypes, parameterizeAllClassNames, useErgonomicShortcuts, null);
}
protected HollowAPIGenerator(String apiClassname,
String packageName,
HollowDataset dataset,
Set<String> parameterizedTypes,
boolean parameterizeAllClassNames,
boolean useErgonomicShortcuts,
Path destinationPath) {
this.apiClassname = apiClassname;
this.packageName = packageName;
this.dataset = dataset;
this.hasCollectionsInDataSet = hasCollectionsInDataSet(dataset);
this.parameterizedTypes = parameterizedTypes;
this.parameterizeClassNames = parameterizeAllClassNames;
this.ergonomicShortcuts = useErgonomicShortcuts ? new HollowErgonomicAPIShortcuts(dataset) : HollowErgonomicAPIShortcuts.NO_SHORTCUTS;
if (destinationPath != null && packageName != null && !packageName.trim().isEmpty()) {
Path packagePath = Paths.get(packageName.replace(".", File.separator));
if (!destinationPath.toAbsolutePath().endsWith(packagePath)) {
destinationPath = destinationPath.resolve(packagePath);
}
}
this.destinationPath = destinationPath;
}
/**
* Usage: java HollowAPIGenerator --argName1=argValue1 --argName2==argValue2. See {@link GeneratorArguments} for
* available arguments.
* @param args the arguments
* @throws IOException if a schema could not be read or the data model written
* @throws ClassNotFoundException if a class of a data model cannot be loaded
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
if (args.length == 0) {
System.out.println("Usage:\n"
+ "java " + HollowAPIGenerator.class.getName() + " --arg1=value1 --arg2=value2\n"
+ "see " + GeneratorArguments.class.getName() + " for available arguments.");
return;
}
HollowWriteStateEngine engine = new HollowWriteStateEngine();
HollowAPIGenerator.Builder builder = new HollowAPIGenerator.Builder();
HollowObjectMapper mapper = new HollowObjectMapper(engine);
ArgumentParser<GeneratorArguments> argumentParser = new ArgumentParser(GeneratorArguments.class, args);
for (ArgumentParser<GeneratorArguments>.ParsedArgument arg : argumentParser.getParsedArguments()) {
switch (arg.getKey()) {
case addToDataModel:
mapper.initializeTypeState(HollowAPIGenerator.class.getClassLoader().loadClass(arg.getValue()));
break;
case addSchemaFileToDataModel:
HollowWriteStateCreator.readSchemaFileIntoWriteState(arg.getValue(), engine);
break;
case apiClassName:
builder.withAPIClassname(arg.getValue());
break;
case classPostfix:
builder.withClassPostfix(arg.getValue());
break;
case getterPrefix:
builder.withGetterPrefix(arg.getValue());
break;
case packageName:
builder.withPackageName(arg.getValue());
break;
case pathToGeneratedFiles:
builder.withDestination(arg.getValue());
break;
case parameterizeAllClassNames:
builder.withParameterizeAllClassNames(Boolean.valueOf(arg.getValue()));
break;
default:
throw new IllegalArgumentException("Unhandled argument " + arg.getKey());
}
}
builder.withDataModel(engine).build().generateSourceFiles();
}
/**
* Determines whether DataSet contains any collections schema
* @param dataset the data set
* @return {@code true} if the data set contains any collections schema
*/
protected static boolean hasCollectionsInDataSet(HollowDataset dataset) {
for(HollowSchema schema : dataset.getSchemas()) {
if ((schema instanceof HollowListSchema) ||
(schema instanceof HollowSetSchema) ||
(schema instanceof HollowMapSchema)) {
return true;
}
}
return false;
}
/**
* Set the CodeGeneratorConfig
* @param config the configuration
*/
protected void setCodeGeneratorConfig(CodeGeneratorConfig config) {
this.config = config;
}
/**
* Use this method to override the default postfix "Hollow" for all generated Hollow object classes.
* @param classPostfix the postfix for all generated Hollow object classes
*/
public void setClassPostfix(String classPostfix) {
config.setClassPostfix(classPostfix);
}
/**
* Use this method to override the default prefix "_" for all getters on all generated Hollow object classes.
* @param getterPrefix the prefix for all generated getters
*/
public void setGetterPrefix(String getterPrefix) {
config.setGetterPrefix(getterPrefix);
}
/**
* Use this method to override generated classnames for type names corresponding to any class in the java.lang package.
*
* Defaults to false, which overrides only type names corresponding to a few select classes in java.lang.
*
* @param useAggressiveSubstitutions true if applied.
*/
public void setUseAggressiveSubstitutions(boolean useAggressiveSubstitutions) {
config.setUseAggressiveSubstitutions(useAggressiveSubstitutions);
}
/**
* Use this method to specify to use new boolean field ergonomics for generated API
*
* Defaults to false to be backwards compatible
*
* @param useBooleanFieldErgonomics true if applied.
*/
public void setUseBooleanFieldErgonomics(boolean useBooleanFieldErgonomics) {
config.setUseBooleanFieldErgonomics(useBooleanFieldErgonomics);
}
/**
* Use this method to specify to use sub packages in generated code instead of single package
*
* Defaults to false to be backwards compatible
*
* @param usePackageGrouping true if applied.
*/
public void setUsePackageGrouping(boolean usePackageGrouping) {
config.setUsePackageGrouping(usePackageGrouping );
}
/**
* Use this method to specify to only generate PrimaryKeyIndex for Types that has PrimaryKey defined
*
* Defaults to false to be backwards compatible
*
* @param reservePrimaryKeyIndexForTypeWithPrimaryKey true if applied.
*/
public void reservePrimaryKeyIndexForTypeWithPrimaryKey(boolean reservePrimaryKeyIndexForTypeWithPrimaryKey) {
config.setReservePrimaryKeyIndexForTypeWithPrimaryKey(reservePrimaryKeyIndexForTypeWithPrimaryKey);
}
/**
* Use this method to specify to use Hollow Primitive Types instead of generating them per project
*
* Defaults to false to be backwards compatible
*
* @param useHollowPrimitiveTypes true if applied.
*/
public void setUseHollowPrimitiveTypes(boolean useHollowPrimitiveTypes) {
config.setUseHollowPrimitiveTypes(useHollowPrimitiveTypes);
}
/**
* If setRestrictApiToFieldType is true, api code only generates {@code get<FieldName>} with return type as per schema
*
* Defaults to false to be backwards compatible
*
* @param restrictApiToFieldType true if applied.
*/
public void setRestrictApiToFieldType(boolean restrictApiToFieldType) {
config.setRestrictApiToFieldType(restrictApiToFieldType);
}
/**
* Generate all files under {@code destinationPath}
*
* @throws IOException if the files cannot be generated
*/
public void generateSourceFiles() throws IOException {
generateFiles(destinationPath.toFile());
}
/**
* Generate files under the specified directory
*
* @param directory the directory under which to generate files
* @throws IOException if the files cannot be generated
* @deprecated construct {@code HollowAPIGenerator} with a {@code destinationPath} then call {@link #generateSourceFiles()}
*/
public void generateFiles(String directory) throws IOException {
generateFiles(new File(directory));
}
/**
* Generate files under the specified directory
*
* @param directory the directory under which to generate files
* @throws IOException if the files cannot be generated
* @deprecated construct {@code HollowAPIGenerator} with a {@code destinationPath} then call {@link #generateSourceFiles()}
*/
public void generateFiles(File directory) throws IOException {
if (packageName != null && !packageName.trim().isEmpty()) {
String packageDir = packageName.replace(".", File.separator);
if (!directory.getAbsolutePath().endsWith(packageDir)) {
directory = new File(directory, packageDir);
}
}
directory.mkdirs();
HollowAPIClassJavaGenerator apiClassGenerator = new HollowAPIClassJavaGenerator(packageName, apiClassname,
dataset, parameterizeClassNames, config);
HollowAPIFactoryJavaGenerator apiFactoryGenerator = new HollowAPIFactoryJavaGenerator(packageName,
apiClassname, dataset, config);
HollowHashIndexGenerator hashIndexGenerator = new HollowHashIndexGenerator(packageName, apiClassname, dataset, config);
generateFile(directory, apiClassGenerator);
generateFile(directory, apiFactoryGenerator);
generateFile(directory, hashIndexGenerator);
generateFilesForHollowSchemas(directory);
}
/**
* Generate files based on dataset schemas under {@code destinationPath}
*
* @throws IOException if the files cannot be generated
*/
protected void generateSourceFilesForHollowSchemas() throws IOException {
this.generateFilesForHollowSchemas(destinationPath.toFile());
}
/**
* Generate files based on dataset schemas under the specified directory
*
* @param directory the directory under which to generate files
* @throws IOException if the files cannot be generated
* @deprecated construct {@code HollowAPIGenerator} with a {@code destinationPath} then call {@link #generateSourceFilesForHollowSchemas()}
*/
protected void generateFilesForHollowSchemas(File directory) throws IOException {
for(HollowSchema schema : dataset.getSchemas()) {
String type = schema.getName();
if (config.isUseHollowPrimitiveTypes() && HollowCodeGenerationUtils.isPrimitiveType(type)) continue; // skip if using hollow primitive type
generateFile(directory, getStaticAPIGenerator(schema));
generateFile(directory, getHollowObjectGenerator(schema));
generateFile(directory, getHollowFactoryGenerator(schema));
if(schema.getSchemaType() == SchemaType.OBJECT) {
HollowObjectSchema objSchema = (HollowObjectSchema)schema;
generateFile(directory, new HollowObjectDelegateInterfaceGenerator(packageName, objSchema,
ergonomicShortcuts, dataset, config));
generateFile(directory, new HollowObjectDelegateCachedImplGenerator(packageName, objSchema,
ergonomicShortcuts, dataset, config));
generateFile(directory, new HollowObjectDelegateLookupImplGenerator(packageName, objSchema,
ergonomicShortcuts, dataset, config));
generateFile(directory, new HollowDataAccessorGenerator(packageName, apiClassname, objSchema,
dataset, config));
if (!config.isReservePrimaryKeyIndexForTypeWithPrimaryKey()) {
generateFile(directory, new LegacyHollowPrimaryKeyIndexGenerator(packageName, apiClassname,
objSchema, dataset, config));
} else if ((objSchema).getPrimaryKey() != null) {
generateFile(directory, new HollowPrimaryKeyIndexGenerator(dataset, packageName, apiClassname,
objSchema, config));
generateFile(directory, new HollowUniqueKeyIndexGenerator(packageName, apiClassname, objSchema,
dataset, config));
}
}
}
}
protected void generateSourceFile(HollowJavaFileGenerator generator) throws IOException {
this.generateFile(destinationPath.toFile(), generator);
}
/**
* @param directory the directory under which to generate a file
* @param generator the file generator
* @throws IOException if the file cannot be generated
* @deprecated construct {@code HollowAPIGenerator} with a {@code destinationPath} then call {@link #generateSourceFile(HollowJavaFileGenerator)}
*/
protected void generateFile(File directory, HollowJavaFileGenerator generator) throws IOException {
// create sub folder if not using default package and sub packages are enabled
if ((packageName!=null && !packageName.trim().isEmpty()) && config.isUsePackageGrouping() && (generator instanceof HollowConsumerJavaFileGenerator)) {
HollowConsumerJavaFileGenerator consumerCodeGenerator = (HollowConsumerJavaFileGenerator)generator;
if (hasCollectionsInDataSet) consumerCodeGenerator.useCollectionsImport();
directory = new File(directory, consumerCodeGenerator.getSubPackageName());
}
if (!directory.exists()) directory.mkdirs();
FileWriter writer = new FileWriter(new File(directory, generator.getClassName() + ".java"));
writer.write(generator.generate());
writer.close();
}
protected HollowJavaFileGenerator getStaticAPIGenerator(HollowSchema schema) {
if(schema instanceof HollowObjectSchema) {
return new TypeAPIObjectJavaGenerator(apiClassname, packageName, (HollowObjectSchema) schema, dataset, config);
} else if(schema instanceof HollowListSchema) {
return new TypeAPIListJavaGenerator(apiClassname, packageName, (HollowListSchema)schema, dataset, config);
} else if(schema instanceof HollowSetSchema) {
return new TypeAPISetJavaGenerator(apiClassname, packageName, (HollowSetSchema)schema, dataset, config);
} else if(schema instanceof HollowMapSchema) {
return new TypeAPIMapJavaGenerator(apiClassname, packageName, (HollowMapSchema)schema, dataset, config);
}
throw new UnsupportedOperationException("What kind of schema is a " + schema.getClass().getName() + "?");
}
protected HollowJavaFileGenerator getHollowObjectGenerator(HollowSchema schema) {
if(schema instanceof HollowObjectSchema) {
return new HollowObjectJavaGenerator(packageName, apiClassname, (HollowObjectSchema) schema,
parameterizedTypes, parameterizeClassNames, ergonomicShortcuts, dataset, config);
} else if(schema instanceof HollowListSchema) {
return new HollowListJavaGenerator(packageName, apiClassname, (HollowListSchema) schema,
parameterizedTypes, parameterizeClassNames, dataset, config);
} else if(schema instanceof HollowSetSchema) {
return new HollowSetJavaGenerator(packageName, apiClassname, (HollowSetSchema) schema,
parameterizedTypes, parameterizeClassNames, dataset, config);
} else if(schema instanceof HollowMapSchema) {
return new HollowMapJavaGenerator(packageName, apiClassname, (HollowMapSchema) schema, dataset, parameterizedTypes, parameterizeClassNames, config);
}
throw new UnsupportedOperationException("What kind of schema is a " + schema.getClass().getName() + "?");
}
protected HollowFactoryJavaGenerator getHollowFactoryGenerator(HollowSchema schema) {
return new HollowFactoryJavaGenerator(packageName, schema, dataset, config);
}
public static class Builder extends AbstractHollowAPIGeneratorBuilder<Builder, HollowAPIGenerator> {
@Override
protected HollowAPIGenerator instantiateGenerator() {
return new HollowAPIGenerator(apiClassname, packageName, dataset, parameterizedTypes, parameterizeAllClassNames, useErgonomicShortcuts, destinationPath);
}
@Override
protected Builder getBuilder() {
return this;
}
}
}
| 9,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.