index
int64 0
990
| proj_name
stringclasses 162
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
|
---|---|---|---|---|---|---|---|---|---|
201 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/query/MapAbsent.java | MapAbsent | doInsert | class MapAbsent<K, V> implements Absent<K, V> {
@StageRef
public KeySearch<K> ks;
@StageRef
public HashLookupSearch hashLookupSearch;
@StageRef
public CheckOnEachPublicOperation checkOnEachPublicOperation;
@StageRef
public SegmentStages s;
@StageRef
MapQuery<K, V, ?> q;
@StageRef
MapEntryStages<K, V> e;
@StageRef
VanillaChronicleMapHolder<K, V, ?> mh;
void putEntry(Data<V> value) {
assert ks.searchStateAbsent();
long entrySize = e.entrySize(ks.inputKey.size(), value.size());
q.allocatedChunks.initEntryAndKey(entrySize);
e.initValue(value);
e.freeExtraAllocatedChunks();
hashLookupSearch.putNewVolatile(e.pos);
}
@NotNull
@Override
public MapQuery<K, V, ?> context() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return q;
}
@NotNull
@Override
public Data<K> absentKey() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return ks.inputKey;
}
@Override
public void doInsert(Data<V> value) {<FILL_FUNCTION_BODY>}
@Override
public void doInsert() {
if (mh.set() == null)
throw new IllegalStateException(mh.h().toIdentityString() +
": Called SetAbsentEntry.doInsert() from Map context");
//noinspection unchecked
doInsert((Data<V>) DummyValueData.INSTANCE);
}
} |
q.putPrefix();
if (!q.entryPresent()) {
putEntry(value);
s.incrementModCount();
ks.setSearchState(PRESENT);
q.initPresenceOfEntry(EntryPresence.PRESENT);
} else {
throw new IllegalStateException(mh.h().toIdentityString() +
": Entry is present in the map when doInsert() is called");
}
| 471 | 110 | 581 |
202 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/query/MapQuery.java | MapQuery | doReplaceValue | class MapQuery<K, V, R> extends HashQuery<K>
implements MapEntry<K, V>, ExternalMapQueryContext<K, V, R>,
ExternalSetQueryContext<K, R>, QueryContextInterface<K, V, R>, MapAndSetContext<K, V, R> {
@StageRef
public AcquireHandle<K, V> acquireHandle;
@StageRef
public DefaultReturnValue<V> defaultReturnValue;
@StageRef
public UsingReturnValue<V> usingReturnValue;
@StageRef
public MapAbsent<K, V> absent;
@StageRef
VanillaChronicleMapHolder<K, V, R> mh;
final DataAccess<V> innerInputValueDataAccess = mh.m().valueDataAccess.copy();
@StageRef
MapEntryStages<K, V> e;
@StageRef
SearchAllocatedChunks allocatedChunks;
@StageRef
KeySearch<K> ks;
@StageRef
InputKeyBytesData<K> inputKeyBytesData;
@Stage("InputValueDataAccess")
private boolean inputValueDataAccessInitialized = false;
void initInputValueDataAccess() {
inputValueDataAccessInitialized = true;
}
void closeInputValueDataAccess() {
innerInputValueDataAccess.uninit();
inputValueDataAccessInitialized = false;
}
@Override
public DataAccess<V> inputValueDataAccess() {
initInputValueDataAccess();
return innerInputValueDataAccess;
}
@Override
public MapQuery<K, V, R> entry() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return entryPresent() ? this : null;
}
@Nullable
@Override
public Absent<K, V> absentEntry() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return entryPresent() ? null : absent;
}
protected void putPrefix() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
if (!s.innerUpdateLock.isHeldByCurrentThread())
s.innerUpdateLock.lock();
if (s.nestedContextsLockedOnSameSegment &&
s.rootContextLockedOnThisSegment.latestSameThreadSegmentModCount() !=
s.contextModCount) {
if (hlp.hashLookupPosInit() && ks.searchStateAbsent())
hlp.closeHashLookupPos();
}
}
@Override
public void doReplaceValue(Data<V> newValue) {<FILL_FUNCTION_BODY>}
@NotNull
@Override
public MapQuery<K, V, R> context() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return this;
}
@Override
public Data<K> getInputKeyBytesAsData(BytesStore bytesStore, long offset, long size) {
inputKeyBytesData.initInputKeyBytesStore(bytesStore, offset, size);
return inputKeyBytesData;
}
} |
putPrefix();
if (entryPresent()) {
e.innerDefaultReplaceValue(newValue);
s.incrementModCount();
ks.setSearchState(PRESENT);
initPresenceOfEntry(EntryPresence.PRESENT);
} else {
throw new IllegalStateException(mh.h().toIdentityString() +
": Entry is absent in the map when doReplaceValue() is called");
}
| 778 | 110 | 888 |
203 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/query/ReplicatedMapAbsent.java | ReplicatedMapAbsent | doInsert | class ReplicatedMapAbsent<K, V> extends MapAbsent<K, V> {
@StageRef
MapQuery<K, V, ?> q;
@StageRef
ReplicatedMapEntryStages<K, V> e;
@StageRef
ReplicationUpdate<K> ru;
@NotNull
@Override
public Data<K> absentKey() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return e.entryKey;
}
@Override
public void doInsert(Data<V> value) {<FILL_FUNCTION_BODY>}
} |
q.putPrefix();
if (!q.entryPresent()) {
if (!ks.searchStatePresent()) {
putEntry(value);
e.updatedReplicationStateOnAbsentEntry();
ks.setSearchState(PRESENT);
q.initPresenceOfEntry(EntryPresence.PRESENT);
} else {
s.tierDeleted(s.tierDeleted() - 1);
e.innerDefaultReplaceValue(value);
e.updatedReplicationStateOnPresentEntry();
}
s.incrementModCount();
e.writeEntryPresent();
ru.updateChange();
} else {
throw new IllegalStateException(mh.h().toIdentityString() +
": Entry is present in the map when doInsert() is called");
}
| 159 | 200 | 359 |
204 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/query/ReplicatedMapQuery.java | ReplicatedMapQuery | absentEntry | class ReplicatedMapQuery<K, V, R> extends MapQuery<K, V, R>
implements MapRemoteQueryContext<K, V, R>, SetRemoteQueryContext<K, R>,
ReplicableEntry, MapReplicableEntry<K, V>, SetReplicableEntry<K> {
@StageRef
ReplicatedMapEntryStages<K, V> e;
@StageRef
ReplicationUpdate ru;
@StageRef
ReplicatedMapAbsentDelegating<K, V> absentDelegating;
@StageRef
DummyValueZeroData<V> dummyValue;
@Nullable
@Override
public Absent<K, V> absentEntry() {<FILL_FUNCTION_BODY>}
@Override
public boolean entryPresent() {
return super.entryPresent() && !e.entryDeleted();
}
@Override
public ReplicatedMapQuery<K, V, R> entry() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return entryPresent() ? this : null;
}
@Override
public void doRemove() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
s.innerUpdateLock.lock();
if (entryPresent()) {
if (e.valueSize > dummyValue.size())
e.innerDefaultReplaceValue(dummyValue);
e.updatedReplicationStateOnPresentEntry();
e.writeEntryDeleted();
ru.updateChange();
s.tierDeleted(s.tierDeleted() + 1);
} else {
throw new IllegalStateException(mh.h().toIdentityString() +
": Entry is absent in the map when doRemove() is called");
}
}
@Override
public void doRemoveCompletely() {
boolean wasDeleted = e.entryDeleted();
super.doRemove();
ru.dropChange();
if (wasDeleted)
s.tierDeleted(s.tierDeleted() - 1L);
}
@Override
public void doReplaceValue(Data<V> newValue) {
super.doReplaceValue(newValue);
e.updatedReplicationStateOnPresentEntry();
ru.updateChange();
}
} |
checkOnEachPublicOperation.checkOnEachPublicOperation();
if (entryPresent()) {
return null;
} else {
if (!ks.searchStatePresent()) {
return absentDelegating;
} else {
assert e.entryDeleted();
return absent;
}
}
| 575 | 79 | 654 |
205 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/replication/ReplicatedQueryAlloc.java | ReplicatedQueryAlloc | alloc | class ReplicatedQueryAlloc extends QueryAlloc {
final CleanupAction cleanupAction = new CleanupAction();
@StageRef
ReplicatedChronicleMapHolder<?, ?, ?> mh;
@StageRef
SegmentStages s;
/**
* Returns {@code true} if at least one old deleted entry was removed.
*
* @param prevPos position to skip during cleanup (because cleaned up separately)
*/
public boolean forcedOldDeletedEntriesCleanup(long prevPos) {
ReplicatedChronicleMap<?, ?, ?> map = mh.m();
if (!map.cleanupRemovedEntries)
return false;
try (MapSegmentContext<?, ?, ?> sc = map.segmentContext(s.segmentIndex)) {
cleanupAction.removedCompletely = 0;
cleanupAction.posToSkip = prevPos;
cleanupAction.iterationContext = (IterationContext<?, ?, ?>) sc;
((ReplicatedHashSegmentContext<?, ?>) sc)
.forEachSegmentReplicableEntry(cleanupAction);
return cleanupAction.removedCompletely > 0;
}
}
@Override
public long alloc(int chunks, long prevPos, int prevChunks) {<FILL_FUNCTION_BODY>}
private class CleanupAction implements Consumer<ReplicableEntry> {
int removedCompletely;
long posToSkip;
IterationContext<?, ?, ?> iterationContext;
@Override
public void accept(ReplicableEntry e) {
ReplicatedChronicleMap<?, ?, ?> map = mh.m();
if (!(e instanceof MapAbsentEntry) || iterationContext.pos() == posToSkip)
return;
long currentTime = currentTime();
if (e.originTimestamp() > currentTime)
return; // presumably unsynchronized clocks
long deleteTimeout = systemTimeIntervalBetween(
e.originTimestamp(), currentTime, map.cleanupTimeoutUnit);
if (deleteTimeout <= map.cleanupTimeout || e.isChanged())
return;
e.doRemoveCompletely();
removedCompletely++;
}
}
} |
long ret = s.allocReturnCode(chunks);
if (ret >= 0) {
if (prevPos >= 0)
s.free(prevPos, prevChunks);
return ret;
}
int firstAttemptedTier = s.tier;
long firstAttemptedTierIndex = s.tierIndex;
long firstAttemptedTierBaseAddr = s.tierBaseAddr;
boolean cleanedFirstAttemptedTier = forcedOldDeletedEntriesCleanup(prevPos);
if (cleanedFirstAttemptedTier) {
// Force recalculation of some properties as new slots may
// have become available and there might be "holes"
// created by removed entries.
((CompiledReplicatedMapQueryContext) (Object) this).closeSearchKey();
}
s.goToFirstTier();
while (true) {
boolean visitingFirstAttemptedTier = s.tier == firstAttemptedTier;
if (cleanedFirstAttemptedTier || !visitingFirstAttemptedTier) {
ret = s.allocReturnCode(chunks);
if (ret >= 0) {
if (prevPos >= 0) {
if (visitingFirstAttemptedTier) {
s.free(prevPos, prevChunks);
} else if (s.tier < firstAttemptedTier) {
int currentTier = s.tier;
long currentTierIndex = s.tierIndex;
long currentTierBaseAddr = s.tierBaseAddr;
s.initSegmentTier(firstAttemptedTier, firstAttemptedTierIndex,
firstAttemptedTierBaseAddr);
s.free(prevPos, prevChunks);
s.initSegmentTier(currentTier, currentTierIndex, currentTierBaseAddr);
}
}
return ret;
}
}
if (visitingFirstAttemptedTier && prevPos >= 0)
s.free(prevPos, prevChunks);
s.nextTier();
}
| 562 | 522 | 1,084 |
206 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/replication/ReplicationUpdate.java | ReplicationUpdate | initReplicationUpdate | class ReplicationUpdate<K> implements RemoteOperationContext<K> {
@Stage("ReplicationUpdate")
public byte innerRemoteIdentifier = (byte) 0;
@Stage("ReplicationUpdate")
public long innerRemoteTimestamp;
@Stage("ReplicationUpdate")
public byte innerRemoteNodeIdentifier;
@StageRef
SegmentStages s;
@StageRef
ReplicatedMapEntryStages<K, ?> e;
@StageRef
ReplicatedChronicleMapHolder<?, ?, ?> mh;
@StageRef
CheckOnEachPublicOperation checkOnEachPublicOperation;
public abstract boolean replicationUpdateInit();
public void initReplicationUpdate(byte identifier, long timestamp, byte remoteNodeIdentifier) {<FILL_FUNCTION_BODY>}
public void dropChange() {
mh.m().dropChange(s.tierIndex, e.pos);
}
public void dropChangeFor(byte remoteIdentifier) {
mh.m().dropChangeFor(s.tierIndex, e.pos, remoteIdentifier);
}
public void moveChange(long oldTierIndex, long oldPos, long newPos) {
mh.m().moveChange(oldTierIndex, oldPos, s.tierIndex, newPos);
}
public void updateChange() {
if (!replicationUpdateInit()) {
raiseChange();
}
}
public void raiseChange() {
mh.m().raiseChange(s.tierIndex, e.pos);
}
public void raiseChangeFor(byte remoteIdentifier) {
mh.m().raiseChangeFor(s.tierIndex, e.pos, remoteIdentifier);
}
public void raiseChangeForAllExcept(byte remoteIdentifier) {
mh.m().raiseChangeForAllExcept(s.tierIndex, e.pos, remoteIdentifier);
}
public boolean changed() {
return mh.m().isChanged(s.tierIndex, e.pos);
}
@Override
public long remoteTimestamp() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return innerRemoteTimestamp;
}
@Override
public byte remoteIdentifier() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return innerRemoteIdentifier;
}
@Override
public byte remoteNodeIdentifier() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return innerRemoteNodeIdentifier;
}
@Override
public byte currentNodeIdentifier() {
return mh.m().identifier();
}
} |
innerRemoteTimestamp = timestamp;
if (identifier == 0)
throw new IllegalStateException(mh.h().toIdentityString() + ": identifier can't be 0");
innerRemoteIdentifier = identifier;
if (remoteNodeIdentifier == 0) {
throw new IllegalStateException(
mh.h().toIdentityString() + ": remote node identifier can't be 0");
}
innerRemoteNodeIdentifier = remoteNodeIdentifier;
| 651 | 112 | 763 |
207 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/ret/DefaultReturnValue.java | DefaultReturnValue | returnValue | class DefaultReturnValue<V> implements InstanceReturnValue<V> {
private V defaultReturnedValue = null;
abstract boolean defaultReturnedValueInit();
private void initDefaultReturnedValue(@NotNull Data<V> value) {
defaultReturnedValue = value.getUsing(null);
}
@Override
public void returnValue(@NotNull Data<V> value) {
initDefaultReturnedValue(value);
}
@Override
public V returnValue() {<FILL_FUNCTION_BODY>}
} |
if (defaultReturnedValueInit()) {
return defaultReturnedValue;
} else {
return null;
}
| 135 | 35 | 170 |
208 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/impl/stage/ret/UsingReturnValue.java | UsingReturnValue | returnValue | class UsingReturnValue<V> implements UsableReturnValue<V> {
private V usingReturnValue = (V) USING_RETURN_VALUE_UNINIT;
private V returnedValue = null;
@Override
public void initUsingReturnValue(V usingReturnValue) {
this.usingReturnValue = usingReturnValue;
}
abstract boolean returnedValueInit();
private void initReturnedValue(@NotNull Data<V> value) {
returnedValue = value.getUsing(usingReturnValue);
}
@Override
public void returnValue(@NotNull Data<V> value) {
initReturnedValue(value);
}
@Override
public V returnValue() {<FILL_FUNCTION_BODY>}
} |
if (returnedValueInit()) {
return returnedValue;
} else {
return null;
}
| 188 | 32 | 220 |
209 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/map/internal/InternalAssertUtil.java | InternalAssertUtil | assertAddress | class InternalAssertUtil {
private static final boolean IS_64_BIT = Jvm.is64bit();
// Suppresses default constructor, ensuring non-instantiability.
private InternalAssertUtil() {
}
public static boolean assertAddress(final long address) {<FILL_FUNCTION_BODY>}
public static boolean assertPosition(final long position) {
assert position >= 0 : "position is negative: " + position;
return true;
}
} |
if (Jvm.is64bit()) {
// It is highly unlikely that we would ever address farther than 2^63
assert address > 0 : "address is non positive: " + address;
} else {
// These memory addresses are illegal on a 32-bit machine
assert address != 0 && address != -1 : "address is illegal: " + address;
}
return true;
| 123 | 104 | 227 |
210 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilderPrivateAPI.java | ChronicleSetBuilderPrivateAPI | remoteOperations | class ChronicleSetBuilderPrivateAPI<K>
implements ChronicleHashBuilderPrivateAPI<K, SetRemoteOperations<K, ?>> {
private final ChronicleHashBuilderPrivateAPI<K, MapRemoteOperations<K, DummyValue, ?>> mapB;
public ChronicleSetBuilderPrivateAPI(
ChronicleHashBuilderPrivateAPI<K, MapRemoteOperations<K, DummyValue, ?>> mapB) {
this.mapB = mapB;
}
@Override
public String name() {
return mapB.name();
}
@Override
public SerializationBuilder<K> keyBuilder() {
return mapB.keyBuilder();
}
@Override
public int segmentEntrySpaceInnerOffset() {
return mapB.segmentEntrySpaceInnerOffset();
}
@Override
public long chunkSize() {
return mapB.chunkSize();
}
@Override
public int maxChunksPerEntry() {
return mapB.maxChunksPerEntry();
}
@Override
public long entriesPerSegment() {
return mapB.entriesPerSegment();
}
@Override
public long tierHashLookupCapacity() {
return mapB.tierHashLookupCapacity();
}
@Override
public long actualChunksPerSegmentTier() {
return mapB.actualChunksPerSegmentTier();
}
@Override
public int segmentHeaderSize() {
return mapB.segmentHeaderSize();
}
@Override
public int actualSegments() {
return mapB.actualSegments();
}
@Override
public long maxExtraTiers() {
return mapB.maxExtraTiers();
}
@Override
public boolean aligned64BitMemoryOperationsAtomic() {
return mapB.aligned64BitMemoryOperationsAtomic();
}
@Override
public boolean checksumEntries() {
return mapB.checksumEntries();
}
@Override
public void replication(byte identifier) {
mapB.replication(identifier);
}
@Override
public void cleanupRemovedEntries(boolean cleanupRemovedEntries) {
mapB.cleanupRemovedEntries(cleanupRemovedEntries);
}
@Override
public void removedEntryCleanupTimeout(long removedEntryCleanupTimeout, TimeUnit unit) {
mapB.removedEntryCleanupTimeout(removedEntryCleanupTimeout, unit);
}
@Override
public void remoteOperations(SetRemoteOperations<K, ?> remoteOperations) {<FILL_FUNCTION_BODY>}
@Override
public Runnable getPreShutdownAction() {
return mapB.getPreShutdownAction();
}
@Override
public boolean skipCloseOnExitHook() {
return mapB.skipCloseOnExitHook();
}
@Override
public boolean sparseFile() {
return mapB.sparseFile();
}
} |
mapB.remoteOperations(new MapRemoteOperations<K, DummyValue, Object>() {
@Override
public void remove(MapRemoteQueryContext<K, DummyValue, Object> q) {
//noinspection unchecked
remoteOperations.remove((SetRemoteQueryContext) q);
}
@Override
public void put(
MapRemoteQueryContext<K, DummyValue, Object> q, Data<DummyValue> newValue) {
//noinspection unchecked
remoteOperations.put((SetRemoteQueryContext) q);
}
});
| 765 | 147 | 912 |
211 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/set/SetFromMap.java | SetFromMap | toIdentityString | class SetFromMap<E> extends AbstractSet<E> implements ChronicleSet<E> {
private final ChronicleMap<E, DummyValue> m; // The backing map
private transient Set<E> s; // Its keySet
SetFromMap(VanillaChronicleMap<E, DummyValue, ?> map) {
m = map;
map.chronicleSet = this;
s = map.keySet();
}
public void clear() {
throwExceptionIfClosed();
m.clear();
}
public int size() {
throwExceptionIfClosed();
return m.size();
}
public boolean isEmpty() {
throwExceptionIfClosed();
return m.isEmpty();
}
public boolean contains(Object o) {
throwExceptionIfClosed();
return m.containsKey(o);
}
public boolean remove(Object o) {
throwExceptionIfClosed();
return m.remove(o, DUMMY_VALUE);
}
public boolean add(E e) {
throwExceptionIfClosed();
return m.putIfAbsent(e, DUMMY_VALUE) == null;
}
@NotNull
public Iterator<E> iterator() {
throwExceptionIfClosed();
return s.iterator();
}
public Object[] toArray() {
throwExceptionIfClosed();
return s.toArray();
}
public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
public String toString() {
return s.toString();
}
@NotNull
@Override
public String toIdentityString() {<FILL_FUNCTION_BODY>}
public int hashCode() {
throwExceptionIfClosed();
return s.hashCode();
}
public boolean equals(Object o) {
throwExceptionIfClosed();
return o == this || s.equals(o);
}
public boolean containsAll(@NotNull Collection<?> c) {
throwExceptionIfClosed();
return s.containsAll(c);
}
public boolean removeAll(@NotNull Collection<?> c) {
throwExceptionIfClosed();
return s.removeAll(c);
}
public boolean retainAll(@NotNull Collection<?> c) {
throwExceptionIfClosed();
return s.retainAll(c);
}
// addAll is the only inherited implementation
@Override
public long longSize() {
throwExceptionIfClosed();
return m.longSize();
}
@Override
public long offHeapMemoryUsed() {
throwExceptionIfClosed();
return m.offHeapMemoryUsed();
}
@Override
public Class<E> keyClass() {
throwExceptionIfClosed();
return m.keyClass();
}
@Override
public Type keyType() {
throwExceptionIfClosed();
return m.keyType();
}
// TODO test queryContext methods
@NotNull
@Override
public ExternalSetQueryContext<E, ?> queryContext(E key) {
//noinspection unchecked
return (ExternalSetQueryContext<E, ?>) m.queryContext(key);
}
@NotNull
@Override
public ExternalSetQueryContext<E, ?> queryContext(Data<E> key) {
//noinspection unchecked
return (ExternalSetQueryContext<E, ?>) m.queryContext(key);
}
@NotNull
@Override
public ExternalSetQueryContext<E, ?> queryContext(BytesStore keyBytes, long offset, long size) {
//noinspection unchecked
return (ExternalSetQueryContext<E, ?>) m.queryContext(keyBytes, offset, size);
}
@Override
public SetSegmentContext<E, ?> segmentContext(int segmentIndex) {
// TODO
throw new UnsupportedOperationException();
}
@Override
public int segments() {
throwExceptionIfClosed();
return m.segments();
}
// TODO test forEach methods
@Override
public boolean forEachEntryWhile(Predicate<? super SetEntry<E>> predicate) {
throwExceptionIfClosed();
Objects.requireNonNull(predicate);
return m.forEachEntryWhile(e -> predicate.test(((SetEntry<E>) e)));
}
@Override
public void forEachEntry(Consumer<? super SetEntry<E>> action) {
throwExceptionIfClosed();
Objects.requireNonNull(action);
m.forEachEntry(e -> action.accept(((SetEntry<E>) e)));
}
@Override
public File file() {
throwExceptionIfClosed();
return m.file();
}
@Override
public String name() {
throwExceptionIfClosed();
return m.name();
}
@Override
public void close() {
m.close();
}
@Override
public boolean isOpen() {
throwExceptionIfClosed();
return m.isOpen();
}
} |
throwExceptionIfClosed();
return "ChronicleSet{" +
"name=" + name() +
", file=" + file() +
", identityHashCode=" + System.identityHashCode(this) +
"}";
| 1,340 | 65 | 1,405 |
212 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/xstream/converters/AbstractChronicleMapConverter.java | AbstractChronicleMapConverter | unmarshal | class AbstractChronicleMapConverter<K, V> implements Converter {
private final Map<K, V> map;
private final Class mapClazz;
AbstractChronicleMapConverter(@NotNull Map<K, V> map) {
this.map = map;
this.mapClazz = map.getClass();
}
private static <E> E deserialize(@NotNull UnmarshallingContext unmarshallingContext,
@NotNull HierarchicalStreamReader reader) {
switch (reader.getNodeName()) {
case "java.util.Collections$EmptySet":
return (E) Collections.emptySet();
case "java.util.Collections$EmptyList":
return (E) Collections.emptyList();
case "java.util.Collections$EmptyMap":
case "java.util.Collections.EmptyMap":
return (E) Collections.emptyMap();
}
return (E) unmarshallingContext.convertAnother(null, forName(reader.getNodeName()));
}
private static Class forName(String clazz) {
try {
return Class.forName(clazz);
} catch (ClassNotFoundException e) {
boolean isNative = clazz.endsWith($$NATIVE);
boolean isHeap = clazz.endsWith($$HEAP);
if (!isNative && !isHeap)
throw new ConversionException("class=" + clazz, e);
final String nativeInterface = isNative ?
clazz.substring(0, clazz.length() - $$NATIVE.length()) :
clazz.substring(0, clazz.length() - $$HEAP.length());
try {
Values.newNativeReference(Class.forName(clazz));
return Class.forName(nativeInterface);
} catch (Exception e1) {
throw new ConversionException("class=" + clazz, e1);
}
}
}
@Override
public boolean canConvert(Class aClass) {
//noinspection unchecked
return mapClazz.isAssignableFrom(aClass);
}
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext
marshallingContext) {
for (Map.Entry e : (Iterable<Map.Entry>) ((Map) o).entrySet()) {
writer.startNode("entry");
{
final Object key = e.getKey();
writer.startNode(key.getClass().getName());
marshallingContext.convertAnother(key);
writer.endNode();
Object value = e.getValue();
writer.startNode(value.getClass().getName());
marshallingContext.convertAnother(value);
writer.endNode();
}
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {<FILL_FUNCTION_BODY>}
} |
// empty map
if ("[\"\"]".equals(reader.getValue()))
return null;
if (!"cmap".equals(reader.getNodeName()))
throw new ConversionException("should be under 'cmap' node");
reader.moveDown();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String nodeName0 = reader.getNodeName();
if (!nodeName0.equals("entry"))
throw new ConversionException("unable to convert node named=" + nodeName0);
final K k;
final V v;
reader.moveDown();
k = deserialize(context, reader);
reader.moveUp();
reader.moveDown();
v = deserialize(context, reader);
reader.moveUp();
if (k != null)
map.put(k, v);
reader.moveUp();
}
reader.moveUp();
return null;
| 754 | 245 | 999 |
213 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/xstream/converters/ByteBufferConverter.java | ByteBufferConverter | unmarshal | class ByteBufferConverter implements Converter {
private final Charset charset = Charset.forName("ISO-8859-1");
private final CharsetDecoder decoder = charset.newDecoder();
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
ByteBuffer buffer = (ByteBuffer) o;
writer.startNode("position");
marshallingContext.convertAnother(buffer.position());
writer.endNode();
writer.startNode("capacity");
marshallingContext.convertAnother(buffer.capacity());
writer.endNode();
writer.startNode("limit");
marshallingContext.convertAnother(buffer.limit());
writer.endNode();
writer.startNode("isDirect");
marshallingContext.convertAnother(buffer.isDirect());
writer.endNode();
buffer.limit();
buffer.capacity();
int position = buffer.position();
int limit = buffer.limit();
buffer.clear();
writer.startNode("data");
try {
CharBuffer charBuffer = decoder.decode(buffer);
writer.setValue(charBuffer.toString());
} catch (CharacterCodingException e) {
throw new ConversionException("", e);
}
writer.endNode();
buffer.limit(limit);
buffer.position(position);
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) {<FILL_FUNCTION_BODY>}
@Override
public boolean canConvert(Class aClass) {
return ByteBuffer.class.isAssignableFrom(aClass);
}
} |
reader.moveDown();
int position = (Integer) unmarshallingContext.convertAnother(null, int.class);
reader.moveUp();
reader.moveDown();
int capacity = (Integer) unmarshallingContext.convertAnother(null, int.class);
reader.moveUp();
reader.moveDown();
int limit = (Integer) unmarshallingContext.convertAnother(null, int.class);
reader.moveUp();
reader.moveDown();
boolean isDirect = (Boolean) unmarshallingContext.convertAnother(null, boolean.class);
reader.moveUp();
ByteBuffer buffer = isDirect ? ByteBuffer.allocateDirect(capacity) : ByteBuffer.allocate(capacity);
buffer.clear();
reader.moveDown();
String o = (String) unmarshallingContext.convertAnother(null, String.class);
CharBuffer uCharBuffer = CharBuffer.wrap(o);
CharsetEncoder encoder = charset.newEncoder();
CoderResult encode = encoder.encode(uCharBuffer, buffer, true);
if (encode.isError())
throw new ConversionException("");
buffer.limit(limit);
buffer.position(position);
reader.moveUp();
buffer.limit(limit);
buffer.position(position);
return buffer;
| 439 | 338 | 777 |
214 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/xstream/converters/CharSequenceConverter.java | CharSequenceConverter | unmarshal | class CharSequenceConverter implements Converter {
@Override
public void marshal(
Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
writer.setValue(source.toString());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {<FILL_FUNCTION_BODY>}
@Override
public boolean canConvert(Class type) {
return CharSequence.class.isAssignableFrom(type);
}
} |
if (context.getRequiredType() == StringBuilder.class) {
return new StringBuilder(reader.getValue());
} else {
return reader.getValue();
}
| 130 | 46 | 176 |
215 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/xstream/converters/ValueConverter.java | ValueConverter | unmarshal | class ValueConverter implements Converter {
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
ValueModel valueModel = ValueModel.acquire(o.getClass());
valueModel.fields().forEach(fieldModel -> {
if (fieldModel instanceof ArrayFieldModel) {
try {
final Method indexedGet = fieldModel.getOrGetVolatile();
indexedGet.setAccessible(true);
writer.startNode(fieldModel.name());
for (int i = 0; i < ((ArrayFieldModel) fieldModel).array().length(); i++) {
writer.startNode(Integer.toString(i));
context.convertAnother(indexedGet.invoke(o, i));
writer.endNode();
}
writer.endNode();
} catch (IllegalAccessException | InvocationTargetException e) {
throw new ConversionException("", e);
}
return;
}
try {
final Method get = fieldModel.getOrGetVolatile();
get.setAccessible(true);
final Object value = get.invoke(o);
writer.startNode(fieldModel.name());
context.convertAnother(value);
writer.endNode();
} catch (Exception e) {
Jvm.error().on(getClass(), "class=" + fieldModel.name(), e);
}
});
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {<FILL_FUNCTION_BODY>}
private void fillInObject(HierarchicalStreamReader reader, UnmarshallingContext context,
ValueModel valueModel, Object using) throws ClassNotFoundException {
while (reader.hasMoreChildren()) {
reader.moveDown();
final String name = reader.getNodeName();
FieldModel fieldModel =
valueModel.fields().filter(f -> f.name().equals(name)).findAny().orElseThrow(() -> new NoSuchElementException("No element with name " + name));
if (fieldModel instanceof ArrayFieldModel) {
while (reader.hasMoreChildren()) {
reader.moveDown();
try {
String index = reader.getNodeName();
int i = Integer.parseInt(index);
Method indexedSet = fieldModel.setOrSetOrderedOrSetVolatile();
indexedSet.setAccessible(true);
Class<?>[] parameterTypes = indexedSet.getParameterTypes();
Object value = context.convertAnother(null, parameterTypes[1]);
indexedSet.invoke(using, i, value);
} catch (Exception e) {
throw new ConversionException("", e);
}
reader.moveUp();
}
reader.moveUp();
continue;
}
Method set = fieldModel.setOrSetOrderedOrSetVolatile();
set.setAccessible(true);
final Class<?>[] parameterTypes = set.getParameterTypes();
final Object value = context.convertAnother(null, parameterTypes[0]);
try {
set.invoke(using, value);
} catch (Exception e) {
throw new ConversionException("", e);
}
reader.moveUp();
}
}
@Override
public boolean canConvert(Class clazz) {
return Values.isValueInterfaceOrImplClass(clazz);
}
} |
try {
ValueModel valueModel = ValueModel.acquire(context.getRequiredType());
Object result = valueModel.heapClass().newInstance();
fillInObject(reader, context, valueModel, result);
return result;
} catch (Exception e) {
throw new ConversionException(
"class=" + context.getRequiredType().getCanonicalName(), e);
}
| 865 | 101 | 966 |
216 | OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/xstream/converters/VanillaChronicleMapConverter.java | VanillaChronicleMapConverter | marshal | class VanillaChronicleMapConverter<K, V> extends AbstractChronicleMapConverter<K, V> {
public VanillaChronicleMapConverter(@NotNull Map<K, V> map) {
super(map);
}
@Override
public void marshal(Object o, final HierarchicalStreamWriter writer, final MarshallingContext
marshallingContext) {<FILL_FUNCTION_BODY>}
} |
((ChronicleMap<K, V>) o).forEachEntry(e -> {
writer.startNode("entry");
{
final Object key = e.key().get();
writer.startNode(key.getClass().getName());
marshallingContext.convertAnother(key);
writer.endNode();
Object value = e.value().get();
writer.startNode(value.getClass().getName());
marshallingContext.convertAnother(value);
writer.endNode();
}
writer.endNode();
});
| 107 | 140 | 247 |
217 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/ChronicleHistoryReaderMain.java | ChronicleHistoryReaderMain | options | class ChronicleHistoryReaderMain {
public static void main(@NotNull String[] args) {
new ChronicleHistoryReaderMain().run(args);
}
protected void run(String[] args) {
final Options options = options();
final CommandLine commandLine = parseCommandLine(args, options);
try (final ChronicleHistoryReader chronicleHistoryReader = chronicleHistoryReader()) {
setup(commandLine, chronicleHistoryReader);
chronicleHistoryReader.execute();
}
}
protected void setup(@NotNull final CommandLine commandLine, @NotNull final ChronicleHistoryReader chronicleHistoryReader) {
chronicleHistoryReader.
withMessageSink(System.out::println).
withProgress(commandLine.hasOption('p')).
withHistosByMethod(commandLine.hasOption('m')).
withBasePath(Paths.get(commandLine.getOptionValue('d')));
if (commandLine.hasOption('t'))
chronicleHistoryReader.withTimeUnit(TimeUnit.valueOf(commandLine.getOptionValue('t')));
if (commandLine.hasOption('i'))
chronicleHistoryReader.withIgnore(Long.parseLong(commandLine.getOptionValue('i')));
if (commandLine.hasOption('w'))
chronicleHistoryReader.withMeasurementWindow(Long.parseLong(commandLine.getOptionValue('w')));
if (commandLine.hasOption('u'))
chronicleHistoryReader.withSummaryOutput(Integer.parseInt(commandLine.getOptionValue('u')));
}
@NotNull
protected ChronicleHistoryReader chronicleHistoryReader() {
return new ChronicleHistoryReader();
}
protected CommandLine parseCommandLine(@NotNull final String[] args, final Options options) {
final CommandLineParser parser = new DefaultParser();
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption('h')) {
printHelpAndExit(options, 0);
}
} catch (ParseException e) {
printHelpAndExit(options, 1, e.getMessage());
}
return commandLine;
}
protected void printHelpAndExit(final Options options, int status) {
printHelpAndExit(options, status, null);
}
protected void printHelpAndExit(final Options options, int status, String message) {
final PrintWriter writer = new PrintWriter(System.out);
new HelpFormatter().printHelp(
writer,
180,
this.getClass().getSimpleName(),
message,
options,
HelpFormatter.DEFAULT_LEFT_PAD,
HelpFormatter.DEFAULT_DESC_PAD,
null,
true
);
writer.flush();
System.exit(status);
}
@NotNull
protected Options options() {<FILL_FUNCTION_BODY>}
} |
final Options options = new Options();
ChronicleReaderMain.addOption(options, "d", "directory", true, "Directory containing chronicle queue files", true);
ChronicleReaderMain.addOption(options, "h", "help-message", false, "Print this help and exit", false);
ChronicleReaderMain.addOption(options, "t", "time unit", true, "Time unit. Default nanos", false);
ChronicleReaderMain.addOption(options, "i", "ignore", true, "How many items to ignore from start", false);
ChronicleReaderMain.addOption(options, "w", "window", true, "Window duration in time unit. Instead of one output at the end, will output every window period", false);
ChronicleReaderMain.addOption(options, "u", "histo offset", true, "Summary output. Instead of histograms, will show one value only, in CSV format. Set this to 0 for 50th, 1 for 90th etc., -1 for worst", false);
options.addOption(new Option("p", false, "Show progress"));
options.addOption(new Option("m", false, "By method"));
return options;
| 724 | 289 | 1,013 |
218 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/channel/PipeHandler.java | PipeHandler | run | class PipeHandler extends AbstractHandler<PipeHandler> {
private String publish;
private String subscribe;
private SyncMode syncMode;
private transient Thread tailerThread;
private Predicate<Wire> filter = null;
private int publishSourceId = 0;
private int subscribeSourceId = 0;
private Consumer<ExcerptTailer> subscriptionIndexController = SubscribeHandler.NO_OP;
public PipeHandler() {
}
static ChronicleQueue newQueue(ChronicleContext context, String queueName, SyncMode syncMode, int sourceId) {
final File path = context.toFile(queueName);
return ChronicleQueue.singleBuilder(path).blockSize(OS.isSparseFileSupported() ? 512L << 30 : 64L << 20).sourceId(sourceId).syncMode(syncMode).build();
}
public String publish() {
return publish;
}
public PipeHandler publish(String publish) {
this.publish = publish;
return this;
}
public String subscribe() {
return subscribe;
}
public PipeHandler subscribe(String subscribe) {
this.subscribe = subscribe;
return this;
}
public SyncMode syncMode() {
return syncMode;
}
public PipeHandler syncMode(SyncMode syncMode) {
this.syncMode = syncMode;
return this;
}
public Predicate<Wire> filter() {
return filter;
}
public PipeHandler filter(Predicate<Wire> filter) {
this.filter = filter;
return this;
}
public int publishSourceId() {
return publishSourceId;
}
public PipeHandler publishSourceId(int publishSourceId) {
this.publishSourceId = publishSourceId;
return this;
}
public PipeHandler subscribeSourceId(int subscribeSourceId) {
this.subscribeSourceId = subscribeSourceId;
return this;
}
@Override
public void run(ChronicleContext context, ChronicleChannel channel) {<FILL_FUNCTION_BODY>}
@Override
public ChronicleChannel asInternalChannel(ChronicleContext context, ChronicleChannelCfg channelCfg) {
return new QueuesChannel(channelCfg, this, newQueue(context, publish, syncMode, publishSourceId), newQueue(context, subscribe, syncMode, 0));
}
static class PHEventPoller extends SimpleCloseable implements EventPoller {
private final ExcerptTailer tailer;
private final Predicate<Wire> filter;
public PHEventPoller(ExcerptTailer tailer, Predicate<Wire> filter) {
this.tailer = tailer;
this.filter = filter;
}
@Override
public boolean onPoll(ChronicleChannel conn) {
boolean wrote = false;
while (SubscribeHandler.copyOneMessage(conn, tailer, filter)) wrote = true;
return wrote;
}
@Override
protected void performClose() {
Closeable.closeQuietly(tailer, tailer.queue());
super.performClose();
}
}
/**
* @param subscriptionIndexController controls where the subscriptions will start to read from, by allowing the caller to
* {@link net.openhft.chronicle.queue.ExcerptTailer#moveToIndex(long) to control the first read location
*/
public PipeHandler subscriptionIndexController(Consumer<ExcerptTailer> subscriptionIndexController) {
this.subscriptionIndexController = subscriptionIndexController;
return this;
}
} |
Pauser pauser = Pauser.balanced();
try (ChronicleQueue subscribeQ = newQueue(context, subscribe, syncMode, subscribeSourceId)) {
final ExcerptTailer tailer;
if (channel instanceof BufferedChronicleChannel) {
BufferedChronicleChannel bc = (BufferedChronicleChannel) channel;
tailer = subscribeQ.createTailer();
tailer.singleThreadedCheckDisabled(true); // assume we are thread safe
subscriptionIndexController.accept(tailer);
bc.eventPoller(new PHEventPoller(tailer, filter));
} else {
tailerThread = new Thread(() -> {
try (AffinityLock lock = context.affinityLock()) {
SubscribeHandler.queueTailer(pauser, channel, subscribeQ, filter, subscriptionIndexController);
} catch (ClosedIORuntimeException e) {
Jvm.warn().on(PipeHandler.class, e.toString());
} catch (Throwable t) {
Jvm.warn().on(PipeHandler.class, t);
}
}, "pipe~tailer");
tailerThread.setDaemon(true);
tailerThread.start();
}
Thread.currentThread().setName("pipe~reader");
try (AffinityLock lock = context.affinityLock()) {
copyFromChannelToQueue(channel, pauser, newQueue(context, publish, syncMode, publishSourceId), syncMode);
} finally {
if (tailerThread != null) tailerThread.interrupt();
}
}
| 938 | 407 | 1,345 |
219 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/channel/PublishHandler.java | PublishHandler | copyFromChannelToQueue | class PublishHandler extends AbstractHandler<PublishHandler> {
private String publish;
private SyncMode syncMode;
private int publishSourceId = 0;
static void copyFromChannelToQueue(ChronicleChannel channel, Pauser pauser, ChronicleQueue publishQueue, SyncMode syncMode) {<FILL_FUNCTION_BODY>}
private static void syncAppender(ExcerptAppender appender, SyncMode syncMode) {
if (syncMode == SyncMode.SYNC) {
try (DocumentContext dc2 = appender.writingDocument()) {
dc2.wire().write("sync").text("");
}
}
appender.sync();
}
public String publish() {
return publish;
}
public PublishHandler publish(String publish) {
this.publish = publish;
return this;
}
public SyncMode syncMode() {
return syncMode;
}
public PublishHandler syncMode(SyncMode syncMode) {
this.syncMode = syncMode;
return this;
}
public int publishSourceId() {
return publishSourceId;
}
public PublishHandler publishSourceId(int publishSourceId) {
this.publishSourceId = publishSourceId;
return this;
}
@Override
public void run(ChronicleContext context, ChronicleChannel channel) {
Pauser pauser = Pauser.balanced();
Thread.currentThread().setName("publish~reader");
try (AffinityLock lock = context.affinityLock()) {
copyFromChannelToQueue(channel, pauser, newQueue(context, publish, syncMode, publishSourceId), syncMode);
}
}
@Override
public ChronicleChannel asInternalChannel(ChronicleContext context, ChronicleChannelCfg channelCfg) {
return new PublishQueueChannel(channelCfg, this, newQueue(context, publish, syncMode, publishSourceId));
}
} |
try (ChronicleQueue publishQ = publishQueue;
ExcerptAppender appender = publishQ.createAppender()) {
appender.singleThreadedCheckDisabled(true); // assume we are thread safe
boolean needsSync = false;
while (!channel.isClosed()) {
try (DocumentContext dc = channel.readingDocument()) {
pauser.unpause();
if (!dc.isPresent()) {
if (needsSync) {
syncAppender(appender, syncMode);
needsSync = false;
}
continue;
}
if (dc.isMetaData()) {
// read message
continue;
}
try (DocumentContext dc2 = appender.writingDocument()) {
dc.wire().copyTo(dc2.wire());
needsSync = syncMode == SyncMode.SYNC || syncMode == SyncMode.ASYNC;
}
}
}
} finally {
Thread.currentThread().setName("connections");
}
| 508 | 263 | 771 |
220 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/channel/SubscribeHandler.java | NoOp | run | class NoOp extends SelfDescribingMarshallable implements Consumer {
@Override
public void accept(Object o) {
return;
}
}
public final static Consumer NO_OP = new NoOp();
private String subscribe;
private transient boolean closeWhenRunEnds = true;
private SyncMode syncMode;
private Predicate<Wire> filter;
private int sourceId;
private Consumer<ExcerptTailer> subscriptionIndexController = NO_OP;
static void queueTailer(@NotNull Pauser pauser,
@NotNull ChronicleChannel channel,
@NotNull ChronicleQueue subscribeQueue,
@Nullable Predicate<Wire> filter,
@NotNull Consumer<ExcerptTailer> subscriptionIndexController) {
try (ChronicleQueue subscribeQ = subscribeQueue; // leave here so it gets closed
ExcerptTailer tailer = subscribeQ.createTailer()) {
tailer.singleThreadedCheckDisabled(true); // assume we are thread safe
subscriptionIndexController.accept(tailer);
while (!channel.isClosing()) {
if (copyOneMessage(channel, tailer, filter))
pauser.reset();
else
pauser.pause();
}
} catch (Exception e) {
Thread.yield();
if (channel.isClosing() || subscribeQueue.isClosing())
return;
throw e;
}
}
static boolean copyOneMessage(ChronicleChannel channel, ExcerptTailer tailer, Predicate<Wire> filter) {
try (DocumentContext dc = tailer.readingDocument()) {
if (!dc.isPresent()) {
return false;
}
if (dc.isMetaData()) {
return true;
}
Wire wire1 = dc.wire();
if (filter != null) {
long pos = wire1.bytes().readPosition();
if (!filter.test(wire1)) {
wire1.bytes().readPosition(wire1.bytes().readLimit());
return true;
}
wire1.bytes().readPosition(pos);
}
try (DocumentContext dc2 = channel.writingDocument()) {
Wire wire2 = dc2.wire();
wire1.copyTo(wire2);
final long dataBuffered = wire2.bytes().writePosition();
// wait for it to drain
return dataBuffered < 32 << 10;
}
}
}
public String subscribe() {
return subscribe;
}
public SubscribeHandler subscribe(String subscribe) {
this.subscribe = subscribe;
return this;
}
public SyncMode syncMode() {
return syncMode;
}
public SubscribeHandler syncMode(SyncMode syncMode) {
this.syncMode = syncMode;
return this;
}
public Predicate<Wire> filter() {
return filter;
}
public SubscribeHandler filter(Predicate<Wire> filter) {
this.filter = filter;
return this;
}
@Override
public void run(ChronicleContext context, ChronicleChannel channel) {<FILL_FUNCTION_BODY> |
Pauser pauser = Pauser.balanced();
final ExcerptTailer tailer;
try (ChronicleQueue subscribeQ = newQueue(context, subscribe, syncMode, sourceId)) {
InternalChronicleChannel icc = (InternalChronicleChannel) channel;
if (icc.supportsEventPoller()) {
tailer = subscribeQ.createTailer();
icc.eventPoller(new SHEventHandler(tailer, filter));
closeWhenRunEnds = false;
} else {
try (AffinityLock lock = context.affinityLock()) {
queueTailer(pauser, channel, newQueue(context, subscribe, syncMode, sourceId), filter, subscriptionIndexController);
}
closeWhenRunEnds = true;
}
}
| 819 | 207 | 1,026 |
221 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/channel/impl/PublishQueueChannel.java | PublishQueueChannel | testMessage | class PublishQueueChannel implements ChronicleChannel {
private final ChronicleChannelCfg channelCfg;
private final AbstractHandler publishHandler;
private final ChannelHeader headerOut;
private final ChronicleQueue publishQueue;
private final ExcerptTailer tailer;
public PublishQueueChannel(ChronicleChannelCfg channelCfg, AbstractHandler publishHandler, ChronicleQueue publishQueue) {
this.channelCfg = channelCfg;
this.publishHandler = publishHandler;
this.headerOut = publishHandler.responseHeader(null);
this.publishQueue = publishQueue;
tailer = publishQueue.createTailer();
}
@Override
public ChronicleChannelCfg channelCfg() {
return channelCfg;
}
@Override
public ChannelHeader headerOut() {
return headerOut;
}
@Override
public ChannelHeader headerIn() {
return publishHandler;
}
@Override
public void close() {
Closeable.closeQuietly(
tailer,
publishQueue);
}
@Override
public boolean isClosed() {
return publishQueue.isClosed();
}
@Override
public DocumentContext readingDocument() {
return NoDocumentContext.INSTANCE;
}
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
return acquireThreadLocalAppender(publishQueue).writingDocument(metaData);
}
@Override
public DocumentContext acquireWritingDocument(boolean metaData) throws UnrecoverableTimeoutException {
return acquireThreadLocalAppender(publishQueue).acquireWritingDocument(metaData);
}
@Override
public void testMessage(long now) {<FILL_FUNCTION_BODY>}
@Override
public long lastTestMessage() {
throw new UnsupportedOperationException();
}
} |
try (DocumentContext dc = writingDocument(true)) {
dc.wire().write("testMessage").writeLong(NanoTime.INSTANCE, now);
}
| 479 | 45 | 524 |
222 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/channel/impl/SubscribeQueueChannel.java | SubscribeQueueChannel | readingDocument | class SubscribeQueueChannel implements ChronicleChannel {
private final ChronicleChannelCfg channelCfg;
private final AbstractHandler pipeHandler;
private final ChannelHeader headerOut;
private final ChronicleQueue subscribeQueue;
private final ExcerptTailer tailer;
private long lastTestMessage;
public SubscribeQueueChannel(ChronicleChannelCfg channelCfg, AbstractHandler pipeHandler, ChronicleQueue subscribeQueue) {
this.channelCfg = channelCfg;
this.pipeHandler = pipeHandler;
this.headerOut = pipeHandler.responseHeader(null);
this.subscribeQueue = subscribeQueue;
tailer = subscribeQueue.createTailer();
}
@Override
public ChronicleChannelCfg channelCfg() {
return channelCfg;
}
@Override
public ChannelHeader headerOut() {
return headerOut;
}
@Override
public ChannelHeader headerIn() {
return pipeHandler;
}
@Override
public void close() {
Closeable.closeQuietly(
tailer,
subscribeQueue);
}
@Override
public boolean isClosed() {
return subscribeQueue.isClosed();
}
@Override
public DocumentContext readingDocument() {<FILL_FUNCTION_BODY>}
@Override
public DocumentContext writingDocument(boolean metaData) throws UnrecoverableTimeoutException {
return NoDocumentContext.INSTANCE;
}
@Override
public DocumentContext acquireWritingDocument(boolean metaData) throws UnrecoverableTimeoutException {
return NoDocumentContext.INSTANCE;
}
@Override
public void testMessage(long now) {
}
@Override
public long lastTestMessage() {
return lastTestMessage;
}
} |
final DocumentContext dc = tailer.readingDocument(true);
if (dc.isMetaData()) {
final Wire wire = dc.wire();
long pos = wire.bytes().readPosition();
final String event = wire.readEvent(String.class);
if ("testMessage".equals(event)) {
final long testMessage = wire.getValueIn().readLong(NanoTime.INSTANCE);
lastTestMessage = testMessage;
try (DocumentContext dc2 = writingDocument(true)) {
dc2.wire().write("testMessage").writeLong(NanoTime.INSTANCE, testMessage);
}
wire.bytes().readPosition(pos);
return dc;
}
dc.close();
return readingDocument();
}
return dc;
| 452 | 200 | 652 |
223 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/RollingResourcesCache.java | RollingResourcesCache | parseCount0 | class RollingResourcesCache {
public static final ParseCount NO_PARSE_COUNT = new ParseCount("", Integer.MIN_VALUE);
private static final int CACHE_SIZE = Jvm.getInteger("chronicle.queue.rollingResourceCache.size", 128);
private static final int ONE_DAY_IN_MILLIS = 86400000;
private static final int MAX_TIMESTAMP_CACHE_SIZE = 32;
@NotNull
private final Function<String, File> fileFactory;
@NotNull
private final DateTimeFormatter formatter;
@NotNull
private final Resource[] values;
private final int length;
@NotNull
private final Function<File, String> fileToName;
private final String format;
private final ConcurrentMap<File, Long> filenameToTimestampCache =
new ConcurrentHashMap<>(MAX_TIMESTAMP_CACHE_SIZE);
private final long epoch;
private ParseCount lastParseCount = NO_PARSE_COUNT;
public RollingResourcesCache(@NotNull final RollCycle cycle, long epoch,
@NotNull Function<String, File> nameToFile,
@NotNull Function<File, String> fileToName) {
this(cycle.lengthInMillis(), cycle.format(), epoch, nameToFile, fileToName);
}
private RollingResourcesCache(final int length,
@NotNull String format, long epoch,
@NotNull Function<String, File> nameToFile,
@NotNull Function<File, String> fileToName) {
this.length = length;
this.fileToName = fileToName;
this.values = new Resource[CACHE_SIZE];
final long millisInDay = epoch % ONE_DAY_IN_MILLIS;
this.epoch = millisInDay >= 0 ? epoch - millisInDay : -ONE_DAY_IN_MILLIS;
this.format = format;
this.formatter = DateTimeFormatter.ofPattern(this.format).withZone(ZoneId.of("UTC"));
this.fileFactory = nameToFile;
}
/**
* Cache some resources for a rollCycle number.
*
* @param cycle the rollCycle number to format
* @return the Resource
*/
@NotNull
public Resource resourceFor(long cycle) {
long millisSinceBeginningOfEpoch = (cycle * length);
long h = Maths.hash64(millisSinceBeginningOfEpoch);
h ^= h >> 32;
int hash = (int) h & (CACHE_SIZE - 1);
Resource dv = values[hash];
if (dv == null || dv.millis != millisSinceBeginningOfEpoch) {
final Instant instant = Instant.ofEpochMilli(millisSinceBeginningOfEpoch + epoch);
@NotNull String text = formatter.format(instant);
values[hash] = dv = new Resource(millisSinceBeginningOfEpoch, text, fileFactory.apply(text));
}
return dv;
}
public int parseCount(@NotNull String name) {
ParseCount last = this.lastParseCount;
if (name.equals(last.name))
return last.count;
int count = parseCount0(name);
lastParseCount = new ParseCount(name, count);
return count;
}
private int parseCount0(@NotNull String name) {<FILL_FUNCTION_BODY>}
public Long toLong(File file) {
final Long cachedValue = filenameToTimestampCache.get(file);
if (cachedValue != null) {
return cachedValue;
}
final TemporalAccessor parse = formatter.parse(fileToName.apply(file));
final long value;
if (length == ONE_DAY_IN_MILLIS) {
value = parse.getLong(ChronoField.EPOCH_DAY);
} else if (length < ONE_DAY_IN_MILLIS) {
value = Instant.from(parse).toEpochMilli() / length;
} else {
long daysSinceEpoch = parse.getLong(ChronoField.EPOCH_DAY);
long adjShift = daysSinceEpoch < 0 ? -1 : 0;
value = adjShift + ((daysSinceEpoch * 86400) / (length / 1000));
}
if (filenameToTimestampCache.size() >= MAX_TIMESTAMP_CACHE_SIZE) {
filenameToTimestampCache.clear();
}
filenameToTimestampCache.put(file, value);
return value;
}
static final class ParseCount {
final String name;
final int count;
public ParseCount(String name, int count) {
this.name = name;
this.count = count;
}
}
public static final class Resource {
public final long millis;
public final String text;
public final File path;
public final File parentPath;
public boolean pathExists;
Resource(long millis, String text, File path) {
this.millis = millis;
this.text = text;
this.path = path;
this.parentPath = path.getParentFile();
}
}
} |
try {
TemporalAccessor parse = formatter.parse(name);
if (!parse.isSupported(ChronoField.EPOCH_DAY)) {
final WeekFields weekFields = WeekFields.of(formatter.getLocale());
if (parse.isSupported(weekFields.weekBasedYear()) && parse.isSupported(weekFields.weekOfWeekBasedYear())) {
int year = Math.toIntExact(parse.getLong(weekFields.weekBasedYear()));
int week = Math.toIntExact(parse.getLong(weekFields.weekOfWeekBasedYear()));
LocalDate ld = LocalDate.now()
.withYear(year)
.with(weekFields.weekOfYear(), week)
.with(weekFields.dayOfWeek(), 1);
return Math.toIntExact(ld.toEpochDay());
}
throw new UnsupportedOperationException("Unable to parse " + name + " using format " + format);
}
long epochDay = parse.getLong(ChronoField.EPOCH_DAY) * 86400;
if (parse.isSupported(ChronoField.SECOND_OF_DAY))
epochDay += parse.getLong(ChronoField.SECOND_OF_DAY);
return Maths.toInt32((epochDay - ((epoch) / 1000)) / (length / 1000));
} catch (DateTimeParseException e) {
throw new RuntimeException(String.format(
"Unable to parse %s using format %s", name, format), e);
}
| 1,351 | 407 | 1,758 |
224 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/WireStorePool.java | WireStorePool | acquire | class WireStorePool extends SimpleCloseable {
@NotNull
private final WireStoreSupplier supplier;
private final StoreFileListener storeFileListener;
private WireStorePool(@NotNull WireStoreSupplier supplier, StoreFileListener storeFileListener) {
this.supplier = supplier;
this.storeFileListener = storeFileListener;
}
@NotNull
public static WireStorePool withSupplier(@NotNull WireStoreSupplier supplier, StoreFileListener storeFileListener) {
return new WireStorePool(supplier, storeFileListener);
}
@Nullable
public SingleChronicleQueueStore acquire(
final int cycle,
WireStoreSupplier.CreateStrategy createStrategy,
SingleChronicleQueueStore oldStore) {<FILL_FUNCTION_BODY>}
public int nextCycle(final int currentCycle, @NotNull TailerDirection direction) throws ParseException {
throwExceptionIfClosed();
return supplier.nextCycle(currentCycle, direction);
}
public void closeStore(@NotNull SingleChronicleQueueStore store) {
BackgroundResourceReleaser.release(store);
if (storeFileListener.isActive())
BackgroundResourceReleaser.run(() -> storeFileListener.onReleased(store.cycle(), store.file()));
}
/**
* list cycles between ( inclusive )
*
* @param lowerCycle the lower cycle
* @param upperCycle the upper cycle
* @return an array including these cycles and all the intermediate cycles
*/
public NavigableSet<Long> listCyclesBetween(int lowerCycle, int upperCycle) {
throwExceptionIfClosed();
return supplier.cycles(lowerCycle, upperCycle);
}
} |
throwExceptionIfClosed();
// reuse cycle store when applicable
if (oldStore != null && oldStore.cycle() == cycle && !oldStore.isClosed())
return oldStore;
SingleChronicleQueueStore store = this.supplier.acquire(cycle, createStrategy);
if (store != null) {
store.cycle(cycle);
if (store != oldStore && storeFileListener.isActive())
BackgroundResourceReleaser.run(() -> storeFileListener.onAcquired(cycle, store.file()));
}
return store;
| 440 | 148 | 588 |
225 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/FileSystemDirectoryListing.java | FileSystemDirectoryListing | refresh | class FileSystemDirectoryListing extends SimpleCloseable implements DirectoryListing {
private final File queueDir;
private final ToIntFunction<String> fileNameToCycleFunction;
private int minCreatedCycle = Integer.MAX_VALUE;
private int maxCreatedCycle = Integer.MIN_VALUE;
private long lastRefreshTimeMS;
FileSystemDirectoryListing(final File queueDir,
final ToIntFunction<String> fileNameToCycleFunction) {
this.queueDir = queueDir;
this.fileNameToCycleFunction = fileNameToCycleFunction;
}
@Override
public void onFileCreated(final File file, final int cycle) {
onRoll(cycle);
}
@Override
public void refresh(boolean force) {<FILL_FUNCTION_BODY>}
@Override
public long lastRefreshTimeMS() {
return lastRefreshTimeMS;
}
@Override
public int getMinCreatedCycle() {
return minCreatedCycle;
}
@Override
public int getMaxCreatedCycle() {
return maxCreatedCycle;
}
@Override
public long modCount() {
return -1;
}
@Override
public void onRoll(int cycle) {
minCreatedCycle = Math.min(minCreatedCycle, cycle);
maxCreatedCycle = Math.max(maxCreatedCycle, cycle);
}
} |
lastRefreshTimeMS = System.currentTimeMillis();
final String[] fileNamesList = queueDir.list();
String minFilename = INITIAL_MIN_FILENAME;
String maxFilename = INITIAL_MAX_FILENAME;
if (fileNamesList != null) {
for (String fileName : fileNamesList) {
if (fileName.endsWith(SingleChronicleQueue.SUFFIX)) {
if (minFilename.compareTo(fileName) > 0)
minFilename = fileName;
if (maxFilename.compareTo(fileName) < 0)
maxFilename = fileName;
}
}
}
int min = UNSET_MIN_CYCLE;
if (!INITIAL_MIN_FILENAME.equals(minFilename))
min = fileNameToCycleFunction.applyAsInt(minFilename);
int max = UNSET_MAX_CYCLE;
if (!INITIAL_MAX_FILENAME.equals(maxFilename))
max = fileNameToCycleFunction.applyAsInt(maxFilename);
minCreatedCycle = min;
maxCreatedCycle = max;
| 365 | 300 | 665 |
226 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/MicroToucher.java | MicroToucher | bgExecute | class MicroToucher {
private final StoreAppender appender;
private long lastPageTouched = 0;
private volatile long lastPageToSync = 0;
private long lastPageSynced = 0;
public MicroToucher(StoreAppender appender) {
this.appender = appender;
}
public boolean execute() {
final Wire bufferWire = appender.wire();
if (bufferWire == null)
return false;
final long lastPosition = appender.lastPosition;
final long lastPage = lastPosition & ~0xFFF;
final long nextPage = (lastPosition + 0xFFF) & ~0xFFF;
Bytes<?> bytes = bufferWire.bytes();
if (nextPage != lastPageTouched) {
lastPageTouched = nextPage;
try {
// best effort
final BytesStore bs = bytes.bytesStore();
if (bs.inside(nextPage, 8))
touchPage(nextPage, bs);
} catch (Throwable ignored) {
}
return true;
}
lastPageToSync = lastPage;
return false;
}
public void bgExecute() {<FILL_FUNCTION_BODY>}
private void sync(BytesStore bytes, long start, long length) {
if (!bytes.inside(start, length))
return;
// long a = System.nanoTime();
PosixAPI.posix().msync(bytes.addressForRead(start), length, MSyncFlag.MS_ASYNC);
// System.out.println("sync took " + (System.nanoTime() - a) / 1000);
}
protected boolean touchPage(long nextPage, BytesStore bs) {
return bs.compareAndSwapLong(nextPage, 0, 0);
}
} |
final long lastPage = this.lastPageToSync;
final long start = this.lastPageSynced;
final long length = Math.min(8 << 20, lastPage - start);
// System.out.println("len "+length);
if (length < 8 << 20)
return;
final Wire bufferWire = appender.wire();
if (bufferWire == null)
return;
BytesStore bytes = bufferWire.bytes().bytesStore();
sync(bytes, start, length);
this.lastPageSynced += length;
| 479 | 146 | 625 |
227 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/ReferenceCountedCache.java | ReferenceCountedCache | releaseResource | class ReferenceCountedCache<K, T extends ReferenceCounted & Closeable, V, E extends Throwable>
extends AbstractCloseable {
private final Map<K, T> cache = new LinkedHashMap<>();
private final Function<T, V> transformer;
private final ThrowingFunction<K, T, E> creator;
private final ReferenceChangeListener referenceChangeListener;
public ReferenceCountedCache(final Function<T, V> transformer,
final ThrowingFunction<K, T, E> creator) {
this.transformer = transformer;
this.creator = creator;
this.referenceChangeListener = new TriggerFlushOnLastReferenceRemoval();
singleThreadedCheckDisabled(true);
}
@NotNull
V get(@NotNull final K key) throws E {
throwExceptionIfClosed();
final V rv;
synchronized (cache) {
@Nullable T value = cache.get(key);
if (value == null) {
value = creator.apply(key);
value.reserveTransfer(INIT, this);
value.addReferenceChangeListener(referenceChangeListener);
//System.err.println("Reserved " + value.toString() + " by " + this);
cache.put(key, value);
}
// this will add to the ref count and so needs to be done inside of sync block
rv = transformer.apply(value);
}
return rv;
}
@Override
protected void performClose() {
synchronized (cache) {
for (T value : cache.values()) {
releaseResource(value);
}
cache.clear();
}
}
private void releaseResource(T value) {<FILL_FUNCTION_BODY>}
public void remove(K key) {
// harmless to call if cache is already closing/closed
synchronized (cache) {
releaseResource(cache.remove(key));
}
}
private class TriggerFlushOnLastReferenceRemoval implements ReferenceChangeListener {
private final Runnable bgCleanup = this::bgCleanup;
@Override
public void onReferenceRemoved(ReferenceCounted referenceCounted, ReferenceOwner referenceOwner) {
if (referenceOwner != ReferenceCountedCache.this && referenceCounted.refCount() == 1) {
BackgroundResourceReleaser.run(bgCleanup);
}
}
private void bgCleanup() {
// remove all which have been de-referenced by other than me. Garbagy but rare
synchronized (cache) {
cache.entrySet().removeIf(entry -> {
T value = entry.getValue();
int refCount = value.refCount();
if (refCount == 1) {
value.release(ReferenceCountedCache.this);
}
return refCount <= 1;
});
}
}
}
} |
try {
if (value != null)
value.release(this);
} catch (Exception e) {
Jvm.debug().on(getClass(), e);
}
| 732 | 50 | 782 |
228 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/RollCycleEncodeSequence.java | RollCycleEncodeSequence | getSequence | class RollCycleEncodeSequence implements Sequence {
private final TwoLongValue writePositionAndSequence;
private final int cycleShift;
private final long sequenceMask;
RollCycleEncodeSequence(LongValue writePositionAndSequence, int indexCount, int indexSpacing) {
this.cycleShift = Math.max(32, Maths.intLog2(indexCount) * 2 + Maths.intLog2(indexSpacing));
this.sequenceMask = (1L << cycleShift) - 1;
this.writePositionAndSequence = writePositionAndSequence instanceof TwoLongValue ?
(TwoLongValue) writePositionAndSequence : null;
}
@Override
public void setSequence(long sequence, long position) {
if (writePositionAndSequence == null)
return;
long value = toLongValue(position, sequence);
writePositionAndSequence.setOrderedValue2(value);
}
@Override
public long toIndex(long headerNumber, long sequence) {
long cycle = toLowerBitsWritePosition(headerNumber);
return toLongValue(cycle, sequence);
}
/**
* gets the sequence for a writePosition
* <p>
* This method will only return a valid sequence number of the write position if the write position is the
* last write position in the queue. YOU CAN NOT USE THIS METHOD TO LOOK UP RANDOM SEQUENCES FOR ANY WRITE POSITION.
* NOT_FOUND_RETRY will be return if a sequence number can not be found ( so can retry )
* or NOT_FOUND when you should not retry
*
* @param forWritePosition the last write position, expected to be the end of queue
* @return NOT_FOUND_RETRY if the sequence for this write position can not be found, or NOT_FOUND if sequenceValue==null or the sequence for this {@code writePosition}
*/
public long getSequence(long forWritePosition) {<FILL_FUNCTION_BODY>}
private long toLongValue(long cycle, long sequenceNumber) {
return (cycle << cycleShift) + (sequenceNumber & sequenceMask);
}
public long toSequenceNumber(long index) {
return index & sequenceMask;
}
private long toLowerBitsWritePosition(long index) {
return index >>> cycleShift;
}
@Override
public String toString() {
return "RollCycleEncodeSequence{" +
"writePositionAndSequence=" + writePositionAndSequence +
", cycleShift=" + cycleShift +
", sequenceMask=" + sequenceMask +
'}';
}
} |
if (writePositionAndSequence == null)
return Sequence.NOT_FOUND;
// We only deal with the 2nd long in the TwoLongValue, and we use it to keep track of current position
// and current sequence. We use the same encoding as index (cycle number is shifted left by cycleShift
// and sequence number occupied the lower 64-cycleShift bits) but for this use case we mask and shift
// position into the space used for cycle number.
// todo optimize the maths in the method below
final long sequenceValue = this.writePositionAndSequence.getVolatileValue2();
if (sequenceValue == 0)
return Sequence.NOT_FOUND;
long writePositionAsCycle = toLongValue(forWritePosition, 0);
long lowerBitsOfWp = toLowerBitsWritePosition(writePositionAsCycle);
final long toLowerBitsWritePosition = toLowerBitsWritePosition(sequenceValue);
if (lowerBitsOfWp == toLowerBitsWritePosition)
return toSequenceNumber(sequenceValue);
return Sequence.NOT_FOUND_RETRY;
| 650 | 279 | 929 |
229 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/SCQMeta.java | SCQMeta | overrideFrom | class SCQMeta implements Metadata {
@NotNull
private final SCQRoll roll;
private final int deltaCheckpointInterval;
private int sourceId;
@SuppressWarnings("unused")
@UsedViaReflection
SCQMeta(@NotNull WireIn wire) {
this.roll = Objects.requireNonNull(wire.read(MetaDataField.roll).typedMarshallable());
this.deltaCheckpointInterval = wire.bytes().readRemaining() > 0 ? wire.read(MetaDataField.deltaCheckpointInterval).int32() : -1; // disabled.
this.sourceId = wire.bytes().readRemaining() > 0 ? wire.read(MetaDataField.sourceId).int32() : 0;
}
SCQMeta(@NotNull SCQRoll roll, int deltaCheckpointInterval, int sourceId) {
this.roll = roll;
this.deltaCheckpointInterval = deltaCheckpointInterval;
this.sourceId = sourceId;
}
@NotNull
public SCQRoll roll() {
return roll;
}
public int deltaCheckpointInterval() {
return deltaCheckpointInterval;
}
public int sourceId() {
return sourceId;
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
wire
.write(MetaDataField.roll).typedMarshallable(roll)
.write(MetaDataField.deltaCheckpointInterval).int32(this.deltaCheckpointInterval)
.write(MetaDataField.sourceId).int32(this.sourceId);
}
@Override
public <T extends Metadata> void overrideFrom(T metadata) {<FILL_FUNCTION_BODY>}
} |
if (!(metadata instanceof SCQMeta))
throw new IllegalStateException("Expected SCQMeta, got " + metadata.getClass());
SCQMeta other = (SCQMeta) metadata;
SCQRoll roll = other.roll;
if (roll.epoch() != this.roll.epoch()) {
Jvm.warn().on(getClass(), "Overriding roll epoch from existing metadata, was " + this.roll.epoch() + ", overriding to " + roll.epoch());
this.roll.epoch(roll.epoch());
}
if (roll.length() != this.roll.length()) {
Jvm.warn().on(getClass(), "Overriding roll length from existing metadata, was " + this.roll.length() + ", overriding to " + roll.length());
this.roll.length(roll.length());
this.roll.format(roll.format());
}
if (roll.rollTime() != null && !Objects.equals(roll.rollTime(), this.roll.rollTime())) {
Jvm.warn().on(getClass(), "Overriding roll time from existing metadata, was " + this.roll.rollTime() + ", overriding to " + roll.rollTime());
this.roll.rollTime(roll.rollTime());
}
if (roll.rollTimeZone() != null && !Objects.equals(roll.rollTimeZone(), this.roll.rollTimeZone())) {
Jvm.warn().on(getClass(), "Overriding roll time zone from existing metadata, was " + this.roll.rollTimeZone() + ", overriding to " + roll.rollTimeZone());
this.roll.rollTimeZone(roll.rollTimeZone());
}
if (other.sourceId != sourceId) {
Jvm.warn().on(getClass(), "Overriding sourceId from existing metadata, was " + sourceId + ", overriding to " + other.sourceId);
this.sourceId = other.sourceId;
}
| 436 | 493 | 929 |
230 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/SCQRoll.java | SCQRoll | toString | class SCQRoll implements Demarshallable, WriteMarshallable {
private int length;
@Nullable
private String format;
@Nullable
private LocalTime rollTime;
@Nullable
private ZoneId rollTimeZone;
private long epoch;
/**
* used by {@link Demarshallable}
*
* @param wire a wire
*/
@UsedViaReflection
private SCQRoll(@NotNull WireIn wire) {
length = wire.read(RollFields.length).int32();
format = wire.read(RollFields.format).text();
epoch = wire.read(RollFields.epoch).int64();
ValueIn rollTimeVIN = wire.read(RollFields.rollTime);
if (rollTimeVIN.hasNext())
rollTime = rollTimeVIN.time();
String zoneId = wire.read(RollFields.rollTimeZone).text();
if (zoneId != null)
rollTimeZone = ZoneId.of(zoneId);
else
rollTimeZone = null;
}
SCQRoll(@NotNull RollCycle rollCycle,
long epoch,
@Nullable LocalTime rollTime,
@Nullable ZoneId rollTimeZone) {
this.length = rollCycle.lengthInMillis();
this.format = rollCycle.format();
this.epoch = epoch;
this.rollTime = rollTime;
this.rollTimeZone = rollTimeZone;
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
wire.write(RollFields.length).int32(length)
.write(RollFields.format).text(format)
.write(RollFields.epoch).int64(epoch);
if (rollTime != null)
wire.write(RollFields.rollTime).time(rollTime);
if (rollTimeZone != null)
wire.write(RollFields.rollTimeZone).text(rollTimeZone.getId());
}
/**
* @return an epoch offset as the number of number of milliseconds since January 1, 1970,
* 00:00:00 GMT
*/
public long epoch() {
return this.epoch;
}
public String format() {
return this.format;
}
int length() {
return length;
}
@Nullable
public LocalTime rollTime() {
return rollTime;
}
@Nullable
public ZoneId rollTimeZone() {
return rollTimeZone;
}
public void length(int length) {
this.length = length;
}
public void format(@Nullable String format) {
this.format = format;
}
public void rollTime(@Nullable LocalTime rollTime) {
this.rollTime = rollTime;
}
public void rollTimeZone(@Nullable ZoneId rollTimeZone) {
this.rollTimeZone = rollTimeZone;
}
public void epoch(long epoch) {
this.epoch = epoch;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
enum RollFields implements WireKey {
length, format, epoch, rollTime, rollTimeZone
}
} |
return "SCQRoll{" +
"length=" + length +
", format='" + format + '\'' +
", epoch=" + epoch +
", rollTime=" + rollTime +
", rollTimeZone=" + rollTimeZone +
'}';
| 843 | 72 | 915 |
231 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/TableDirectoryListing.java | TableDirectoryListing | refresh | class TableDirectoryListing extends AbstractCloseable implements DirectoryListing {
private static final String HIGHEST_CREATED_CYCLE = "listing.highestCycle";
private static final String LOWEST_CREATED_CYCLE = "listing.lowestCycle";
private static final String MOD_COUNT = "listing.modCount";
static final int UNSET_MAX_CYCLE = Integer.MIN_VALUE;
static final int UNSET_MIN_CYCLE = Integer.MAX_VALUE;
static final String INITIAL_MIN_FILENAME = Character.toString(Character.MAX_VALUE);
static final String INITIAL_MAX_FILENAME = Character.toString(Character.MIN_VALUE);
private final TableStore<?> tableStore;
private final Path queuePath;
private final ToIntFunction<String> fileNameToCycleFunction;
private volatile LongValue maxCycleValue;
private volatile LongValue minCycleValue;
private volatile LongValue modCount;
private long lastRefreshTimeMS = 0;
TableDirectoryListing(
final @NotNull TableStore<?> tableStore,
final Path queuePath,
final ToIntFunction<String> fileNameToCycleFunction) {
this.tableStore = tableStore;
this.queuePath = queuePath;
this.fileNameToCycleFunction = fileNameToCycleFunction;
checkReadOnly(tableStore);
singleThreadedCheckDisabled(true);
}
protected void checkReadOnly(@NotNull TableStore<?> tableStore) {
if (tableStore.readOnly()) {
throw new IllegalArgumentException(getClass().getSimpleName() + " should only be used for writable queues");
}
}
@Override
public void init() {
throwExceptionIfClosedInSetter();
tableStore.doWithExclusiveLock(ts -> {
initLongValues();
minCycleValue.compareAndSwapValue(Long.MIN_VALUE, UNSET_MIN_CYCLE);
if (modCount.getVolatileValue() == Long.MIN_VALUE) {
modCount.compareAndSwapValue(Long.MIN_VALUE, 0);
}
return this;
});
}
protected void initLongValues() {
maxCycleValue = tableStore.acquireValueFor(HIGHEST_CREATED_CYCLE);
minCycleValue = tableStore.acquireValueFor(LOWEST_CREATED_CYCLE);
modCount = tableStore.acquireValueFor(MOD_COUNT);
}
@Override
public void refresh(final boolean force) {<FILL_FUNCTION_BODY>}
@Override
public void onFileCreated(final File file, final int cycle) {
onRoll(cycle);
}
@Override
public void onRoll(int cycle) {
minCycleValue.setMinValue(cycle);
maxCycleValue.setMaxValue(cycle);
modCount.addAtomicValue(1);
}
@Override
public long lastRefreshTimeMS() {
return lastRefreshTimeMS;
}
@Override
public int getMaxCreatedCycle() {
return getMaxCycleValue();
}
@Override
public int getMinCreatedCycle() {
return getMinCycleValue();
}
@Override
public long modCount() {
return modCount.getVolatileValue();
}
@Override
public String toString() {
return tableStore.dump(WireType.BINARY_LIGHT);
}
protected void performClose() {
Closeable.closeQuietly(minCycleValue, maxCycleValue, modCount);
}
private int getMaxCycleValue() {
return (int) maxCycleValue.getVolatileValue();
}
private int getMinCycleValue() {
return (int) minCycleValue.getVolatileValue();
}
} |
if (!force) {
return;
}
lastRefreshTimeMS = System.currentTimeMillis();
final long currentMin0 = minCycleValue.getVolatileValue();
final long currentMax0 = maxCycleValue.getVolatileValue();
while (true) {
throwExceptionIfClosed();
tableStore.throwExceptionIfClosed();
Jvm.safepoint();
final long currentMax = maxCycleValue.getVolatileValue();
final String[] fileNamesList = queuePath.toFile().list();
String minFilename = INITIAL_MIN_FILENAME;
String maxFilename = INITIAL_MAX_FILENAME;
if (fileNamesList != null) {
for (String fileName : fileNamesList) {
if (fileName.endsWith(SingleChronicleQueue.SUFFIX)) {
if (minFilename.compareTo(fileName) > 0)
minFilename = fileName;
if (maxFilename.compareTo(fileName) < 0)
maxFilename = fileName;
}
}
}
int min = UNSET_MIN_CYCLE;
if (!INITIAL_MIN_FILENAME.equals(minFilename))
min = fileNameToCycleFunction.applyAsInt(minFilename);
int max = UNSET_MAX_CYCLE;
if (!INITIAL_MAX_FILENAME.equals(maxFilename))
max = fileNameToCycleFunction.applyAsInt(maxFilename);
if (currentMin0 == min && currentMax0 == max) {
modCount.addAtomicValue(1);
return;
}
minCycleValue.setOrderedValue(min);
if (maxCycleValue.compareAndSwapValue(currentMax, max)) {
modCount.addAtomicValue(1);
break;
}
Jvm.nanoPause();
}
| 1,006 | 496 | 1,502 |
232 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/TableDirectoryListingReadOnly.java | TableDirectoryListingReadOnly | init | class TableDirectoryListingReadOnly extends TableDirectoryListing {
TableDirectoryListingReadOnly(final @NotNull TableStore<?> tableStore) {
super(tableStore, null, null);
}
@Override
protected void checkReadOnly(@NotNull TableStore<?> tableStore) {
// no-op
}
@Override
public void init() {<FILL_FUNCTION_BODY>}
@Override
public void refresh(final boolean force) {
// no-op
}
@Override
public void onFileCreated(final File file, final int cycle) {
onRoll(cycle);
}
@Override
public void onRoll(int cycle) {
// no-op
}
} |
throwExceptionIfClosedInSetter();
// it is possible if r/o queue created at same time as r/w queue for longValues to be only half-written
final long timeoutMillis = System.currentTimeMillis() + 500;
while (true) {
try {
initLongValues();
break;
} catch (Exception e) {
if (System.currentTimeMillis() > timeoutMillis)
throw e;
Jvm.pause(1);
}
}
| 192 | 131 | 323 |
233 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/TableStoreWriteLock.java | TableStoreWriteLock | lockAssertPostConditions | class TableStoreWriteLock extends AbstractTSQueueLock implements WriteLock {
public static final String APPEND_LOCK_KEY = "chronicle.append.lock";
private static final String LOCK_KEY = "chronicle.write.lock";
private final long timeout;
private Thread lockedByThread = null;
private StackTrace lockedHere;
public TableStoreWriteLock(final TableStore<?> tableStore, Supplier<TimingPauser> pauser, Long timeoutMs, final String lockKey) {
super(lockKey, tableStore, pauser);
timeout = timeoutMs;
}
public TableStoreWriteLock(final TableStore<?> tableStore, Supplier<TimingPauser> pauser, Long timeoutMs) {
this(tableStore, pauser, timeoutMs, LOCK_KEY);
}
/**
* Guaranteed to succeed in getting the lock (may involve timeout and recovery) or else throw.
* <p>This is not re-entrant i.e. if you lock and try and lock again it will timeout and recover
*/
@Override
public void lock() {
throwExceptionIfClosed();
assert checkNotAlreadyLocked();
long currentLockValue = 0;
TimingPauser tlPauser = pauser.get();
try {
currentLockValue = lock.getVolatileValue();
while (!lock.compareAndSwapValue(UNLOCKED, PID)) {
currentLockValue = lockGetCurrentLockValue(tlPauser);
}
lockAssertPostConditions();
// success
} catch (TimeoutException e) {
handleTimeoutEx(currentLockValue);
} finally {
tlPauser.reset();
}
}
private long lockGetCurrentLockValue(TimingPauser tlPauser) throws TimeoutException {
if (Thread.currentThread().isInterrupted())
throw new InterruptedRuntimeException("Interrupted for the lock file:" + path);
tlPauser.pause(timeout, TimeUnit.MILLISECONDS);
return lock.getVolatileValue();
}
private void lockAssertPostConditions() {<FILL_FUNCTION_BODY>}
private void handleTimeoutEx(long currentLockValue) {
final String lockedBy = getLockedBy(currentLockValue);
final String warningMsg = lockHandleTimeoutExCreateWarningMessage(lockedBy);
if (forceUnlockOnTimeoutWhen == UnlockMode.NEVER)
throw new UnrecoverableTimeoutException(new IllegalStateException(warningMsg + UNLOCK_MAIN_MSG));
else if (forceUnlockOnTimeoutWhen == UnlockMode.LOCKING_PROCESS_DEAD) {
if (forceUnlockIfProcessIsDead())
lock();
else
throw new UnrecoverableTimeoutException(new IllegalStateException(warningMsg + UNLOCK_MAIN_MSG));
} else {
warn().on(getClass(), warningMsg + UNLOCKING_FORCIBLY_MSG);
forceUnlock(currentLockValue);
lock();
}
}
@NotNull
private String lockHandleTimeoutExCreateWarningMessage(String lockedBy) {
return "Couldn't acquire write lock " +
"after " + timeout + " ms " +
"for the lock file:" + path + ". " +
"Lock was held by " + lockedBy;
}
@NotNull
protected String getLockedBy(long value) {
return value == Long.MIN_VALUE ? "unknown" :
value == PID ? "me"
: Long.toString((int) value);
}
private boolean checkNotAlreadyLocked() {
if (!locked())
return true;
if (lockedByThread == null)
return true;
if (lockedByThread == Thread.currentThread())
throw new AssertionError("Lock is already acquired by current thread and is not reentrant - nested document context?", lockedHere);
return true;
}
@Override
public void unlock() {
throwExceptionIfClosed();
if (!lock.compareAndSwapValue(PID, UNLOCKED)) {
long value = lock.getVolatileValue();
if (value == UNLOCKED)
warn().on(getClass(), "Write lock was already unlocked. For the " +
"lock file:" + path);
else
warn().on(getClass(), "Write lock was locked by someone else! For the " +
"lock file:" + path + " " +
"by PID: " + getLockedBy(value));
}
lockedByThread = null;
lockedHere = null;
}
@Override
public boolean locked() {
throwExceptionIfClosed();
return lock.getVolatileValue(UNLOCKED) != UNLOCKED;
}
/**
* Don't use this - for internal use only
*/
public void forceUnlock() {
throwExceptionIfClosed();
if (locked())
forceUnlock(lockedBy());
}
/**
* Don't use this - for internal use only
* Does not warn when force unlocked
*/
@Deprecated(/* to be removed in x.26. No replacement provided - use forceUnlock */)
public void forceUnlockQuietly() {
lock.setValue(UNLOCKED);
}
} |
//noinspection ConstantConditions,AssertWithSideEffects
assert SKIP_ASSERTIONS ||
((lockedByThread = Thread.currentThread()) != null && (lockedHere = new StackTrace()) != null);
| 1,351 | 58 | 1,409 |
234 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/ThreadLocalAppender.java | ThreadLocalAppender | acquireThreadLocalAppender | class ThreadLocalAppender {
private ThreadLocalAppender() {
// Intentional no-op
}
/**
* Returns a ExcerptAppender for the given ChronicleQueue that is local to the current Thread.
* <p>
* An Appender can be used to store new excerpts sequentially to the queue.
* <p>
* <b>
* An Appender is <em>NOT thread-safe</em> and, in addition to that, confined to be used <em>by the creating thread only.</em>.
* Sharing an Appender across threads is unsafe and will inevitably lead to errors and unspecified behaviour.
* </b>
* <p>
* This method returns a {@link ThreadLocal} appender, so does not produce any garbage, hence it's safe to simply call
* this method every time an appender is needed.
*
* @return Returns a ExcerptAppender for this ChronicleQueue that is local to the current Thread
* @throws IllegalArgumentException if the queue it is passed is not an instance of {@link SingleChronicleQueue}
*/
public static ExcerptAppender acquireThreadLocalAppender(ChronicleQueue queue) {<FILL_FUNCTION_BODY>}
} |
if (!(queue instanceof SingleChronicleQueue)) {
throw new IllegalArgumentException("acquireThreadLocalAppender only accepts instances of SingleChronicleQueue");
}
SingleChronicleQueue singleChronicleQueue = (SingleChronicleQueue) queue;
return singleChronicleQueue.acquireThreadLocalAppender(singleChronicleQueue);
| 317 | 87 | 404 |
235 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/single/namedtailer/IndexUpdaterFactory.java | IndexUpdaterFactory | createIndexUpdater | class IndexUpdaterFactory {
/**
* Create an instance of an {@link IndexUpdater} depending on the values provided.
*/
@Nullable
public static IndexUpdater createIndexUpdater(@Nullable String tailerName, @NotNull SingleChronicleQueue queue) {<FILL_FUNCTION_BODY>}
/**
* An index updater that simply sets the index value on update. No versioning.
*/
public static class StandardIndexUpdater implements IndexUpdater, Closeable {
private final LongValue indexValue;
public StandardIndexUpdater(@NotNull LongValue indexValue) {
this.indexValue = indexValue;
}
@Override
public void close() throws IOException {
closeQuietly(indexValue);
}
@Override
public void update(long index) {
indexValue.setValue(index);
}
@Override
public LongValue index() {
return indexValue;
}
}
/**
* An index updater that increments a version field on every update.
*/
public static class VersionedIndexUpdater implements IndexUpdater, Closeable {
private final TableStoreWriteLock versionIndexLock;
private final LongValue indexValue;
private final LongValue indexVersionValue;
public VersionedIndexUpdater(@NotNull String tailerName,
@NotNull SingleChronicleQueue queue,
@NotNull LongValue indexValue,
@NotNull LongValue indexVersionValue) {
this.versionIndexLock = queue.versionIndexLockForId(tailerName);
this.versionIndexLock.forceUnlockIfProcessIsDead();
this.indexValue = indexValue;
this.indexVersionValue = indexVersionValue;
}
@Override
public void close() throws IOException {
closeQuietly(versionIndexLock, indexValue, indexVersionValue);
}
@Override
public void update(long index) {
try {
versionIndexLock.lock();
indexValue.setVolatileValue(index);
indexVersionValue.addAtomicValue(1);
} finally {
versionIndexLock.unlock();
}
}
@Override
public LongValue index() {
return indexValue;
}
}
} |
if (tailerName == null) {
// A null index updater is used when a plain (unnamed) tailer is in use
// Note this nullness is not ideal and needs to be tackled in a future refactor of StoreTailer
return null;
} else if (tailerName.startsWith(SingleChronicleQueue.REPLICATED_NAMED_TAILER_PREFIX)) {
// Replicated named tailers use an additional version field updated on each index mutation
return new VersionedIndexUpdater(
tailerName,
queue,
queue.indexForId(tailerName),
queue.indexVersionForId(tailerName)
);
} else {
// Normal named tailers use a simple unversioned scheme
return new StandardIndexUpdater(queue.indexForId(tailerName));
}
| 570 | 215 | 785 |
236 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/table/AbstractTSQueueLock.java | AbstractTSQueueLock | forceUnlockIfProcessIsDead | class AbstractTSQueueLock extends AbstractCloseable implements Closeable {
protected static final String UNLOCK_MAIN_MSG = ". You can manually unlock with net.openhft.chronicle.queue.main.UnlockMain";
protected static final String UNLOCKING_FORCIBLY_MSG = ". Unlocking forcibly. Note that this feature is designed to recover " +
"if another process died while holding a lock. If the other process is still alive, you may see queue corruption.";
protected static final long PID = getProcessId();
public static final long UNLOCKED = 1L << 63;
protected final UnlockMode forceUnlockOnTimeoutWhen;
protected final LongValue lock;
protected final ThreadLocal<TimingPauser> pauser;
protected final File path;
protected final TableStore tableStore;
private final String lockKey;
public AbstractTSQueueLock(final String lockKey, final TableStore<?> tableStore, final Supplier<TimingPauser> pauserSupplier) {
this.tableStore = tableStore;
this.lock = tableStore.doWithExclusiveLock(ts -> ts.acquireValueFor(lockKey));
this.pauser = ThreadLocal.withInitial(pauserSupplier);
this.path = tableStore.file();
this.lockKey = lockKey;
final boolean dontRecoverLockTimeout = Jvm.getBoolean("queue.dont.recover.lock.timeout");
if (dontRecoverLockTimeout) {
forceUnlockOnTimeoutWhen = UnlockMode.NEVER;
Jvm.warn().on(getClass(), "queue.dont.recover.lock.timeout property is deprecated and will be removed in a future version. " +
"Use queue.force.unlock.mode=NEVER instead");
} else {
forceUnlockOnTimeoutWhen = UnlockMode.valueOf(Jvm.getProperty("queue.force.unlock.mode", UnlockMode.LOCKING_PROCESS_DEAD.name()).toUpperCase());
}
singleThreadedCheckDisabled(true);
}
protected void performClose() {
Closeable.closeQuietly(lock);
}
/**
* will only force unlock if you give it the correct pid
*/
protected void forceUnlock(long value) {
boolean unlocked = lock.compareAndSwapValue(value, UNLOCKED);
Jvm.warn().on(getClass(), "" +
"Forced unlock for the " +
"lock file:" + path + ", " +
"lockKey: " + lockKey + ", " +
"unlocked: " + unlocked,
new StackTrace("Forced unlock"));
}
public boolean isLockedByCurrentProcess(LongConsumer notCurrentProcessConsumer) {
final long pid = this.lock.getVolatileValue();
// mask off thread (if used)
int realPid = (int) pid;
if (realPid == PID)
return true;
notCurrentProcessConsumer.accept(pid);
return false;
}
/**
* forces an unlock only if the process that currently holds the table store lock is no-longer running
*
* @return {@code true} if the lock was already unlocked, It will not release the lock if it is held by this process
* or the process that was holding the lock is no longer running (and we were able to unlock).
* Otherwise {@code false} is returned if the lock is held by this process or another live process.
*/
public boolean forceUnlockIfProcessIsDead() {<FILL_FUNCTION_BODY>}
/**
* @return the pid that had the locked or the returns UNLOCKED if it is not locked
*/
public long lockedBy() {
return lock.getVolatileValue();
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "{" +
"lock=" + lock +
", path=" + path +
", lockKey='" + lockKey + '\'' +
'}';
}
} |
long pid;
for (; ; ) {
pid = this.lock.getVolatileValue();
if (pid == UNLOCKED)
return true;
// mask off thread (if used)
int realPid = (int) pid;
if (!Jvm.isProcessAlive(realPid)) {
Jvm.warn().on(this.getClass(), format("Forced unlocking `%s` in lock file:%s, as this was locked by: %d which is now dead",
lockKey, this.path, realPid));
if (lock.compareAndSwapValue(pid, UNLOCKED))
return true;
} else
break;
}
if (Jvm.isDebugEnabled(this.getClass()))
// don't make this a WARN as this method should only unlock if process is dead or current process.
Jvm.debug().on(this.getClass(), format("Unable to release the lock=%s in the table store file=%s " +
"as it is being held by pid=%d, and this process is still running.", lockKey, path, pid));
return false;
| 1,012 | 283 | 1,295 |
237 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/table/ReadonlyTableStore.java | ReadonlyTableStore | bytes | class ReadonlyTableStore<T extends Metadata> extends AbstractCloseable implements TableStore<T> {
private final T metadata;
public ReadonlyTableStore(T metadata) {
this.metadata = metadata;
singleThreadedCheckDisabled(true);
}
@Override
public T metadata() {
return metadata;
}
@Override
protected void performClose() {
}
@Override
public LongValue acquireValueFor(CharSequence key, long defaultValue) {
throw new UnsupportedOperationException("Read only");
}
@Override
public <T> void forEachKey(T accumulator, TableStoreIterator<T> tsIterator) {
throw new UnsupportedOperationException("Read only");
}
@Override
public <R> R doWithExclusiveLock(Function<TableStore<T>, ? extends R> code) {
UnsupportedOperationException read_only = new UnsupportedOperationException("Read only");
throw read_only;
}
@Nullable
@Override
public File file() {
throwExceptionIfClosed();
UnsupportedOperationException read_only = new UnsupportedOperationException("Read only");
throw read_only;
}
@NotNull
@Override
public MappedBytes bytes() {<FILL_FUNCTION_BODY>}
@NotNull
@Override
public String dump() {
return metadata.toString();
}
@Override
public String dump(WireType wireType) {
return metadata.toString();
}
@NotNull
@Override
public String shortDump() {
return metadata.toString();
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
UnsupportedOperationException read_only = new UnsupportedOperationException("Read only");
throw read_only;
}
@Override
public boolean readOnly() {
return true;
}
} |
throwExceptionIfClosed();
UnsupportedOperationException read_only = new UnsupportedOperationException("Read only");
throw read_only;
| 487 | 38 | 525 |
238 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/impl/table/SingleTableBuilder.java | SingleTableBuilder | builder | class SingleTableBuilder<T extends Metadata> implements Builder<TableStore<T>> {
static {
CLASS_ALIASES.addAlias(WireType.class);
CLASS_ALIASES.addAlias(SingleTableStore.class, "STStore");
}
@NotNull
private final File file;
@NotNull
private final T metadata;
private WireType wireType;
private boolean readOnly;
private SingleTableBuilder(@NotNull File path, @NotNull T metadata) {
this.file = path;
this.metadata = metadata;
}
@NotNull
public static <T extends Metadata> SingleTableBuilder<T> builder(@NotNull File file, @NotNull WireType wireType, @NotNull T metadata) {<FILL_FUNCTION_BODY>}
@NotNull
public static <T extends Metadata> SingleTableBuilder<T> binary(@NotNull Path path, @NotNull T metadata) {
return binary(path.toFile(), metadata);
}
@NotNull
public static <T extends Metadata> SingleTableBuilder<T> binary(@NotNull String file, @NotNull T metadata) {
return binary(new File(file), metadata);
}
@NotNull
public static <T extends Metadata> SingleTableBuilder<T> binary(@NotNull File basePathFile, @NotNull T metadata) {
return builder(basePathFile, WireType.BINARY_LIGHT, metadata);
}
// *************************************************************************
//
// *************************************************************************
@NotNull
public TableStore<T> build() {
if (readOnly) {
if (!file.exists())
throw new IORuntimeException("Metadata file not found in readOnly mode");
// Wait a short time for the file to be initialized
TimingPauser pauser = Pauser.balanced();
try {
while (file.length() < OS.mapAlignment()) {
pauser.pause(1, TimeUnit.SECONDS);
}
} catch (TimeoutException e) {
throw new IORuntimeException("Metadata file found in readOnly mode, but not initialized yet");
}
}
MappedBytes bytes = null;
try {
if (!readOnly && file.createNewFile() && !file.canWrite()) {
throw new IllegalStateException("Cannot write to tablestore file " + file);
}
bytes = MappedBytes.mappedBytes(file, OS.SAFE_PAGE_SIZE, OS.SAFE_PAGE_SIZE, readOnly);
// these MappedBytes are shared, but the assumption is they shouldn't grow. Supports 2K entries.
bytes.singleThreadedCheckDisabled(true);
// eagerly initialize backing MappedFile page - otherwise wire.writeFirstHeader() will try to lock the file
// to allocate the first byte store and that will cause lock overlap
bytes.readVolatileInt(0);
Wire wire = wireType.apply(bytes);
if (readOnly)
return SingleTableStore.doWithSharedLock(file, v -> {
try {
return readTableStore(wire);
} catch (IOException ex) {
throw Jvm.rethrow(ex);
}
}, () -> null);
else {
MappedBytes finalBytes = bytes;
return SingleTableStore.doWithExclusiveLock(file, v -> {
try {
if (wire.writeFirstHeader()) {
return writeTableStore(finalBytes, wire);
} else {
return readTableStore(wire);
}
} catch (IOException ex) {
throw Jvm.rethrow(ex);
}
}, () -> null);
}
} catch (IOException e) {
throw new IORuntimeException("file=" + file.getAbsolutePath(), e);
} finally {
if (bytes != null)
bytes.singleThreadedCheckReset();
}
}
@NotNull
private TableStore<T> readTableStore(Wire wire) throws StreamCorruptedException {
wire.readFirstHeader();
final ValueIn valueIn = readTableStoreValue(wire);
@NotNull TableStore<T> existing = Objects.requireNonNull(valueIn.typedMarshallable());
metadata.overrideFrom(existing.metadata());
return existing;
}
private ValueIn readTableStoreValue(@NotNull Wire wire) throws StreamCorruptedException {
try (ScopedResource<StringBuilder> stlSb = Wires.acquireStringBuilderScoped()) {
StringBuilder name = stlSb.get();
ValueIn valueIn = wire.readEventName(name);
if (!StringUtils.isEqual(name, MetaDataKeys.header.name())) {
throw new StreamCorruptedException("The first message should be the header, was " + name);
}
return valueIn;
}
}
@NotNull
private TableStore<T> writeTableStore(MappedBytes bytes, Wire wire) {
TableStore<T> store = new SingleTableStore<>(wireType, bytes, metadata);
wire.writeEventName("header").object(store);
wire.updateFirstHeader();
return store;
}
@NotNull
@Override
@Deprecated(/* to be removed in x.26*/)
public SingleTableBuilder<T> clone() {
try {
@SuppressWarnings("unchecked")
SingleTableBuilder<T> clone = (SingleTableBuilder) super.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
@NotNull
public File file() {
return file;
}
public WireType wireType() {
return wireType;
}
public SingleTableBuilder<T> wireType(WireType wireType) {
this.wireType = wireType;
return this;
}
public boolean readOnly() {
return readOnly;
}
public SingleTableBuilder<T> readOnly(boolean readOnly) {
this.readOnly = readOnly;
return this;
}
} |
if (file.isDirectory()) {
throw new IllegalArgumentException("Tables should be configured with the table file, not a directory. Actual file used: " + file.getParentFile());
}
if (!file.getName().endsWith(SingleTableStore.SUFFIX)) {
throw new IllegalArgumentException("Invalid file type: " + file.getName());
}
return new SingleTableBuilder<>(file, metadata).wireType(wireType);
| 1,528 | 110 | 1,638 |
239 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/domestic/QueueOffsetSpec.java | QueueOffsetSpec | apply | class QueueOffsetSpec {
private static final String TOKEN_DELIMITER = ";";
private final Type type;
private final String[] spec;
private QueueOffsetSpec(final Type type, final String[] spec) {
this.type = type;
this.spec = spec;
}
public static QueueOffsetSpec ofEpoch(final long epoch) {
return new QueueOffsetSpec(Type.EPOCH, new String[]{Long.toString(epoch)});
}
public static QueueOffsetSpec ofRollTime(@NotNull final LocalTime time, @NotNull final ZoneId zoneId) {
return new QueueOffsetSpec(Type.ROLL_TIME, new String[]{time.toString(), zoneId.toString()});
}
public static QueueOffsetSpec ofNone() {
return new QueueOffsetSpec(Type.NONE, new String[]{});
}
public static QueueOffsetSpec parse(@NotNull final String definition) {
final String[] tokens = definition.split(TOKEN_DELIMITER);
final Type type = Type.valueOf(tokens[0]);
switch (type) {
case EPOCH:
expectArgs(tokens, 2);
return new QueueOffsetSpec(type, new String[]{tokens[1]});
case ROLL_TIME:
expectArgs(tokens, 3);
return new QueueOffsetSpec(type, new String[]{tokens[1], tokens[2]});
case NONE:
expectArgs(tokens, 1);
return new QueueOffsetSpec(type, new String[]{});
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
}
public static String formatEpochOffset(final long epochOffset) {
return String.format("%s;%s", Type.EPOCH.name(), epochOffset);
}
public static String formatRollTime(final LocalTime time, final ZoneId zoneId) {
return String.format("%s;%s;%s", Type.ROLL_TIME.name(), time.toString(), zoneId.toString());
}
public static String formatNone() {
return Type.NONE.name();
}
private static ZoneId toZoneId(final String zoneId) {
return ZoneId.of(zoneId);
}
private static LocalTime toLocalTime(final String timestamp) {
return LocalTime.parse(timestamp);
}
private static void expectArgs(final String[] tokens, final int expectedLength) {
if (tokens.length != expectedLength) {
throw new IllegalArgumentException("Expected " + expectedLength + " tokens in " + Arrays.toString(tokens));
}
}
public void apply(final SingleChronicleQueueBuilder builder) {<FILL_FUNCTION_BODY>}
public String format() {
return type.name() + TOKEN_DELIMITER + type.argFormatter.apply(spec);
}
public void validate() {
switch (type) {
case EPOCH:
Long.parseLong(spec[0]);
break;
case ROLL_TIME:
toLocalTime(spec[0]);
toZoneId(spec[1]);
break;
case NONE:
break;
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
}
public enum Type {
EPOCH(args -> args[0]),
ROLL_TIME(args -> args[0] + TOKEN_DELIMITER + args[1]),
NONE(args -> "");
private final Function<String[], String> argFormatter;
Type(final Function<String[], String> argFormatter) {
this.argFormatter = argFormatter;
}
}
} |
switch (type) {
case EPOCH:
builder.epoch(Long.parseLong(spec[0]));
break;
case ROLL_TIME:
builder.rollTime(toLocalTime(spec[0]), toZoneId(spec[1]));
break;
case NONE:
break;
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
| 951 | 106 | 1,057 |
240 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/main/InternalBenchmarkMain.java | InternalBenchmarkMain | benchmark | class InternalBenchmarkMain {
static volatile boolean running = true;
static int throughput = Integer.getInteger("throughput", 250); // MB/s
static int runtime = Integer.getInteger("runtime", 300); // seconds
static String basePath = System.getProperty("path", OS.TMP);
static volatile long readerLoopTime = 0;
static volatile long readerEndLoopTime = 0;
static int counter = 0;
static {
System.setProperty("jvm.safepoint.enabled", "true");
}
public static void main(String[] args) {
System.out.println(
"-Dthroughput=" + throughput
+ " -Druntime=" + runtime
+ " -Dpath=" + basePath);
MappedFile.warmup();
System.out.println("Warming up");
benchmark(128);
System.out.println("Warmed up");
for (int size = 64; size <= 16 << 20; size *= 4) {
benchmark(size);
}
}
static void benchmark(int messageSize) {<FILL_FUNCTION_BODY>}
private static void runInner(Histogram transportTime, Histogram readTime, ExcerptTailer tailer) {
Jvm.safepoint();
/*if (tailer.peekDocument()) {
if (counter++ < 1000) {
Jvm.safepoint();
return;
}
}*/
if (counter > 0)
Jvm.safepoint();
else
Jvm.safepoint();
counter = 0;
try (DocumentContext dc = tailer.readingDocument(false)) {
Jvm.safepoint();
if (!dc.isPresent()) {
return;
}
long transport = System.nanoTime();
Jvm.safepoint();
Wire wire = dc.wire();
Bytes<?> bytes = wire.bytes();
long start = readMessage(bytes);
long end = System.nanoTime();
transportTime.sample((double) (transport - start));
readTime.sample((double) (end - transport));
}
Jvm.safepoint();
}
@NotNull
private static ChronicleQueue createQueue(String path) {
return ChronicleQueue.singleBuilder(path)
.blockSize(1 << 30)
.pauserSupplier(Pauser::timedBusy)
.build();
}
private static long readMessage(Bytes<?> bytes) {
Jvm.safepoint();
long start = bytes.readLong();
long rp = bytes.readPosition();
long rl = bytes.readLimit();
long addr = bytes.addressForRead(rp);
long addrEnd = bytes.addressForRead(rl);
Memory memory = OS.memory();
for (addr += 8; addr + 7 < addrEnd; addr += 8)
memory.readLong(addr);
Jvm.safepoint();
return start;
}
private static void writeMessage(Wire wire, int messageSize) {
Bytes<?> bytes = wire.bytes();
long wp = bytes.writePosition();
long addr = bytes.addressForWrite(wp);
Memory memory = OS.memory();
for (int i = 0; i < messageSize; i += 16) {
memory.writeLong(addr + i, 0L);
memory.writeLong(addr + i + 8, 0L);
}
bytes.writeSkip(messageSize);
bytes.writeLong(wp, System.nanoTime());
}
} |
Histogram writeTime = new Histogram(32, 7);
Histogram transportTime = new Histogram(32, 7);
Histogram readTime = new Histogram(32, 7);
String path = basePath + "/test-q-" + messageSize;
ChronicleQueue queue = createQueue(path);
// Pretoucher will only work with Queue Enterprise in the path
Thread pretoucher = new Thread(() -> {
try (ExcerptAppender appender = queue.createAppender()) {
Thread thread = Thread.currentThread();
while (!thread.isInterrupted()) {
appender.pretouch();
Jvm.pause(10);
}
}
});
pretoucher.setDaemon(true);
pretoucher.start();
Histogram loopTime = new Histogram();
Thread reader = new Thread(() -> {
// try (ChronicleQueue queue2 = createQueue(path))
ExcerptTailer tailer = queue.createTailer().toEnd();
long endLoop = System.nanoTime();
while (running) {
loopTime.sample((double) (System.nanoTime() - endLoop));
Jvm.safepoint();
// readerLoopTime = System.nanoTime();
// if (readerLoopTime - readerEndLoopTime > 1000)
// System.out.println("r " + (readerLoopTime - readerEndLoopTime));
// try {
runInner(transportTime, readTime, tailer);
runInner(transportTime, readTime, tailer);
runInner(transportTime, readTime, tailer);
runInner(transportTime, readTime, tailer);
// } finally {
// readerEndLoopTime = System.nanoTime();
// }
Jvm.safepoint();
endLoop = System.nanoTime();
}
});
reader.start();
Jvm.pause(250); // give the reader time to start
long next = System.nanoTime();
long end = (long) (next + runtime * 1e9);
ExcerptAppender appender = queue.createAppender();
while (end > System.nanoTime()) {
long start = System.nanoTime();
try (DocumentContext dc = appender.writingDocument(false)) {
writeMessage(dc.wire(), messageSize);
}
long written = System.nanoTime();
long time = written - start;
// System.out.println(time);
writeTime.sample(time);
long diff = writeTime.totalCount() - readTime.totalCount();
Thread.yield();
if (diff >= 200) {
// long rlt = readerLoopTime;
// long delay = System.nanoTime() - rlt;
System.out.println("diff=" + diff /* +" delay= " + delay*/);
StringBuilder sb = new StringBuilder();
sb.append("Reader: profile of the thread");
Jvm.trimStackTrace(sb, reader.getStackTrace());
System.out.println(sb);
}
next += messageSize * 1e9 / (throughput * 1e6);
long delay = next - System.nanoTime();
if (delay > 0)
LockSupport.parkNanos(delay);
}
while (readTime.totalCount() < writeTime.totalCount())
Jvm.pause(50);
pretoucher.interrupt();
reader.interrupt();
running = false;
// monitor.interrupt();
System.out.println("Loop times " + loopTime.toMicrosFormat());
System.out.println("messageSize " + messageSize);
System.out.println("messages " + writeTime.totalCount());
System.out.println("write histogram: " + writeTime.toMicrosFormat());
System.out.println("transport histogram: " + transportTime.toMicrosFormat());
System.out.println("read histogram: " + readTime.toMicrosFormat());
IOTools.deleteDirWithFiles(path, 2);
Jvm.pause(1000);
| 933 | 1,060 | 1,993 |
241 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/main/InternalDumpMain.java | InternalDumpMain | dump | class InternalDumpMain {
private static final String FILE = System.getProperty("file");
private static final boolean SKIP_TABLE_STORE = Jvm.getBoolean("skipTableStoreDump");
private static final boolean UNALIGNED = Jvm.getBoolean("dumpUnaligned");
private static final int LENGTH = ", 0".length();
static {
SingleChronicleQueueBuilder.addAliases();
}
public static void main(String[] args) throws FileNotFoundException {
dump(args[0]);
}
public static void dump(@NotNull String path) throws FileNotFoundException {
File path2 = new File(path);
PrintStream out = FILE == null ? System.out : new PrintStream(FILE);
long upperLimit = Long.MAX_VALUE;
dump(path2, out, upperLimit);
}
public static void dump(@NotNull File path, @NotNull PrintStream out, long upperLimit) {<FILL_FUNCTION_BODY>}
private static void dumpFile(@NotNull File file, @NotNull PrintStream out, long upperLimit) {
Bytes<ByteBuffer> buffer = Bytes.elasticByteBuffer();
try (MappedBytes bytes = MappedBytes.mappedBytes(file, 4 << 20, OS.pageSize(), !OS.isWindows())) {
bytes.readLimit(bytes.realCapacity());
StringBuilder sb = new StringBuilder();
WireDumper dumper = WireDumper.of(bytes, !UNALIGNED);
while (bytes.readRemaining() >= 4) {
sb.setLength(0);
boolean last = dumper.dumpOne(sb, buffer);
if (sb.indexOf("\nindex2index:") != -1 || sb.indexOf("\nindex:") != -1) {
// truncate trailing zeros
if (sb.indexOf(", 0\n]\n") == sb.length() - 6) {
int i = indexOfLastZero(sb);
if (i < sb.length())
sb.setLength(i - 5);
sb.append(" # truncated trailing zeros\n]");
}
}
out.println(sb);
if (last)
break;
if (bytes.readPosition() > upperLimit) {
out.println("# limit reached.");
return;
}
}
} catch (IOException ioe) {
err.println("Failed to read " + file + " " + ioe);
} finally {
buffer.releaseLast();
}
}
private static int indexOfLastZero(@NotNull CharSequence str) {
int i = str.length() - 3;
do {
i -= LENGTH;
CharSequence charSequence = str.subSequence(i, i + 3);
if (!", 0".contentEquals(charSequence))
return i + LENGTH;
} while (i > 3);
return 0;
}
} |
if (path.isDirectory()) {
final FilenameFilter filter =
SKIP_TABLE_STORE
? (d, n) -> n.endsWith(SingleChronicleQueue.SUFFIX)
: (d, n) -> n.endsWith(SingleChronicleQueue.SUFFIX) || n.endsWith(SingleTableStore.SUFFIX);
File[] files = path.listFiles(filter);
if (files == null) {
err.println("Directory not found " + path);
System.exit(1);
}
Arrays.sort(files);
for (File file : files) {
out.println("## " + file);
dumpFile(file, out, upperLimit);
}
} else if (path.getName().endsWith(SingleChronicleQueue.SUFFIX) || path.getName().endsWith(SingleTableStore.SUFFIX)) {
dumpFile(path, out, upperLimit);
}
| 740 | 243 | 983 |
242 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/main/InternalPingPongMain.java | InternalPingPongMain | pingPong | class InternalPingPongMain {
// static int throughput = Integer.getInteger("throughput", 250); // MB/s
static int runtime = Integer.getInteger("runtime", 30); // seconds
static String basePath = System.getProperty("path", OS.TMP);
static AtomicLong writeTime = new AtomicLong();
static AtomicInteger writeCount = new AtomicInteger();
static AtomicInteger readCount = new AtomicInteger();
static AtomicBoolean running = new AtomicBoolean(true);
static {
System.setProperty("jvm.safepoint.enabled", "true");
}
public static void main(String[] args) {
System.out.println(
// "-Dthroughput=" + throughput
" -Druntime=" + runtime
+ " -Dpath=" + basePath);
MappedFile.warmup();
pingPong(64);
}
static void pingPong(int size) {<FILL_FUNCTION_BODY>}
@NotNull
private static ChronicleQueue createQueue(String path) {
return ChronicleQueue.single(path);
}
} |
String path = InternalPingPongMain.basePath + "/test-q-" + Time.uniqueId();
Histogram readDelay = new Histogram();
Histogram readDelay2 = new Histogram();
try (ChronicleQueue queue = createQueue(path)) {
Thread reader = new Thread(() -> {
ExcerptTailer tailer = queue.createTailer();
while (running.get()) {
//noinspection StatementWithEmptyBody
while (readCount.get() == writeCount.get()) ;
long wakeTime = System.nanoTime();
while (running.get()) {
try (DocumentContext dc = tailer.readingDocument(true)) {
if (!dc.isPresent())
continue;
}
break;
}
final long delay = wakeTime - writeTime.get();
final long time = System.nanoTime() - wakeTime;
readDelay2.sample(time);
readDelay.sample(delay);
if (time + delay > 20_000)
System.out.println("td " + delay + " + " + time);
if (readCount.get() == 100000) {
System.out.println("reset");
readDelay.reset();
readDelay2.reset();
}
readCount.incrementAndGet();
}
});
reader.setDaemon(true);
reader.start();
Jvm.pause(100);
final long finish = System.currentTimeMillis() + runtime * 1000L;
final ExcerptAppender appender = queue.createAppender();
while (System.currentTimeMillis() < finish) {
if (readCount.get() < writeCount.get()) {
Thread.yield();
continue;
}
try (DocumentContext dc = appender.writingDocument(false)) {
dc.wire().bytes().writeSkip(size);
}
writeCount.incrementAndGet();
writeTime.set(System.nanoTime());
}
running.set(false);
}
System.out.println("read delay: " + readDelay.toMicrosFormat());
System.out.println("read delay2: " + readDelay2.toMicrosFormat());
IOTools.deleteDirWithFiles(path, 2);
| 296 | 589 | 885 |
243 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/main/InternalRemovableRollFileCandidatesMain.java | InternalRemovableRollFileCandidatesMain | main | class InternalRemovableRollFileCandidatesMain {
/**
* Produces a list of removable roll file candidates and prints
* their absolute path to standard out row-by-row.
*
* @param args the directory. If no directory is given, "." is assumed
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
final File dir;
if (args.length == 0) {
dir = new File(".");
} else {
dir = new File(args[0]);
}
FileUtil.removableRollFileCandidates(dir)
.map(File::getAbsolutePath)
.forEach(System.out::println);
| 98 | 87 | 185 |
244 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/main/InternalUnlockMain.java | InternalUnlockMain | unlock | class InternalUnlockMain {
static {
SingleChronicleQueueBuilder.addAliases();
}
public static void main(String[] args) {
unlock(args[0]);
}
private static void unlock(@NotNull String dir) {<FILL_FUNCTION_BODY>}
} |
File path = new File(dir);
if (!path.isDirectory()) {
System.err.println("Path argument must be a queue directory");
System.exit(1);
}
File storeFilePath = new File(path, QUEUE_METADATA_FILE);
if (!storeFilePath.exists()) {
System.err.println("Metadata file not found, nothing to unlock");
System.exit(1);
}
final TableStore<?> store = SingleTableBuilder.binary(storeFilePath, Metadata.NoMeta.INSTANCE).readOnly(false).build();
// appender lock
(new TableStoreWriteLock(store, BusyTimedPauser::new, 0L, TableStoreWriteLock.APPEND_LOCK_KEY)).forceUnlock();
// write lock
(new TableStoreWriteLock(store, BusyTimedPauser::new, 0L)).forceUnlock();
System.out.println("Done");
| 78 | 245 | 323 |
245 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/InternalDummyMethodReaderQueueEntryHandler.java | InternalDummyMethodReaderQueueEntryHandler | accept | class InternalDummyMethodReaderQueueEntryHandler implements QueueEntryHandler {
private final Bytes<?> textConversionTarget = Bytes.allocateElasticOnHeap();
private final WireType wireType;
public InternalDummyMethodReaderQueueEntryHandler(@NotNull WireType wireType) {
this.wireType = requireNonNull(wireType);
}
@Override
public void accept(final WireIn wireIn, final Consumer<String> messageHandler) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
textConversionTarget.releaseLast();
}
} |
long elementCount = 0;
while (wireIn.hasMore()) {
new BinaryWire(wireIn.bytes()).copyOne(wireType.apply(textConversionTarget));
elementCount++;
if ((elementCount & 1) == 0) {
messageHandler.accept(textConversionTarget.toString());
textConversionTarget.clear();
}
}
| 156 | 98 | 254 |
246 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/InternalMessageToTextQueueEntryHandler.java | InternalMessageToTextQueueEntryHandler | accept | class InternalMessageToTextQueueEntryHandler implements QueueEntryHandler {
private final Bytes<?> textConversionTarget = Bytes.allocateElasticOnHeap();
private final WireType wireType;
public InternalMessageToTextQueueEntryHandler(WireType wireType) {
this.wireType = requireNonNull(wireType);
}
private static boolean isBinaryFormat(final byte dataFormatIndicator) {
return dataFormatIndicator < 0;
}
@Override
public void accept(final WireIn wireIn, final Consumer<String> messageHandler) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
textConversionTarget.releaseLast();
}
} |
final Bytes<?> serialisedMessage = wireIn.bytes();
final byte dataFormatIndicator = serialisedMessage.readByte(serialisedMessage.readPosition());
String text;
if (isBinaryFormat(dataFormatIndicator)) {
textConversionTarget.clear();
final BinaryWire binaryWire = new BinaryWire(serialisedMessage);
binaryWire.copyTo(wireType.apply(textConversionTarget));
text = textConversionTarget.toString();
} else {
text = serialisedMessage.toString();
}
messageHandler.accept(text);
| 186 | 153 | 339 |
247 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/MessageCountingMessageConsumer.java | MessageCountingMessageConsumer | consume | class MessageCountingMessageConsumer implements MessageConsumer {
private final long matchLimit;
private final MessageConsumer wrappedConsumer;
private long matches = 0;
/**
* Constructor
*
* @param matchLimit The limit used to determine {@link #matchLimitReached()}
* @param wrappedConsumer The downstream consumer to pass messages to
*/
public MessageCountingMessageConsumer(long matchLimit, MessageConsumer wrappedConsumer) {
this.matchLimit = matchLimit;
this.wrappedConsumer = wrappedConsumer;
}
@Override
public boolean consume(long index, String message) {<FILL_FUNCTION_BODY>}
public boolean matchLimitReached() {
return matchLimit > 0 && matches >= matchLimit;
}
} |
final boolean consume = wrappedConsumer.consume(index, message);
if (consume) {
matches++;
}
return consume;
| 190 | 40 | 230 |
248 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/PatternFilterMessageConsumer.java | PatternFilterMessageConsumer | consume | class PatternFilterMessageConsumer implements MessageConsumer {
private final List<Pattern> patterns;
private final boolean shouldBePresent;
private final MessageConsumer nextMessageConsumer;
/**
* Constructor
*
* @param patterns The list of patterns to match against
* @param shouldBePresent true if we require all the patterns to match, false if we require none of the patterns to match
* @param nextMessageConsumer The next message consumer in line, messages that pass the filter will be passed to it
*/
public PatternFilterMessageConsumer(List<Pattern> patterns, boolean shouldBePresent, MessageConsumer nextMessageConsumer) {
this.patterns = patterns;
this.shouldBePresent = shouldBePresent;
this.nextMessageConsumer = nextMessageConsumer;
}
@Override
public boolean consume(long index, String message) {<FILL_FUNCTION_BODY>}
} |
for (Pattern pattern : patterns) {
if (shouldBePresent != pattern.matcher(message).find()) {
return false;
}
}
return nextMessageConsumer.consume(index, message);
| 219 | 57 | 276 |
249 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/queueentryreaders/AbstractTailerPollingQueueEntryReader.java | AbstractTailerPollingQueueEntryReader | read | class AbstractTailerPollingQueueEntryReader implements QueueEntryReader {
private final ExcerptTailer tailer;
private final Function<ExcerptTailer, DocumentContext> pollMethod;
protected AbstractTailerPollingQueueEntryReader(ExcerptTailer tailer, Function<ExcerptTailer, DocumentContext> pollMethod) {
this.tailer = tailer;
this.pollMethod = pollMethod;
}
@Override
public final boolean read() {<FILL_FUNCTION_BODY>}
protected abstract void doRead(DocumentContext documentContext);
} |
try (DocumentContext dc = pollMethod.apply(tailer)) {
if (!dc.isPresent()) {
return false;
}
doRead(dc);
return true;
}
| 154 | 54 | 208 |
250 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/queueentryreaders/MethodReaderQueueEntryReader.java | MethodReaderQueueEntryReader | read | class MethodReaderQueueEntryReader implements QueueEntryReader {
private final ExcerptTailer tailer;
private final MessageConsumer messageConsumer;
private final MethodReader methodReader;
private final Bytes<ByteBuffer> bytes;
public MethodReaderQueueEntryReader(ExcerptTailer tailer, MessageConsumer messageConsumer, WireType wireType, Class<?> methodReaderInterface, boolean showMessageHistory) {
this.tailer = tailer;
this.messageConsumer = messageConsumer;
bytes = Bytes.elasticHeapByteBuffer(256);
Wire wire = wireType.apply(bytes);
if (wire instanceof TextWire)
((TextWire) wire).useTextDocuments();
MethodWriterBuilder<?> mwb = wire.methodWriterBuilder(methodReaderInterface);
if (showMessageHistory)
mwb.updateInterceptor((methodName, t) -> {
MessageHistory messageHistory = MessageHistory.get();
// this is an attempt to recognise that no MH was read and instead the method reader called reset(...) on it
if (messageHistory.sources() != 1 || messageHistory.timings() != 1)
bytes.append(messageHistory + System.lineSeparator());
return true;
});
methodReader = tailer.methodReader(mwb.build());
}
@Override
public boolean read() {<FILL_FUNCTION_BODY>}
} |
if (!methodReader.readOne()) {
return false;
}
messageConsumer.consume(tailer.lastReadIndex(), bytes.toString());
bytes.clear();
return true;
| 354 | 52 | 406 |
251 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/reader/queueentryreaders/VanillaQueueEntryReader.java | VanillaQueueEntryReader | read | class VanillaQueueEntryReader implements QueueEntryReader {
private final ExcerptTailer tailer;
private final Function<ExcerptTailer, DocumentContext> pollMethod;
private final QueueEntryHandler messageConverter;
private final MessageConsumer messageConsumer;
public VanillaQueueEntryReader(@NotNull ExcerptTailer tailer, @NotNull Function<ExcerptTailer, DocumentContext> pollMethod,
@NotNull QueueEntryHandler messageConverter, @NotNull MessageConsumer messageConsumer) {
this.tailer = tailer;
this.pollMethod = pollMethod;
this.messageConverter = messageConverter;
this.messageConsumer = messageConsumer;
}
@Override
public boolean read() {<FILL_FUNCTION_BODY>}
} |
try (DocumentContext dc = pollMethod.apply(tailer)) {
if (!dc.isPresent()) {
return false;
}
messageConverter.accept(dc.wire(), val -> messageConsumer.consume(dc.index(), val));
return true;
}
| 192 | 74 | 266 |
252 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/util/InternalFileUtil.java | ProcFdWalker | visitFile | class ProcFdWalker extends SimpleFileVisitor<Path> {
private final Set<String> openFiles = new HashSet<>();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {<FILL_FUNCTION_BODY>}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// we definitely won't be able to access all the files, and it's common for a file to go missing mid-traversal
// so don't log when one of those things happens
if (!((exc instanceof AccessDeniedException) || (exc instanceof NoSuchFileException))) {
Jvm.warn().on(ProcFdWalker.class, "Error visiting file", exc);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (!dir.toAbsolutePath().toString().matches("/proc(/\\d+(/fd)?)?")) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
} |
if (file.toAbsolutePath().toString().matches("/proc/\\d+/fd/\\d+")) {
try {
final String e = file.toRealPath().toAbsolutePath().toString();
openFiles.add(e);
} catch (NoSuchFileException | AccessDeniedException e) {
// Ignore, sometimes they disappear & we can't access all the files
} catch (IOException e) {
Jvm.warn().on(ProcFdWalker.class, "Error resolving " + file, e);
}
}
return FileVisitResult.CONTINUE;
| 289 | 153 | 442 |
253 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/writer/ChronicleWriter.java | ChronicleWriter | asMethodWriter | class ChronicleWriter {
private Path basePath;
private String methodName;
private List<String> files;
private Class<?> writeTo;
public void execute() throws IOException {
try (final ChronicleQueue queue = ChronicleQueue.singleBuilder(this.basePath).build();
final ExcerptAppender appender = queue.createAppender()) {
for (final String file : files) {
final Object payload = Marshallable.fromFile(Object.class, file);
try (final DocumentContext dc = appender.writingDocument()) {
if (writeTo != null)
dc.wire().write(methodName).marshallable((WriteMarshallable) payload);
else
dc.wire().write(methodName).object(payload);
}
}
}
}
/**
* Chronicle queue base path
* @param path path of queue to write to
* @return this
*/
public ChronicleWriter withBasePath(final Path path) {
this.basePath = path;
return this;
}
/**
* Interface class to use to write via
* @param interfaceName interface
* @return this
*/
public ChronicleWriter asMethodWriter(String interfaceName) {<FILL_FUNCTION_BODY>}
/**
* Specify method name to write each message out as
* @param methodName method name
* @return this
*/
public ChronicleWriter withMethodName(String methodName) {
this.methodName = methodName;
return this;
}
/**
* List of files to read and, for each, write out a message preceded by {@link #methodName}
* @param files files
* @return this
*/
public ChronicleWriter withFiles(List<String> files) {
this.files = files;
return this;
}
} |
try {
this.writeTo = Class.forName(interfaceName);
} catch (ClassNotFoundException e) {
throw Jvm.rethrow(e);
}
return this;
| 474 | 52 | 526 |
254 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/internal/writer/ChronicleWriterMain.java | ChronicleWriterMain | printHelpAndExit | class ChronicleWriterMain {
public void run(@NotNull String[] args) throws Exception {
final Options options = options();
final CommandLine commandLine = parseCommandLine(args, options);
final ChronicleWriter writer = new ChronicleWriter();
configure(writer, commandLine);
writer.execute();
}
private CommandLine parseCommandLine(final @NotNull String[] args, final Options options) {
final CommandLineParser parser = new DefaultParser();
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption('h')) {
printHelpAndExit(options, 0, null);
}
if (commandLine.getArgList().isEmpty()) {
printHelpAndExit(options, 1, "Need files...");
}
} catch (ParseException e) {
printHelpAndExit(options, 1, e.getMessage());
}
return commandLine;
}
private void printHelpAndExit(final Options options, int status, String message) {<FILL_FUNCTION_BODY>}
private void configure(final ChronicleWriter writer, final CommandLine commandLine) {
writer.withBasePath(Paths.get(commandLine.getOptionValue('d')));
writer.withMethodName(commandLine.getOptionValue('m'));
if (commandLine.hasOption('i')) {
final String r = commandLine.getOptionValue('i');
writer.asMethodWriter(r.equals("null") ? null : r);
}
writer.withFiles(commandLine.getArgList());
}
@NotNull
private Options options() {
final Options options = new Options();
addOption(options, "m", "method", true, "Method name", true);
addOption(options, "d", "directory", true, "Directory containing chronicle queue to write to", true);
addOption(options, "i", "interface", true, "Interface to write via", false);
return options;
}
} |
final PrintWriter writer = new PrintWriter(System.out);
new HelpFormatter().printHelp(
writer,
180,
this.getClass().getSimpleName() + " files..",
message,
options,
HelpFormatter.DEFAULT_LEFT_PAD,
HelpFormatter.DEFAULT_DESC_PAD,
null,
true
);
writer.flush();
System.exit(status);
| 510 | 114 | 624 |
255 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/rollcycles/RollCycleArithmetic.java | RollCycleArithmetic | toIndex | class RollCycleArithmetic {
/**
* Sunday 1970 Jan 4th 00:00:00 UTC
*/
public static final int SUNDAY_00_00 = 259_200_000;
private final int cycleShift;
private final int indexCount;
private final int indexSpacing;
private final long sequenceMask;
public static RollCycleArithmetic of(int indexCount, int indexSpacing) {
return new RollCycleArithmetic(indexCount, indexSpacing);
}
private RollCycleArithmetic(int indexCount, int indexSpacing) {
this.indexCount = Maths.nextPower2(indexCount, 8);
assert this.indexCount <= MAX_INDEX_COUNT : "indexCount: " + indexCount;
this.indexSpacing = Maths.nextPower2(indexSpacing, 1);
cycleShift = Math.max(32, Maths.intLog2(indexCount) * 2 + Maths.intLog2(indexSpacing));
assert cycleShift < Long.SIZE : "cycleShift: " + cycleShift;
sequenceMask = (1L << cycleShift) - 1;
}
public long maxMessagesPerCycle() {
return Math.min(sequenceMask, ((long) indexCount * indexCount * indexSpacing));
}
public long toIndex(int cycle, long sequenceNumber) {<FILL_FUNCTION_BODY>}
public long toSequenceNumber(long index) {
return index & sequenceMask;
}
public int toCycle(long index) {
return Maths.toUInt31(index >> cycleShift);
}
public int indexSpacing() {
return indexSpacing;
}
public int indexCount() {
return indexCount;
}
} |
return ((long) cycle << cycleShift) + (sequenceNumber & sequenceMask);
| 463 | 22 | 485 |
256 | OpenHFT_Chronicle-Queue | Chronicle-Queue/src/main/java/net/openhft/chronicle/queue/util/ToolsUtil.java | ToolsUtil | warnIfResourceTracing | class ToolsUtil {
private ToolsUtil() {
}
/**
* When running tools e.g. ChronicleReader, from the CQ source dir, resource tracing may be turned on
*/
public static void warnIfResourceTracing() {<FILL_FUNCTION_BODY>}
} |
// System.err (*not* logger as slf4j may not be set up e.g. when running queue_reader.sh)
if (Jvm.isResourceTracing())
System.err.println("Resource tracing is turned on - this will eventually die with OOME");
| 77 | 70 | 147 |
257 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/ActionEnter.java | ActionEnter | getStartIndex | class ActionEnter {
private HttpServletRequest request = null;
private String rootPath = null;
private String contextPath = null;
private String actionType = null;
private ConfigManager configManager = null;
public ActionEnter ( HttpServletRequest request, String rootPath, String userId) {
this.request = request;
this.rootPath = rootPath;
this.actionType = request.getParameter( "action" );
this.contextPath = request.getContextPath();
this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI(), userId );
}
public String exec () {
String callbackName = this.request.getParameter("callback");
if ( callbackName != null ) {
if ( !validCallbackName( callbackName ) ) {
return new BaseState( false, AppInfo.ILLEGAL ).toJSONString();
}
String ww = callbackName+"("+this.invoke()+");";
return ww;
} else {
return this.invoke();
}
}
public String invoke() {
if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
}
if ( this.configManager == null || !this.configManager.valid() ) {
return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
}
State state = null;
int actionCode = ActionMap.getType( this.actionType );
Map<String, Object> conf = null;
switch ( actionCode ) {
case ActionMap.CONFIG:
String config = this.configManager.getAllConfig().toString();
return config;
case ActionMap.UPLOAD_IMAGE:
case ActionMap.UPLOAD_SCRAWL:
case ActionMap.UPLOAD_VIDEO:
case ActionMap.UPLOAD_FILE:
conf = this.configManager.getConfig( actionCode );
state = new Uploader( request, conf ).doExec();
break;
case ActionMap.CATCH_IMAGE:
conf = configManager.getConfig( actionCode );
String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
state = new ImageHunter( conf ).capture( list );
break;
case ActionMap.LIST_IMAGE:
case ActionMap.LIST_FILE:
conf = configManager.getConfig( actionCode );
int start = this.getStartIndex();
state = new FileManager( conf ).listFile( start );
break;
}
System.out.println("upload state:"+state.toJSONString());
return state.toJSONString();
}
public int getStartIndex () {<FILL_FUNCTION_BODY>}
/**
* callback参数验证
*/
public boolean validCallbackName ( String name ) {
if ( name.matches( "^[a-zA-Z_]+[\\w0-9_]*$" ) ) {
return true;
}
return false;
}
} |
String start = this.request.getParameter( "start" );
try {
return Integer.parseInt( start );
} catch ( Exception e ) {
return 0;
}
| 816 | 55 | 871 |
258 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/Encoder.java | Encoder | toUnicode | class Encoder {
public static String toUnicode ( String input ) {<FILL_FUNCTION_BODY>}
} |
StringBuilder builder = new StringBuilder();
char[] chars = input.toCharArray();
for ( char ch : chars ) {
if ( ch < 256 ) {
builder.append( ch );
} else {
builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) );
}
}
return builder.toString();
| 34 | 115 | 149 |
259 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/PathFormat.java | PathFormat | parse | class PathFormat {
private static final String TIME = "time";
private static final String FULL_YEAR = "yyyy";
private static final String YEAR = "yy";
private static final String MONTH = "mm";
private static final String DAY = "dd";
private static final String HOUR = "hh";
private static final String MINUTE = "ii";
private static final String SECOND = "ss";
private static final String RAND = "rand";
private static Date currentDate = null;
public static String parse ( String input ) {<FILL_FUNCTION_BODY>}
/**
* 格式化路径, 把windows路径替换成标准路径
* @param input 待格式化的路径
* @return 格式化后的路径
*/
public static String format ( String input ) {
return input.replace( "\\", "/" );
}
public static String parse ( String input, String filename ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
Matcher matcher = pattern.matcher(input);
String matchStr = null;
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matchStr = matcher.group( 1 );
if ( matchStr.indexOf( "filename" ) != -1 ) {
filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" );
matcher.appendReplacement(sb, filename );
} else {
matcher.appendReplacement(sb, PathFormat.getString( matchStr ) );
}
}
matcher.appendTail(sb);
return sb.toString();
}
private static String getString ( String pattern ) {
pattern = pattern.toLowerCase();
// time 处理
if ( pattern.indexOf( PathFormat.TIME ) != -1 ) {
return PathFormat.getTimestamp();
} else if ( pattern.indexOf( PathFormat.FULL_YEAR ) != -1 ) {
return PathFormat.getFullYear();
} else if ( pattern.indexOf( PathFormat.YEAR ) != -1 ) {
return PathFormat.getYear();
} else if ( pattern.indexOf( PathFormat.MONTH ) != -1 ) {
return PathFormat.getMonth();
} else if ( pattern.indexOf( PathFormat.DAY ) != -1 ) {
return PathFormat.getDay();
} else if ( pattern.indexOf( PathFormat.HOUR ) != -1 ) {
return PathFormat.getHour();
} else if ( pattern.indexOf( PathFormat.MINUTE ) != -1 ) {
return PathFormat.getMinute();
} else if ( pattern.indexOf( PathFormat.SECOND ) != -1 ) {
return PathFormat.getSecond();
} else if ( pattern.indexOf( PathFormat.RAND ) != -1 ) {
return PathFormat.getRandom( pattern );
}
return pattern;
}
private static String getTimestamp () {
return System.currentTimeMillis() + "";
}
private static String getFullYear () {
return new SimpleDateFormat( "yyyy" ).format( PathFormat.currentDate );
}
private static String getYear () {
return new SimpleDateFormat( "yy" ).format( PathFormat.currentDate );
}
private static String getMonth () {
return new SimpleDateFormat( "MM" ).format( PathFormat.currentDate );
}
private static String getDay () {
return new SimpleDateFormat( "dd" ).format( PathFormat.currentDate );
}
private static String getHour () {
return new SimpleDateFormat( "HH" ).format( PathFormat.currentDate );
}
private static String getMinute () {
return new SimpleDateFormat( "mm" ).format( PathFormat.currentDate );
}
private static String getSecond () {
return new SimpleDateFormat( "ss" ).format( PathFormat.currentDate );
}
private static String getRandom ( String pattern ) {
int length = 0;
pattern = pattern.split( ":" )[ 1 ].trim();
length = Integer.parseInt( pattern );
return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length );
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
} |
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
Matcher matcher = pattern.matcher(input);
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) );
}
matcher.appendTail(sb);
return sb.toString();
| 1,184 | 151 | 1,335 |
260 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/define/BaseState.java | BaseState | toString | class BaseState implements State {
private boolean state = false;
private String info = null;
private Map<String, String> infoMap = new HashMap<String, String>();
public BaseState () {
this.state = true;
}
public BaseState ( boolean state ) {
this.setState( state );
}
public BaseState ( boolean state, String info ) {
this.setState( state );
this.info = info;
}
public BaseState ( boolean state, int infoCode ) {
this.setState( state );
this.info = AppInfo.getStateInfo( infoCode );
}
public BaseState ( boolean state, int infoCode , File tempFile) {
this.setState( state );
this.info = AppInfo.getStateInfo( infoCode );
this.tmpFile = tempFile;
}
public boolean isSuccess () {
return this.state;
}
public void setState ( boolean state ) {
this.state = state;
}
public void setInfo ( String info ) {
this.info = info;
}
public void setInfo ( int infoCode ) {
this.info = AppInfo.getStateInfo( infoCode );
}
@Override
public String toJSONString() {
return this.toString();
}
public String toString () {<FILL_FUNCTION_BODY>}
@Override
public void putInfo(String name, String val) {
this.infoMap.put(name, val);
}
@Override
public void putInfo(String name, long val) {
this.putInfo(name, val+"");
}
private File tmpFile;
public File getTmpFile() {
return tmpFile;
}
public void setTmpFile(File tmpFile) {
this.tmpFile = tmpFile;
}
} |
String key = null;
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info;
StringBuilder builder = new StringBuilder();
builder.append( "{\"state\": \"" + stateVal + "\"" );
Iterator<String> iterator = this.infoMap.keySet().iterator();
while ( iterator.hasNext() ) {
key = iterator.next();
builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" );
}
builder.append( "}" );
return Encoder.toUnicode( builder.toString() );
| 457 | 186 | 643 |
261 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/define/MultiState.java | MultiState | toJSONString | class MultiState implements State {
private boolean state = false;
private String info = null;
private Map<String, Long> intMap = new HashMap<String, Long>();
private Map<String, String> infoMap = new HashMap<String, String>();
private List<String> stateList = new ArrayList<String>();
public MultiState ( boolean state ) {
this.state = state;
}
public MultiState ( boolean state, String info ) {
this.state = state;
this.info = info;
}
public MultiState ( boolean state, int infoKey ) {
this.state = state;
this.info = AppInfo.getStateInfo( infoKey );
}
@Override
public boolean isSuccess() {
return this.state;
}
public void addState ( State state ) {
stateList.add( state.toJSONString() );
}
/**
* 该方法调用无效果
*/
@Override
public void putInfo(String name, String val) {
this.infoMap.put(name, val);
}
@Override
public String toJSONString() {<FILL_FUNCTION_BODY>}
@Override
public void putInfo(String name, long val) {
this.intMap.put( name, val );
}
} |
String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info;
StringBuilder builder = new StringBuilder();
builder.append( "{\"state\": \"" + stateVal + "\"" );
// 数字转换
Iterator<String> iterator = this.intMap.keySet().iterator();
while ( iterator.hasNext() ) {
stateVal = iterator.next();
builder.append( ",\""+ stateVal +"\": " + this.intMap.get( stateVal ) );
}
iterator = this.infoMap.keySet().iterator();
while ( iterator.hasNext() ) {
stateVal = iterator.next();
builder.append( ",\""+ stateVal +"\": \"" + this.infoMap.get( stateVal ) + "\"" );
}
builder.append( ", list: [" );
iterator = this.stateList.iterator();
while ( iterator.hasNext() ) {
builder.append( iterator.next() + "," );
}
if ( this.stateList.size() > 0 ) {
builder.deleteCharAt( builder.length() - 1 );
}
builder.append( " ]}" );
return Encoder.toUnicode( builder.toString() );
| 327 | 387 | 714 |
262 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/hunter/FileManager.java | FileManager | getAllowFiles | class FileManager {
private String dir = null;
private String rootPath = null;
private String[] allowFiles = null;
private int count = 0;
public FileManager ( Map<String, Object> conf ) {
this.rootPath = (String)conf.get( "rootPath" );
this.dir = this.rootPath + (String)conf.get( "dir" );
this.allowFiles = this.getAllowFiles( conf.get("allowFiles") );
this.count = (Integer)conf.get( "count" );
}
public State listFile ( int index ) {
File dir = new File( this.dir );
State state = null;
if ( !dir.exists() ) {
return new BaseState( false, AppInfo.NOT_EXIST );
}
if ( !dir.isDirectory() ) {
return new BaseState( false, AppInfo.NOT_DIRECTORY );
}
Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true );
if ( index < 0 || index > list.size() ) {
state = new MultiState( true );
} else {
Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count );
state = this.getState( fileList );
}
state.putInfo( "start", index );
state.putInfo( "total", list.size() );
return state;
}
private State getState ( Object[] files ) {
MultiState state = new MultiState( true );
BaseState fileState = null;
File file = null;
for ( Object obj : files ) {
if ( obj == null ) {
break;
}
file = (File)obj;
fileState = new BaseState( true );
fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) );
state.addState( fileState );
}
return state;
}
private String getPath ( File file ) {
String path = file.getAbsolutePath();
return path.replace( this.rootPath, "/" );
}
private String[] getAllowFiles ( Object fileExt ) {<FILL_FUNCTION_BODY>}
} |
String[] exts = null;
String ext = null;
if ( fileExt == null ) {
return new String[ 0 ];
}
exts = (String[])fileExt;
for ( int i = 0, len = exts.length; i < len; i++ ) {
ext = exts[ i ];
exts[ i ] = ext.replace( ".", "" );
}
return exts;
| 612 | 130 | 742 |
263 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/hunter/ImageHunter.java | ImageHunter | captureRemoteData | class ImageHunter {
private String filename = null;
private String savePath = null;
private String rootPath = null;
private List<String> allowTypes = null;
private long maxSize = -1;
private List<String> filters = null;
public ImageHunter ( Map<String, Object> conf ) {
this.filename = (String)conf.get( "filename" );
this.savePath = (String)conf.get( "savePath" );
this.rootPath = (String)conf.get( "rootPath" );
this.maxSize = (Long)conf.get( "maxSize" );
this.allowTypes = Arrays.asList( (String[])conf.get( "allowFiles" ) );
this.filters = Arrays.asList( (String[])conf.get( "filter" ) );
}
public State capture ( String[] list ) {
MultiState state = new MultiState( true );
for ( String source : list ) {
state.addState( captureRemoteData( source ) );
}
return state;
}
public State captureRemoteData ( String urlStr ) {<FILL_FUNCTION_BODY>}
private String getPath ( String savePath, String filename, String suffix ) {
return PathFormat.parse( savePath + suffix, filename );
}
private boolean validHost ( String hostname ) {
try {
InetAddress ip = InetAddress.getByName(hostname);
if (ip.isSiteLocalAddress()) {
return false;
}
} catch (UnknownHostException e) {
return false;
}
return !filters.contains( hostname );
}
private boolean validContentState ( int code ) {
return HttpURLConnection.HTTP_OK == code;
}
private boolean validFileType ( String type ) {
return this.allowTypes.contains( type );
}
private boolean validFileSize ( int size ) {
return size < this.maxSize;
}
} |
HttpURLConnection connection = null;
URL url = null;
String suffix = null;
try {
url = new URL( urlStr );
if ( !validHost( url.getHost() ) ) {
return new BaseState( false, AppInfo.PREVENT_HOST );
}
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects( true );
connection.setUseCaches( true );
if ( !validContentState( connection.getResponseCode() ) ) {
return new BaseState( false, AppInfo.CONNECTION_ERROR );
}
suffix = MIMEType.getSuffix( connection.getContentType() );
if ( !validFileType( suffix ) ) {
return new BaseState( false, AppInfo.NOT_ALLOW_FILE_TYPE );
}
if ( !validFileSize( connection.getContentLength() ) ) {
return new BaseState( false, AppInfo.MAX_SIZE );
}
String savePath = this.getPath( this.savePath, this.filename, suffix );
String physicalPath = this.rootPath + savePath;
State state = StorageManager.saveFileByInputStream( connection.getInputStream(), physicalPath );
if ( state.isSuccess() ) {
state.putInfo( "url", PathFormat.format( savePath ) );
state.putInfo( "source", urlStr );
}
return state;
} catch ( Exception e ) {
return new BaseState( false, AppInfo.REMOTE_FAIL );
}
| 534 | 428 | 962 |
264 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/upload/Base64Uploader.java | Base64Uploader | save | class Base64Uploader {
public static State save(String content, Map<String, Object> conf) {<FILL_FUNCTION_BODY>}
private static byte[] decode(String content) {
return Base64.decodeBase64(content);
}
private static boolean validSize(byte[] data, long length) {
return data.length <= length;
}
} |
byte[] data = decode(content);
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validSize(data, maxSize)) {
return new BaseState(false, AppInfo.MAX_SIZE);
}
String suffix = FileType.getSuffix("JPG");
String savePath = PathFormat.parse((String) conf.get("savePath"),
(String) conf.get("filename"));
savePath = savePath + suffix;
String physicalPath = (String) conf.get("rootPath") + savePath;
State storageState = StorageManager.saveBinaryFile(data, physicalPath);
if (storageState.isSuccess()) {
storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", "");
}
return storageState;
| 99 | 241 | 340 |
265 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/upload/BinaryUploader.java | BinaryUploader | save | class BinaryUploader {
public static final State save(HttpServletRequest request,
Map<String, Object> conf) {<FILL_FUNCTION_BODY>}
private static boolean validType(String type, String[] allowTypes) {
List<String> list = Arrays.asList(allowTypes);
return list.contains(type);
}
} |
FileItemStream fileStream = null;
boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;
if (!ServletFileUpload.isMultipartContent(request)) {
return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
}
ServletFileUpload upload = new ServletFileUpload(
new DiskFileItemFactory());
if ( isAjaxUpload ) {
upload.setHeaderEncoding( "UTF-8" );
}
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
fileStream = iterator.next();
if (!fileStream.isFormField())
break;
fileStream = null;
}
if (fileStream == null) {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
String savePath = (String) conf.get("savePath");
String originFileName = fileStream.getName();
String suffix = FileType.getSuffixByFilename(originFileName);
originFileName = originFileName.substring(0,
originFileName.length() - suffix.length());
savePath = savePath + suffix;
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
savePath = PathFormat.parse(savePath, originFileName);
String physicalPath = (String) conf.get("rootPath") + savePath;
InputStream is = fileStream.openStream();
State storageState = StorageManager.saveFileByInputStream(is,
physicalPath, maxSize);
is.close();
if (storageState.isSuccess()) {
storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName + suffix);
}
return storageState;
} catch (FileUploadException e) {
return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
} catch (IOException e) {
}
return new BaseState(false, AppInfo.IO_ERROR);
| 93 | 612 | 705 |
266 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/upload/StorageManager.java | StorageManager | saveTmpFile | class StorageManager {
public static final int BUFFER_SIZE = 8192;
public StorageManager() {
}
public static State saveBinaryFile(byte[] data, String path) {
if(!FileMagicUtils.isUserUpFileType(data,path.substring(path.lastIndexOf(".")))){
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
File file = new File(path);
State state = valid(file);
if (!state.isSuccess()) {
return state;
}
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bos.write(data);
bos.flush();
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true, file.getAbsolutePath());
state.putInfo( "size", data.length );
state.putInfo( "title", file.getName() );
return state;
}
public static State saveFileByInputStream(InputStream is, String path,
long maxSize) {
BaseState validateState = isUserUpFileType(is,path.substring(path.lastIndexOf(".")));
if(!validateState.isSuccess()) return validateState;
State state = new BaseState(false, AppInfo.IO_ERROR);
File tmpFile = validateState.getTmpFile();
if(tmpFile!=null){
state = saveTmpFile(tmpFile, path);
deleteTmpFile(tmpFile);
return state;
}
return state;
}
public static State saveFileByInputStream(InputStream is, String path) {
BaseState validateState = isUserUpFileType(is,path.substring(path.lastIndexOf(".")));
if(!validateState.isSuccess()) return validateState;
State state = new BaseState(false, AppInfo.IO_ERROR);
File tmpFile = validateState.getTmpFile();
if(tmpFile!=null){
state = saveTmpFile(tmpFile, path);
deleteTmpFile(tmpFile);
return state;
}
return state;
}
private static File getTmpFile() {
File tmpDir = FileUtils.getTempDirectory();
String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
return new File(tmpDir, tmpFileName);
}
private static State saveTmpFile(File tmpFile, String path) {<FILL_FUNCTION_BODY>}
private static State valid(File file) {
File parentPath = file.getParentFile();
if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
}
if (!parentPath.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
return new BaseState(true);
}
public static BaseState isUserUpFileType(InputStream is,String fileSuffix) {
File tmpFile = getTmpFile();
byte[] dataBuf = new byte[ 2048 ];
BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
int count = 0;
while ((count = bis.read(dataBuf)) != -1) {
bos.write(dataBuf, 0, count);
}
bis.close();
bos.flush();
bos.close();
if(!FileMagicUtils.isUserUpFileType(tmpFile,fileSuffix)){
tmpFile.delete();
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
// tmpFile.delete();
} catch (IOException e) {
e.printStackTrace();
return new BaseState(false, AppInfo.IO_ERROR);
}
return new BaseState(true, AppInfo.SUCCESS, tmpFile);
}
private static void deleteTmpFile(File tmpFile) {
try{
tmpFile.delete();
}catch (Exception e){
e.printStackTrace();
}
}
} |
State state = null;
File targetFile = new File(path);
if (targetFile.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
try {
FileUtils.moveFile(tmpFile, targetFile);
} catch (IOException e) {
e.printStackTrace();
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true);
state.putInfo( "size", targetFile.length() );
state.putInfo( "title", targetFile.getName() );
return state;
| 1,155 | 168 | 1,323 |
267 | wkeyuan_DWSurvey | DWSurvey/src/main/java/com/baidu/ueditor/upload/Uploader.java | Uploader | doExec | class Uploader {
private HttpServletRequest request = null;
private Map<String, Object> conf = null;
public Uploader(HttpServletRequest request, Map<String, Object> conf) {
this.request = request;
this.conf = conf;
}
public final State doExec() {<FILL_FUNCTION_BODY>}
} |
String filedName = (String) this.conf.get("fieldName");
State state = null;
if ("true".equals(this.conf.get("isBase64"))) {
state = Base64Uploader.save(this.request.getParameter(filedName),
this.conf);
} else {
state = BinaryUploader.save(this.request, this.conf);
}
return state;
| 89 | 113 | 202 |
268 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/base/controller/JcaptchaController.java | JcaptchaController | execute | class JcaptchaController {
@Autowired
private ImageCaptchaService imageCaptchaService;
@RequestMapping("/jcaptcha.do")
public String execute(HttpServletRequest request,HttpServletResponse response) throws Exception {<FILL_FUNCTION_BODY>}
} |
byte[] captchaChallengeAsJpeg = null;
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// get the session id that will identify the generated captcha.
// the same id must be used to validate the response, the session id
// is a good candidate!
String captchaId = request.getSession().getId();
// call the ImageCaptchaService getChallenge method
BufferedImage challenge = imageCaptchaService.getImageChallengeForID(captchaId, request.getLocale());
// a jpeg encoder
/*
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
*/
jpegOutputStream = new ByteArrayOutputStream();
ImageIO.write(challenge,"jpg",jpegOutputStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flush it in the response
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
return null;
| 73 | 398 | 471 |
269 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/base/controller/LoginRegisterResult.java | LoginRegisterResult | FAILURE | class LoginRegisterResult {
private String status;
private String type;
private String[] currentAuthority;
private HttpResult httpResult;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getCurrentAuthority() {
return currentAuthority;
}
public void setCurrentAuthority(String[] currentAuthority) {
this.currentAuthority = currentAuthority;
}
public HttpResult getHttpResult() {
return httpResult;
}
public void setHttpResult(HttpResult httpResult) {
this.httpResult = httpResult;
}
public static LoginRegisterResult RESULT(String status,String type){
LoginRegisterResult loginResult = new LoginRegisterResult();
loginResult.setStatus(status);
loginResult.setType(type);
loginResult.setCurrentAuthority(new String[]{});
return loginResult;
}
public static LoginRegisterResult SUCCESS(String currentAuthority){
LoginRegisterResult loginResult = new LoginRegisterResult();
loginResult.setStatus("ok");
loginResult.setType("account");
// loginResult.setCurrentAuthority("admin");
loginResult.setCurrentAuthority(new String[]{currentAuthority});
return loginResult;
}
public static LoginRegisterResult SUCCESS(String[] currentAuthority){
LoginRegisterResult loginResult = new LoginRegisterResult();
loginResult.setStatus("ok");
loginResult.setType("account");
// loginResult.setCurrentAuthority("admin");
loginResult.setCurrentAuthority(currentAuthority);
return loginResult;
}
public static LoginRegisterResult FAILURE(){
LoginRegisterResult loginResult = new LoginRegisterResult();
loginResult.setStatus("error");
loginResult.setType("account");
loginResult.setCurrentAuthority(new String[]{"guest"});
return loginResult;
}
public static LoginRegisterResult FAILURE(HttpResult httpResult){<FILL_FUNCTION_BODY>}
} |
LoginRegisterResult loginResult = new LoginRegisterResult();
loginResult.setStatus("error");
loginResult.setType("account");
loginResult.setCurrentAuthority(new String[]{"guest"});
loginResult.setHttpResult(httpResult);
return loginResult;
| 571 | 72 | 643 |
270 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/base/controller/SecurityController.java | SecurityController | loginPwd | class SecurityController {
@Autowired
private AccountManager accountManager;
@Autowired
private UserManager userManager;
@Autowired
private FormAuthenticationWithLockFilter formAuthFilter;
@RequestMapping("/logout.do")
@ResponseBody
public HttpResult logout(HttpServletRequest request,HttpServletResponse response) throws Exception {
if (SecurityUtils.getSubject() != null) {
User curUser = accountManager.getCurUser();
String userId = "";
String loginName = "";
if(curUser!=null){
userId = curUser.getId();
loginName = curUser.getLoginName();
}
SecurityUtils.getSubject().logout();
}
request.getSession().invalidate();
return HttpResult.SUCCESS();
}
@RequestMapping("/login.do")
@ResponseBody
public LoginRegisterResult login(HttpServletRequest request, HttpServletResponse response, String userName, String password) {
Subject subject = SecurityUtils.getSubject();
boolean isAuth = subject.isAuthenticated();
if(isAuth){
User user = accountManager.getCurUser();
if(user!=null){
String[] authed = new String[]{};
if("1".equals(user.getId())) authed = new String[]{RoleCode.DWSURVEY_SUPER_ADMIN};
return LoginRegisterResult.SUCCESS(authed);
}
}
//账号密码
request.setAttribute("username",userName);
return loginPwd(request,response,userName,password);
}
@RequestMapping("/login-pwd.do")
@ResponseBody
public LoginRegisterResult loginPwd(HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password) {<FILL_FUNCTION_BODY>}
@RequestMapping("/checkEmail.do")
@ResponseBody
public boolean checkEmailUn(String id,String email) throws Exception{
User user=userManager.findEmailUn(id,email);
boolean result=true;
if(user!=null){
result=false;
}
return result;
}
@RequestMapping("/checkLoginNamelUn.do")
@ResponseBody
public boolean checkLoginNamelUn(String id,String loginName) throws Exception{
User user=userManager.findNameUn(id,loginName);
boolean result=true;
if(user!=null){
result=false;
}
return result;
}
} |
Subject subject = SecurityUtils.getSubject();
boolean isAuth = subject.isAuthenticated();
String error="账号或密码错误";
String[] authed = null;
try{
if(isAuth) subject.logout();
if(StringUtils.isNotEmpty(userName)){
User user = accountManager.findUserByLoginNameOrEmail(userName);
if(user!=null){
UsernamePasswordToken loginToken = new UsernamePasswordToken(userName, password);
request.setAttribute("username",userName);
if (!formAuthFilter.checkIfAccountLocked(request)) {
try {
subject.login(loginToken);
formAuthFilter.resetAccountLock(userName);
subject.getSession().setAttribute("loginUserName", userName);
user.setLastLoginTime(new Date());
accountManager.saveUp(user);
if("1".equals(user.getId())) authed = new String[]{RoleCode.DWSURVEY_SUPER_ADMIN};
return LoginRegisterResult.SUCCESS(authed);
} catch (IncorrectCredentialsException e) {
formAuthFilter.decreaseAccountLoginAttempts(request);
error = "密码不正确";
} catch (AuthenticationException e) {
error = "身份认证错误";
}
} else {
// ExcessiveAttemptsException超过登录次数
error = "超过登录次数限制";
}
}else{
error = "未找到userName对应用户";
}
}else{
error = "登录名userName不能为空";
}
}catch (Exception e) {
e.printStackTrace();
error = e.getMessage();
}
return LoginRegisterResult.FAILURE(HttpResult.FAILURE_MSG(error));
| 650 | 461 | 1,111 |
271 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/base/service/AccountManager.java | AccountManager | isSupervisor | class AccountManager {
private static Logger logger = LoggerFactory.getLogger(AccountManager.class);
@Autowired
private UserDao userDao;
// @Autowired
// private NotifyMessageProducer notifyMessageProducer;//JMS消息推送
private ShiroDbRealm shiroRealm;
/**
* 在保存用户时,发送用户修改通知消息, 由消息接收者异步进行较为耗时的通知邮件发送.
*
* 如果企图修改超级用户,取出当前操作员用户,打印其信息然后抛出异常.
*
*/
// 演示指定非默认名称的TransactionManager.
@Transactional
public void saveUser(User user) {
if (isSupervisor(user)) {
logger.warn("操作员{}尝试修改超级管理员用户", SecurityUtils.getSubject()
.getPrincipal());
throw new ServiceException("不能修改超级管理员用户");
}
//判断是否有重复用户
String shaPassword = DigestUtils.sha1Hex(user.getPlainPassword());
user.setShaPassword(shaPassword);
boolean bool=user.getId()==null?true:false;
userDao.save(user);
if (shiroRealm != null) {
shiroRealm.clearCachedAuthorizationInfo(user.getLoginName());
}
/*if(bool){
// Email email=new Email();
// sendNotifyMessage(email); 使用jms辅助 发送邮件
simpleMailService.sendRegisterMailByAsync(user);
}*/
}
@Transactional
public void saveUp(User user){
if (isSupervisor(user)) {
logger.warn("操作员{}尝试修改超级管理员用户", SecurityUtils.getSubject().getPrincipal());
throw new ServiceException("不能修改超级管理员用户");
}
userDao.save(user);
}
@Transactional
public boolean updatePwd(String curpwd, String newPwd) {
User user = getCurUser();
if(user!=null){
if(curpwd!=null && newPwd!=null){
//判断是否有重复用户
String curShaPassword = DigestUtils.sha1Hex(curpwd);
if(user.getShaPassword().equals(curShaPassword)){
String shaPassword = DigestUtils.sha1Hex(newPwd);
user.setShaPassword(shaPassword);
userDao.save(user);
return true;
}
}
}
return false;
}
/*public User getByUid(String userSource,String uid){
Criterion cri1=Restrictions.eq("thirdSource", userSource);
Criterion cri2=Restrictions.eq("thirdUid", uid);
return userDao.findUnique(cri1,cri2);
}*/
//新注册用户,注册后
// private void sendNotifyMessage(Email email) {
// notifyMessageProducer.sendQueue(email);
// }
/**
* 判断是否超级管理员.
*/
private boolean isSupervisor(User user) {<FILL_FUNCTION_BODY>}
@Transactional(readOnly = true)
public User getUser(String id) {
return userDao.get(id);
}
@Transactional(readOnly = true)
public User findUserByLoginName(String loginName) {
return userDao.findUniqueBy("loginName", loginName);
}
@Transactional(readOnly = true)
public User findUserByLoginNameOrEmail(String loginName) {
User user = null;
if(loginName!=null){
user = userDao.findUniqueBy("loginName", loginName);
if(user==null && loginName.contains("@")){
//是邮箱账号
user = userDao.findUniqueBy("email", loginName);
}
}
return user;
}
/*验证邮箱是否存在*/
@Transactional(readOnly = true)
public User findUserByEmail(String email){
List<User> users=userDao.findBy("email", email);
if(users!=null && users.size()>0){
return users.get(0);
}
return null;
}
/**
* 检查用户名是否唯一.
*
* @return loginName在数据库中唯一或等于oldLoginName时返回true.
*/
@Transactional(readOnly = true)
public boolean isLoginNameUnique(String newLoginName, String oldLoginName) {
return userDao.isPropertyUnique("loginName", newLoginName, oldLoginName);
}
/**
* 取出当前登陆用户
*/
public User getCurUser(){
Subject subject=SecurityUtils.getSubject();
if(subject!=null){
Object principal=subject.getPrincipal();
if(principal!=null){
User user = findUserByLoginName(principal.toString());
return user;
}
}
return null;
}
} |
// return (user.getId() != null && user.getId() == 1L);
return false;
| 1,472 | 32 | 1,504 |
272 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/email/Email.java | Email | toString | class Email {
private String to;// 收件人
private String subject;// 主题
private String username;// 用户称呼
private String content;// 内容
private String date;// 日期
private String sendEmailId;
public Email() {
super();
}
public Email(String to, String subject, String username, String content,
String date) {
super();
this.to = to;
this.subject = subject;
this.username = username;
this.content = content;
this.date = date;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSendEmailId() {
return sendEmailId;
}
public void setSendEmailId(String sendEmailId) {
this.sendEmailId = sendEmailId;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "Email [content=" + content + ", date=" + date + ", subject="
+ subject + ", to=" + to + ", username=" + username + "]";
| 468 | 51 | 519 |
273 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/file/FileMagicUtils.java | FileMagicUtils | getFileMagic | class FileMagicUtils {
//非登录用户能够上传的文件类型
public static FileMagic[] anonUpFileType() {
return new FileMagic[]{FileMagic.PNG,FileMagic.JPG,FileMagic.JPEG,FileMagic.GIF,
FileMagic.TXT,FileMagic.PDF,
FileMagic.XLSX,FileMagic.XLS,FileMagic.DOC,FileMagic.DOCX,FileMagic.PPT,FileMagic.PPTX,
FileMagic.ZIP,FileMagic.RAR,FileMagic.Z7Z};
}
//登录用户能够上传的文件类型
public static FileMagic[] userUpFileType() {
return new FileMagic[]{FileMagic.PNG,FileMagic.JPG,FileMagic.JPEG,FileMagic.GIF,
FileMagic.TXT,FileMagic.PDF,
FileMagic.XLSX,FileMagic.XLS,FileMagic.DOC,FileMagic.DOCX,FileMagic.PPT,FileMagic.PPTX,
FileMagic.ZIP,FileMagic.RAR,FileMagic.Z7Z};
}
//根据文件获取对应的文件类型
public static FileMagic getFileMagic(File inp, String fileSuffix) throws Exception {
FileMagic fileMagic = null;
FileInputStream fis = null;
try{
fis = new FileInputStream(inp);
fileMagic = getFileMagic(fis,fileSuffix);
}catch (Exception e){
e.printStackTrace();
}finally {
if (fis!=null) fis.close();
}
return fileMagic;
}
//切换到使用最新的tika验测
public static FileMagic getFileMagic(byte[] bytes,String fileName) throws IOException{<FILL_FUNCTION_BODY>}
//切换到使用最新的tika验测
public static FileMagic getFileMagic(InputStream fis, String fileName) throws IOException{
String mineType = TikaFileUtils.mimeType(fis,fileName);
if(mineType!=null){
FileMagic[] fileMagics = FileMagic.values();
int fileMagicLength = fileMagics.length;
for(int i = 0; i < fileMagicLength; ++i) {
FileMagic fm = fileMagics[i];
String fileSuffix = fm.getFileSuffix().toLowerCase();
if (fileSuffix.indexOf(mineType.toLowerCase())>=0) {
return fm;
}
}
}
return FileMagic.UNKNOWN;
}
public static boolean isUserUpFileType(byte[] bytes, String suffix) {
try {
FileMagic fileMagic = getFileMagic(bytes,suffix);
if (isUserUpFileMagic(fileMagic)) return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean isUserUpFileType(File file, String suffix) {
try {
FileMagic fileMagic = getFileMagic(file,suffix);
if (isUserUpFileMagic(fileMagic)) return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean isUserUpFileType(InputStream inputStream, String suffix) {
try {
FileMagic fileMagic = getFileMagic(inputStream,suffix);
if (isUserUpFileMagic(fileMagic)) return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 判断是否在登录用户可上传白名单
* @param fileMagic
* @return
*/
public static boolean isUserUpFileMagic(FileMagic fileMagic) {
FileMagic[] fileMagics = userUpFileType();
for (FileMagic magic:fileMagics) {
if(magic == fileMagic){
return true;
}
}
return false;
}
} |
String mineType = TikaFileUtils.mimeType(bytes,fileName);
if(mineType!=null){
FileMagic[] fileMagics = FileMagic.values();
int fileMagicLength = fileMagics.length;
for(int i = 0; i < fileMagicLength; ++i) {
FileMagic fm = fileMagics[i];
String fileSuffix = fm.getFileSuffix().toLowerCase();
if (fileSuffix.indexOf(mineType.toLowerCase())>=0) {
return fm;
}
}
}
return FileMagic.UNKNOWN;
| 1,091 | 167 | 1,258 |
274 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/file/TikaFileUtils.java | TikaFileUtils | mimeType | class TikaFileUtils {
public static String mimeType(byte[] bytes, String suffix) {<FILL_FUNCTION_BODY>}
public static String mimeType(InputStream inputStream, String suffix) {
try {
Tika tika = new Tika();
String mimeTypeStr = tika.detect(inputStream,suffix);
return getMimeType(mimeTypeStr, suffix);
} catch (IOException e) {
e.printStackTrace();
} catch (MimeTypeException e) {
e.printStackTrace();
}
return null;
}
private static String getMimeType(String mimeTypeStr, String suffix) throws MimeTypeException {
MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes();
MimeType mimeType = mimeTypes.forName(mimeTypeStr);
if(mimeType.getExtensions().stream().anyMatch(ext -> ext.equals(suffix))){
return suffix;
}
return null;
}
public static String getMimeType(InputStream inputStream, String suffix) {
try {
Tika tika = new Tika();
String mimeTypeStr = tika.detect(inputStream,suffix);
return getMimeType(mimeTypeStr);
} catch (IOException e) {
e.printStackTrace();
} catch (MimeTypeException e) {
e.printStackTrace();
}
return null;
}
private static String getMimeType(String mimeTypeStr) throws MimeTypeException {
MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes();
MimeType mimeType = mimeTypes.forName(mimeTypeStr);
List<String> list = mimeType.getExtensions();
return JSON.toJSONString(list);
}
} |
try {
Tika tika = new Tika();
String mimeTypeStr = tika.detect(bytes,suffix);
return getMimeType(mimeTypeStr, suffix);
} catch (MimeTypeException e) {
e.printStackTrace();
}
return null;
| 474 | 80 | 554 |
275 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/httpclient/IdleConnectionEvictor.java | IdleConnectionEvictor | run | class IdleConnectionEvictor extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
this.connMgr = connMgr;
// 启动当前线程
this.start();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
} |
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
| 136 | 84 | 220 |
276 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/httpclient/ResultUtils.java | ResultUtils | getPageByPageResult | class ResultUtils {
public static <T> Page<T> getPageByPageResult(PageResult<T> pageResult){<FILL_FUNCTION_BODY>}
public static <T> PageResult<T> getPageResultByPage(Page<T> page,PageResult<T> pageResult){
if(page!=null){
if(pageResult==null){
pageResult = new PageResult<T>();
}
pageResult.setCurrent(page.getPageNo());
pageResult.setSuccess(true);
pageResult.setData(page.getResult());
pageResult.setPageSize(page.getPageSize());
pageResult.setTotal(Integer.parseInt(page.getTotalItems()+""));
}
return pageResult;
}
} |
Page<T> page = new Page<T>();
Integer current = pageResult.getCurrent();
if(current==null){
current=1;
}
Integer pageSize = pageResult.getPageSize();
if(pageSize==null){
pageSize = 10;
}
page.setPageNo(current);
page.setPageSize(pageSize);
return page;
| 197 | 104 | 301 |
277 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/ipaddr/IPService.java | IPService | getIp | class IPService {
@Autowired
private IPLocationService ipLocationService;
public IPLocation getIpLocation(String ip) {
if(ip==null){
return null;
}
try{
return ipLocationService.getLocationByIp(ip);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 根据ip取得所在地区
* @param ip
* @return
*/
public String getCountry(String ip) {
if(ip==null){
return "";
}
return ipLocationService.getLocationByIp(ip).getProvince();
}
/**
* 根据IP,查出此ip所在的城市
*
* @param ip
* @return
*/
public String getCurCity(String ip) {
//空实现
return null;
}
/**
*
* @param country
* @return
*/
public String getCurCityByCountry(String country) {
return null;
}
public String getIp(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
/**
* 检查以localhost,127.0.0.1访问时得到真实IP
* @param ip
* @return
*/
public String checkLocalIp(String ip){
if("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1%0".equals(ip)){
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ip=inetAddress.getHostAddress();
if(ip!=null && ip.length()>15){ //"***.***.***.***".length() = 15
if(ip.indexOf(",")>0){
ip = ip.substring(0,ip.indexOf(","));
}
}
} catch (UnknownHostException e) {
// e.printStackTrace();2019000MA6TG48K
}
}
return ip;
}
public String replaceIPv6LocalIp(String ip){
if("0:0:0:0:0:0:0:1".equals(ip)){
ip="127.0.0.1";
}
return ip;
}
} |
//Http Header:X-Forwarded-For
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// ip=replaceIPv6LocalIp(ip);
ip=checkLocalIp(ip);
if(ip!=null && ip.indexOf(",")>0){
ip=ip.substring(0,ip.indexOf(","));
}
return ip;
| 709 | 257 | 966 |
278 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/jcaptcha/CaptchaEngineEx.java | CaptchaEngineEx | buildInitialFactories | class CaptchaEngineEx extends ListImageCaptchaEngine {
/*protected void buildInitialFactories() {
int minWordLength = 4;
int maxWordLength = 5;
int fontSize = 50;
int imageWidth = 250;
int imageHeight = 100;
WordGenerator wordGenerator = new RandomWordGenerator(
"0123456789abcdefghijklmnopqrstuvwxyz");
TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
maxWordLength, new RandomListColorGenerator(new Color[] {
new Color(23, 170, 27), new Color(220, 34, 11),
new Color(23, 67, 172) }), new TextDecorator[] {});
BackgroundGenerator background = new UniColorBackgroundGenerator(
imageWidth, imageHeight, Color.white);
FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
new Font[] { new Font("nyala", Font.BOLD, fontSize),
new Font("Bell MT", Font.PLAIN, fontSize),
new Font("Credit valley", Font.BOLD, fontSize) });
ImageDeformation postDef = new ImageDeformationByFilters(
new ImageFilter[] {});
ImageDeformation backDef = new ImageDeformationByFilters(
new ImageFilter[] {});
ImageDeformation textDef = new ImageDeformationByFilters(
new ImageFilter[] {});
WordToImage word2image = new DeformedComposedWordToImage(font,
background, randomPaster, backDef, textDef, postDef);
addFactory(new GimpyFactory(wordGenerator, word2image));
}*/
protected void buildInitialFactories() {<FILL_FUNCTION_BODY>}
} |
int minWordLength = 4;
int maxWordLength = 5;
/*int fontSize = 50;
int imageWidth = 250;
int imageHeight = 100;*/
int fontSize = 30;
int imageWidth = 120;
int imageHeight = 50;
WordGenerator dictionnaryWords = new ComposeDictionaryWordGenerator(new FileDictionary("toddlist"));
// word2image components
TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
maxWordLength, new RandomListColorGenerator(new Color[] {
new Color(23, 170, 27), new Color(220, 34, 11),
new Color(23, 67, 172) }), new TextDecorator[] {});
BackgroundGenerator background = new UniColorBackgroundGenerator(
imageWidth, imageHeight, Color.white);
// ColorGenerator colorGenerator=new RandomListColorGenerator(new Color[]{new Color(235, 234, 235),new Color(255, 255, 255)});
// BackgroundGenerator background=new FunkyBackgroundGenerator(imageWidth, imageHeight,colorGenerator);
FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
new Font[] { new Font("nyala", Font.BOLD, fontSize),
new Font("Bell MT", Font.PLAIN, fontSize),
new Font("Credit valley", Font.BOLD, fontSize) });
ImageDeformation postDef = new ImageDeformationByFilters(
new ImageFilter[] {});
ImageDeformation backDef = new ImageDeformationByFilters(
new ImageFilter[] {});
ImageDeformation textDef = new ImageDeformationByFilters(
new ImageFilter[] {});
WordToImage word2image = new DeformedComposedWordToImage(font,
background, randomPaster, backDef, textDef, postDef);
addFactory(new GimpyFactory(dictionnaryWords, word2image));
| 526 | 592 | 1,118 |
279 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/CollectionMapper.java | CollectionMapper | extractToMap | class CollectionMapper {
/**
* 提取集合中的对象的属性(通过Getter函数), 组合成Map.
*
* @param collection 来源集合.
* @param keyPropertyName 要提取为Map中的Key值的属性名.
* @param valuePropertyName 要提取为Map中的Value值的属性名.
*/
public static Map extractToMap(final Collection collection, final String keyPropertyName,
final String valuePropertyName) {<FILL_FUNCTION_BODY>}
/**
* 提取集合中的对象的属性(通过Getter函数), 组合成List.
*
* @param collection 来源集合.
* @param propertyName 要提取的属性名.
*/
public static List extractToList(final Collection collection, final String propertyName) {
List list = new ArrayList();
try {
for (Object obj : collection) {
list.add(PropertyUtils.getProperty(obj, propertyName));
}
} catch (Exception e) {
throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
}
return list;
}
/**
* 提取集合中的对象的属性(通过Getter函数), 组合成由分割符分隔的字符串.
*
* @param collection 来源集合.
* @param propertyName 要提取的属性名.
* @param separator 分隔符.
*/
public static String extractToString(final Collection collection, final String propertyName, final String separator) {
List list = extractToList(collection, propertyName);
return StringUtils.join(list, separator);
}
} |
Map map = new HashMap();
try {
for (Object obj : collection) {
map.put(PropertyUtils.getProperty(obj, keyPropertyName),
PropertyUtils.getProperty(obj, valuePropertyName));
}
} catch (Exception e) {
throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
}
return map;
| 483 | 116 | 599 |
280 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/ImprovedNamingStrategy.java | ImprovedNamingStrategy | convert | class ImprovedNamingStrategy implements PhysicalNamingStrategy {
@Override
public Identifier toPhysicalCatalogName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSchemaName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
return convert(identifier);
}
@Override
public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSequenceName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
return convert(identifier);
}
@Override
public Identifier toPhysicalColumnName(Identifier identifier, JdbcEnvironment jdbcEnvironment) {
return convert(identifier);
}
private Identifier convert(Identifier identifier) {<FILL_FUNCTION_BODY>}
} |
if (identifier == null || StringUtils.isBlank(identifier.getText())) {
return identifier;
}
String regex = "([a-z])([A-Z])";
String replacement = "$1_$2";
String newName = identifier.getText().replaceAll(regex, replacement).toLowerCase();
return Identifier.toIdentifier(newName);
| 205 | 94 | 299 |
281 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/ObjectMapper.java | ObjectMapper | convertToObject | class ObjectMapper {
/**
* 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
*/
private static DozerBeanMapper dozer = new DozerBeanMapper();
/**
* 基于Dozer转换对象的类型.
*/
public static <T> T map(Object source, Class<T> destinationClass) {
return dozer.map(source, destinationClass);
}
/**
* 基于Dozer转换Collection中对象的类型.
*/
public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
List<T> destinationList = Lists.newArrayList();
for (Object sourceObject : sourceList) {
T destinationObject = dozer.map(sourceObject, destinationClass);
destinationList.add(destinationObject);
}
return destinationList;
}
static {
//初始化日期格式为yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss
registerDateConverter("yyyy-MM-dd,yyyy-MM-dd HH:mm:ss");
}
/**
* 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔
*/
public static void registerDateConverter(String patterns) {
DateConverter dc = new DateConverter();
dc.setUseLocaleFormat(true);
dc.setPatterns(StringUtils.split(patterns, ","));
ConvertUtils.register(dc, Date.class);
}
/**
* 基于Apache BeanUtils转换字符串到相应类型.
*
* @param value 待转换的字符串.
* @param toType 转换目标类型.
*/
public static Object convertToObject(String value, Class<?> toType) {<FILL_FUNCTION_BODY>}
} |
Object cvt_value=null;
try {
cvt_value=ConvertUtils.convert(value, toType);
// if(toType==Date.class){
// SimpleDateFormat dateFormat=null;
// try{
// dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// cvt_value=dateFormat.parse(value);
// }catch(Exception e){
// dateFormat=new SimpleDateFormat("yyyy-MM-dd");
// cvt_value=dateFormat.parse(value);
// }
// }
} catch (Exception e) {
throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
}
return cvt_value;
| 532 | 214 | 746 |
282 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/mapper/PhysicalNamingStrategyImpl.java | PhysicalNamingStrategyImpl | addUnderscores | class PhysicalNamingStrategyImpl extends PhysicalNamingStrategyStandardImpl implements Serializable {
public static final PhysicalNamingStrategyImpl INSTANCE = new PhysicalNamingStrategyImpl();
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
return new Identifier(addUnderscores(name.getText()), name.isQuoted());
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
return new Identifier(addUnderscores(name.getText()), name.isQuoted());
}
protected static String addUnderscores(String name) {<FILL_FUNCTION_BODY>}
} |
final StringBuilder buf = new StringBuilder( name.replace('.', '_') );
for (int i=1; i<buf.length()-1; i++) {
if (
Character.isLowerCase( buf.charAt(i-1) ) &&
Character.isUpperCase( buf.charAt(i) ) &&
Character.isLowerCase( buf.charAt(i+1) )
) {
buf.insert(i++, '_');
}
}
return buf.toString().toLowerCase(Locale.ROOT);
| 168 | 140 | 308 |
283 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/page/Page.java | Page | setStartEndPageNo | class Page<T> extends PageRequest implements Iterable<T> {
protected List<T> result = null;
protected long totalItems = -1;
public Page() {
}
public Page(PageRequest request) {
this.pageNo = request.pageNo;
this.pageSize = request.pageSize;
this.countTotal = request.countTotal;
this.orderBy = request.orderBy;
this.orderDir = request.orderDir;
}
/**
* 获得页内的记录列表.
*/
public List<T> getResult() {
return result;
}
/**
* 设置页内的记录列表.
*/
public void setResult(final List<T> result) {
this.result = result;
}
/**
* 获得总记录数, 默认值为-1.
*/
public long getTotalItems() {
return totalItems;
}
/**
* 设置总记录数.
*/
public void setTotalItems(final long totalItems) {
this.totalItems = totalItems;
// getSlider(this.pageNoSize);
setStartEndPageNo();
}
/**
* 实现Iterable接口, 可以for(Object item : page)遍历使用
*/
@Override
public Iterator<T> iterator() {
return result.iterator();
}
/**
* 根据pageSize与totalItems计算总页数.
*/
public int getTotalPages() {
return (int) Math.ceil((double) totalItems / (double) getPageSize());
}
/**
* 是否还有下一页.
*/
public boolean hasNextPage() {
return (getPageNo() + 1 <= getTotalPages());
}
/**
* 是否最后一页.
*/
public boolean isLastPage() {
return !hasNextPage();
}
/**
* 取得下页的页号, 序号从1开始.
* 当前页为尾页时仍返回尾页序号.
*/
public int getNextPage() {
if (hasNextPage()) {
return getPageNo() + 1;
} else {
return getPageNo();
}
}
/**
* 是否还有上一页.
*/
public boolean hasPrePage() {
return (getPageNo() > 1);
}
/**
* 是否第一页.
*/
public boolean isFirstPage() {
return !hasPrePage();
}
/**
* 取得上页的页号, 序号从1开始.
* 当前页为首页时返回首页序号.
*/
public int getPrePage() {
if (hasPrePage()) {
return getPageNo() - 1;
} else {
return getPageNo();
}
}
/**
* 计算以当前页为中心的页面列表,如"首页,23,24,25,26,27,末页"
* @param count 需要计算的列表大小
* @return pageNo列表
*/
public List<Integer> getSlider(int count) {
int halfSize = count / 2;
totalPage = getTotalPages();
int startPageNo = Math.max(getPageNo() - halfSize, 1);
int endPageNo = Math.min(startPageNo + count - 1, totalPage);
if (endPageNo - startPageNo < count) {
startPageNo = Math.max(endPageNo - count, 1);
}
List<Integer> result = Lists.newArrayList();
for (int i = startPageNo; i <= endPageNo; i++) {
result.add(i);
}
this.pageNos=result;
return result;
}
private int startpage;
private int endpage;
public void setStartEndPageNo(){<FILL_FUNCTION_BODY>}
public int getStartpage() {
return startpage;
}
public void setStartpage(int startpage) {
this.startpage = startpage;
}
public int getEndpage() {
return endpage;
}
public void setEndpage(int endpage) {
this.endpage = endpage;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} |
totalPage = getTotalPages();
startpage = pageNo
- (pageNoSize % 2 == 0 ? pageNoSize / 2 - 1
: pageNoSize / 2);
endpage = pageNo + pageNoSize / 2;
if (startpage < 1) {
startpage = 1;
if (totalPage >= pageNoSize) {
endpage = pageNoSize;
} else {
endpage = totalPage;
}
}
if (endpage > totalPage) {
endpage = totalPage;
if ((endpage - pageNoSize) > 0) {
startpage = endpage - pageNoSize + 1;
} else {
startpage = 1;
}
}
// return new PageIndexUtil(startpage, endpage);
| 1,287 | 237 | 1,524 |
284 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/page/PageRequest.java | PageRequest | getSort | class PageRequest {
protected int pageNo = 1;
protected int pageSize = 10;
protected String orderBy = null;
protected String orderDir = null;
protected boolean countTotal = true;
protected List<Integer> pageNos;
protected int pageNoSize = 5;
public PageRequest() {
}
public PageRequest(int pageNo, int pageSize) {
this.pageNo = pageNo;
this.pageSize = pageSize;
}
/**
* 获得当前页的页号, 序号从1开始, 默认为1.
*/
public int getPageNo() {
return pageNo;
}
/**
* 设置当前页的页号, 序号从1开始, 低于1时自动调整为1.
*/
public void setPageNo(final int pageNo) {
this.pageNo = pageNo;
if (pageNo < 1) {
this.pageNo = 1;
}
}
/**
* 获得每页的记录数量, 默认为10.
*/
public int getPageSize() {
return pageSize;
}
/**
* 设置每页的记录数量, 低于1时自动调整为1.
*/
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
if (pageSize < 1) {
this.pageSize = 1;
}
}
/**
* 获得排序字段, 无默认值. 多个排序字段时用','分隔.
*/
public String getOrderBy() {
return orderBy;
}
/**
* 设置排序字段, 多个排序字段时用','分隔.
*/
public void setOrderBy(final String orderBy) {
this.orderBy = orderBy;
}
/**
* 获得排序方向, 无默认值.
*/
public String getOrderDir() {
return orderDir;
}
/**
* 设置排序方式向.
*
* @param orderDir
* 可选值为desc或asc,多个排序字段时用','分隔.
*/
public void setOrderDir(final String orderDir) {
String lowcaseOrderDir = StringUtils.lowerCase(orderDir);
// 检查order字符串的合法值
String[] orderDirs = StringUtils.split(lowcaseOrderDir, ',');
for (String orderDirStr : orderDirs) {
if (!StringUtils.equals(Sort.DESC, orderDirStr)
&& !StringUtils.equals(Sort.ASC, orderDirStr)) {
throw new IllegalArgumentException("排序方向" + orderDirStr
+ "不是合法值");
}
}
this.orderDir = lowcaseOrderDir;
}
/**
* 获得排序参数.
*/
public List<Sort> getSort() {<FILL_FUNCTION_BODY>}
/**
* 是否已设置排序字段,无默认值.
*/
public boolean isOrderBySetted() {
return (StringUtils.isNotBlank(orderBy) && StringUtils
.isNotBlank(orderDir));
}
/**
* 是否默认计算总记录数.
*/
public boolean isCountTotal() {
return countTotal;
}
/**
* 设置是否默认计算总记录数.
*/
public void setCountTotal(boolean countTotal) {
this.countTotal = countTotal;
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置, 序号从0开始.
*/
public int getOffset() {
return ((pageNo - 1) * pageSize);
}
public static class Sort {
public static final String ASC = "asc";
public static final String DESC = "desc";
private final String property;
private final String dir;
public Sort(String property, String dir) {
this.property = property;
this.dir = dir;
}
public String getProperty() {
return property;
}
public String getDir() {
return dir;
}
}
public List<Integer> getPageNos() {
return pageNos;
}
public void setPageNoSize(int pageNoSize) {
this.pageNoSize = pageNoSize;
}
// 总页数
protected int totalPage;
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
// 是否取最后一页数据
private boolean islastpage=false;
public boolean isIslastpage() {
return islastpage;
}
public void setIslastpage(boolean islastpage) {
this.islastpage = islastpage;
}
} |
String[] orderBys = StringUtils.split(orderBy, ',');
String[] orderDirs = StringUtils.split(orderDir, ',');
AssertUtils.isTrue(orderBys.length == orderDirs.length,
"分页多重排序参数中,排序字段与排序方向的个数不相等");
List<Sort> orders = Lists.newArrayList();
for (int i = 0; i < orderBys.length; i++) {
orders.add(new Sort(orderBys[i], orderDirs[i]));
}
return orders;
| 1,419 | 168 | 1,587 |
285 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/security/ShiroDbRealm.java | ShiroDbRealm | doGetAuthenticationInfo | class ShiroDbRealm extends AuthorizingRealm {
@Autowired
protected AccountManager accountManager;
public ShiroDbRealm() {
setCredentialsMatcher(new HashedCredentialsMatcher("SHA-1"));
}
/**
* 认证回调函数,登录时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {<FILL_FUNCTION_BODY>}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.fromRealm(getName()).iterator().next();
// User user = accountManager.findUserByLoginName(username);
User user = accountManager.findUserByLoginNameOrEmail(username);
if(user!=null){
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
if ("1".equals(user.getId())) {
info.addRole(RoleCode.DWSURVEY_SUPER_ADMIN);
}
return info;
}
return null;
}
/**
* 更新用户授权信息缓存.
*/
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
}
} |
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
// User user = accountManager.findUserByLoginName(token.getUsername());
//根据loginToken 看能不查到当前token token有效期就1分钟
String tokenPassword=new String(token.getPassword());
User user = accountManager.findUserByLoginNameOrEmail(token.getUsername());
//user.getStandardLock()==1
if (user != null && user.getStatus().intValue()!=0 && (user.getVisibility()==null || user.getVisibility()==1 )) {
return new SimpleAuthenticationInfo(user.getLoginName(), user.getShaPassword() , getName());
} else {
return null;
}
| 388 | 196 | 584 |
286 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/FormAuthenticationWithLockFilter.java | FormAuthenticationWithLockFilter | decreaseAccountLoginAttempts | class FormAuthenticationWithLockFilter extends FormAuthenticationFilter {
Log log=LogFactory.getLog(FormAuthenticationWithLockFilter.class);
private long maxLoginAttempts = 10;
public static ConcurrentHashMap<String, AtomicLong> accountLockMap = new ConcurrentHashMap<String, AtomicLong>();
private String successAdminUrl;
private String successAdminRole;
@Autowired
protected AccountManager accountManager;
@Override
public boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
AuthenticationToken token = createToken(request, response);
if (token == null) {
String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken "
+ "must be created in order to execute a login attempt.";
throw new IllegalStateException(msg);
}
if (checkIfAccountLocked(request)) {
return onLoginFailure(token, new ExcessiveAttemptsException(), request, response);
} else {
if (!doLogin(request, response, token)) {
resetAccountLock(getUsername(request));
return false;
}
return true;
}
}
public boolean checkIfAccountLocked(ServletRequest request) {
String username = getUsername(request);
if (username!=null && accountLockMap.get((String) username) != null) {
long remainLoginAttempts = accountLockMap.get((String) username).get();
if (remainLoginAttempts <= 0) {
return true;
}
}
return false;
}
private boolean doLogin(ServletRequest request, ServletResponse response, AuthenticationToken token)
throws Exception {
try {
Subject subject = getSubject(request, response);
subject.login(token);
// User user = accountManager.findUserByLoginName(getUsername(request));
User user = accountManager.findUserByLoginNameOrEmail(getUsername(request));
user.setLastLoginTime(new Date());
accountManager.saveUp(user);
return onLoginSuccess(token, subject, request, response);
} catch (IncorrectCredentialsException e) {
decreaseAccountLoginAttempts(request);
checkIfAccountLocked(request);
return onLoginFailure(token, e, request, response);
} catch (AuthenticationException e) {
return onLoginFailure(token, e, request, response);
}
}
public void decreaseAccountLoginAttempts(ServletRequest request) {<FILL_FUNCTION_BODY>}
public void resetAccountLock(String username) {
accountLockMap.put(username, new AtomicLong(maxLoginAttempts));
}
public void setMaxLoginAttempts(long maxLoginAttempts) {
this.maxLoginAttempts = maxLoginAttempts;
}
public void setSuccessAdminUrl(String successAdminUrl) {
this.successAdminUrl = successAdminUrl;
}
public void setSuccessAdminRole(String successAdminRole) {
this.successAdminRole = successAdminRole;
}
/* 得到某个账号还可以登录次数 */
public Long getAccountLocked(String username){
long remainLoginAttempts=0;
if (username!=null && accountLockMap.get((String) username) != null) {
remainLoginAttempts = accountLockMap.get((String) username).get();
}
return remainLoginAttempts+1;
}
/* 重写登录失败,加入了失败时还可以重试的次数信息 */
@Override
protected boolean onLoginFailure(AuthenticationToken token,
AuthenticationException e, ServletRequest request,
ServletResponse response) {
request.setAttribute("remainLoginAttempt", getAccountLocked(getUsername(request)));
return super.onLoginFailure(token, e, request, response);
}
@Override
protected String getUsername(ServletRequest request) {
// TODO Auto-generated method stub
String username = super.getUsername(request);
if(username==null){
Object temp=request.getAttribute(getUsernameParam());
username=temp!=null?temp.toString():null;
}
return username;
}
@Override
protected String getPassword(ServletRequest request) {
String password = super.getPassword(request);
if(password==null){
Object temp=request.getAttribute(getPasswordParam());
password=temp!=null?temp.toString():null;
}
return password;
}
@Override
protected boolean isRememberMe(ServletRequest request) {
// TODO Auto-generated method stub
return super.isRememberMe(request);
}
} |
AtomicLong initValue = new AtomicLong(maxLoginAttempts);
AtomicLong remainLoginAttempts = accountLockMap.putIfAbsent(getUsername(request), new AtomicLong(maxLoginAttempts));
if (remainLoginAttempts == null) {
remainLoginAttempts = initValue;
}
remainLoginAttempts.getAndDecrement();
accountLockMap.put(getUsername(request), remainLoginAttempts);
| 1,339 | 129 | 1,468 |
287 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/MyRolesAuthorizationFilter.java | MyRolesAuthorizationFilter | onAccessDenied | class MyRolesAuthorizationFilter extends RolesAuthorizationFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
} |
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
// this.saveRequestAndRedirectToLogin(request, response);
WebUtils.toHttp(response).sendError(401);
} else {
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(403);
}
}
return false;
| 56 | 156 | 212 |
288 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/security/filter/MyUserFilter.java | MyUserFilter | redirectToLogin | class MyUserFilter extends UserFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request,ServletResponse response, Object mappedValue) {
return super.isAccessAllowed(request,response,mappedValue);
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
return super.onAccessDenied(request, response);
}
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
} |
// super.redirectToLogin(request, response);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
try {
HttpResult httpResult = HttpResult.buildResult(HttpStatus.NOLOGIN);
JSONObject responseJSONObject = JSONObject.fromObject(httpResult);
writer.write(responseJSONObject.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
| 137 | 158 | 295 |
289 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/web/Token.java | Token | getToken | class Token {
/***
* 设置令牌
* @param request
*/
public static void setToken(HttpServletRequest request){
request.getSession().setAttribute("sessionToken", UUID.randomUUID().toString() );
}
public static String getToken(HttpServletRequest request){<FILL_FUNCTION_BODY>}
/***
* 验证是否为重复提交
* @param request
* @return String true非重复提交,false重复提交,error非法操作
*/
public static boolean validToken(HttpServletRequest request){
String sessionToken = (String)request.getSession().getAttribute("sessionToken");
String requestToken = request.getParameter("sessionToken");
// System.out.println("sessionToken1:"+sessionToken);
// System.out.println("requestToken1:"+requestToken);
if(null == sessionToken || "null".equals(sessionToken)){
sessionToken = "";
}
if(null == requestToken || "null".equals(requestToken) ){
requestToken = "";
}
if(sessionToken.equals(requestToken)){
//返回前一定要重置session中的SesToken
request.getSession().setAttribute("sessionToken",UUID.randomUUID().toString() );
//非重复提交
return true;
}else{
//返回前一定要重置session中的SesToken
request.getSession().setAttribute("sessionToken", UUID.randomUUID().toString() );
//重复提交
return false;
}
}
} |
String sessionToken = (String)request.getSession().getAttribute("sessionToken");
if(null == sessionToken || "".equals(sessionToken)){
sessionToken = UUID.randomUUID().toString();
request.getSession().setAttribute("sessionToken",sessionToken );
//把这个sessionToken保存在redis中
//然后判断的时候根据redis是否有这个sessionToken,有看是不是使用过,使用过不能可以用
}
return sessionToken;
| 399 | 116 | 515 |
290 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/xss/esapi/ManageSecurityFilter.java | ManageSecurityFilter | doFilter | class ManageSecurityFilter implements Filter {
private static final String FILTER_APPLIED = ManageSecurityFilter.class.getName() + ".FILTERED";
private Set<String> excludePathRegex = new HashSet<String>();
public void setExcludePathRegex(Set<String> excludePathRegex) {
this.excludePathRegex = excludePathRegex;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
}
} |
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
throw new ServletException("XSSFilter just supports HTTP requests");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String uri = httpRequest.getRequestURI();
for (String regex : excludePathRegex) {
if (uri.matches(regex)) {
chain.doFilter(request, response);
return;
}
}
// Apply Filter
if (null != httpRequest.getAttribute(FILTER_APPLIED)) {
chain.doFilter(request, response);
return;
}
try {
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
SecurityRequestWrapper requestWrapper = new SecurityRequestWrapper(httpRequest);
chain.doFilter(requestWrapper, response);
} finally {
httpRequest.removeAttribute(FILTER_APPLIED);
}
| 176 | 248 | 424 |
291 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/plugs/zxing/ZxingUtil.java | ZxingUtil | qRCodeCommon | class ZxingUtil {
public static BufferedImage qRCodeCommon(String content, String imgType, int size){<FILL_FUNCTION_BODY>}
} |
int imgSize = 67 + 12 * (size - 1);
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try{
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}catch (WriterException e){
e.printStackTrace();
}
return null;
| 46 | 179 | 225 |
292 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/service/BaseServiceImpl.java | BaseServiceImpl | getBaseDao | class BaseServiceImpl<T extends IdEntity, ID extends Serializable>
implements BaseService<T, ID> {
protected BaseDao<T, ID> baseDao;
protected BaseDao<T, ID> getBaseDao() {<FILL_FUNCTION_BODY>}
@Override
public void save(T t) {
String id = t.getId();
if (id != null && "".equals(id)) {
t.setId(null);
}
getBaseDao().save(t);
}
@Override
public void delete(T t) {
getBaseDao().delete(t);
}
public void delete(ID id) {
getBaseDao().delete(get(id));
};
public T get(ID id) {
return getBaseDao().get(id);
}
public T getModel(ID id) {
return getBaseDao().getModel(id);
};
@Override
public T findById(ID id) {
return getBaseDao().findUniqueBy("id",id);
}
@Override
public List<T> findList(Criterion... criterions) {
return getBaseDao().find(criterions);
}
@Override
public Page<T> findPage(Page<T> page, Criterion... criterions) {
return getBaseDao().findPage(page, criterions);
}
public Page<T> findPageByCri(Page<T> page, List<Criterion> criterions) {
return getBaseDao().findPageByCri(page, criterions);
}
} |
if (baseDao == null) {
setBaseDao();
}
return baseDao;
| 462 | 37 | 499 |
293 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/BuildHtml.java | BuildHtml | writeLocal | class BuildHtml {
/**
* 内容输入到本地
* @param fileName
* @param fileRealPath
* @param os
* @throws IOException
* @throws FileNotFoundException
*/
public static File writeLocal(String fileName, String fileRealPath,
final ByteArrayOutputStream os) throws IOException,
FileNotFoundException {<FILL_FUNCTION_BODY>}
} |
File file2 = new File(fileRealPath);
if (!file2.exists() || !file2.isDirectory()) {
file2.mkdirs();
}
File file = new File(fileRealPath + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
os.writeTo(fos);
fos.close();
return file;
| 119 | 134 | 253 |
294 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/CookieUtils.java | CookieUtils | getCookie | class CookieUtils {
/**
* 添加cookie
*
* @param response
* @param name
* Cookie的名称,不能为null
* @param value
* Cookie的值,默认值空字符串
* @param maxAge
* @param path
* 默认值'/'
*/
public static void addCookie(HttpServletResponse response, String name,
String value, Integer maxAge, String path) {
if (value == null) {
value = "";
}
if (path == null) {
path = "/";
}
Cookie cookie = new Cookie(name, value);
cookie.setPath(path);
if (maxAge != null) {
cookie.setMaxAge(maxAge);
}
response.addCookie(cookie);
}
/**
* 设置cookie
*
* @param response
* @param name
* cookie名字
* @param value
* cookie值
* @param maxAge
* cookie生命周期 以秒为单位
*/
public static void addCookie(HttpServletResponse response, String name,
String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge > 0)
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
* @param request
* @param cookieName
* @return 指定的cookie
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {<FILL_FUNCTION_BODY>}
} |
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
for (Cookie c : cookies) {
if (c.getName().equals(cookieName)) {
return c;
}
}
return null;
| 514 | 92 | 606 |
295 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/DiaowenProperty.java | DiaowenProperty | processProperties | class DiaowenProperty extends
PropertyPlaceholderConfigurer {
public static String STORAGE_URL_PREFIX = null;
public static String SURVEYURL_MODE = "auto";
public static String WEBSITE_URL = "http://192.168.3.20:8080/#";
// private static Map<String, String> ctxPropertiesMap;
public static String LICENSE_DESC = null;
public static String LICENSE_ORGAN = null;
public static String LICENSE_EMAIL = null;
public static String LICENSE_TYPENAME = null;
public static String LICENSE_DOMAIN = null;
public static String LICENSE_CREATIONDATE = null;
public static String LICENSE_SERVERID = null;
public static String LICENSE_ID = null;
public static String LICENSE_VERSION = null;
public static String LICENSE_EVALUATION = null;
public static String LICENSE_PUBLICKEY = null;
public static String LICENSE_SIGN = null;
@Override
protected void processProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props) throws BeansException {<FILL_FUNCTION_BODY>}
/*
public static String getContextProperty(String name) {
return ctxPropertiesMap.get(name);
}
*/
public void diaowenInit(){
}
} |
super.processProperties(beanFactoryToProcess, props);
/*STORAGE_URL_PREFIX = props.getProperty("dw.storage.url_prefix");
SURVEYURL_MODE = props.getProperty("dw.surveyurl.mode");
WEBSITE_URL = props.getProperty("dw.website.url");
LICENSE_DESC = props.getProperty("dw.license.description");
LICENSE_ORGAN = props.getProperty("dw.license.organisation");
LICENSE_EMAIL = props.getProperty("dw.license.email");
LICENSE_TYPENAME = props.getProperty("dw.license.licenseTypeName");
LICENSE_CREATIONDATE = props.getProperty("dw.license.creationDate");
LICENSE_DOMAIN = props.getProperty("dw.license.licenseDomain");
LICENSE_SERVERID = props.getProperty("dw.license.serverId");
LICENSE_ID = props.getProperty("dw.license.licenseId");
LICENSE_VERSION = props.getProperty("dw.license.licenseVersion");
LICENSE_EVALUATION = props.getProperty("dw.license.evaluation");
LICENSE_PUBLICKEY = props.getProperty("dw.license.publickey");
LICENSE_SIGN = props.getProperty("dw.license.sign");
*/
/*
ctxPropertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
*/
| 350 | 444 | 794 |
296 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/DwWriteFile.java | DwWriteFile | writeOS | class DwWriteFile {
/**
* OS写到文件
* @param fileName
* @param fileRealPath
* @param os
* @throws IOException
* @throws FileNotFoundException
*/
public static File writeOS(String fileName, String fileRealPath, final ByteArrayOutputStream os) throws IOException,
FileNotFoundException {<FILL_FUNCTION_BODY>}
} |
fileRealPath = fileRealPath.substring(fileRealPath.lastIndexOf("/wjHtml")+1);
// fileRealPath = "/Users/xiajunlanna/IdeaProjects/dwsurvey/target/"+fileRealPath;
fileRealPath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH+fileRealPath;
File file = new File(fileRealPath);
if (!file.isDirectory() || !file.exists()) {
file.mkdirs();
}
File newFile = new File(fileRealPath + fileName);
if (!newFile.exists()) {
newFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(newFile);
os.writeTo(fos);
fos.close();
return newFile;
| 115 | 233 | 348 |
297 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/DwsUtils.java | DwsUtils | downloadFile | class DwsUtils {
public static String BASEURL_DEFAULT = "http://www.surveyform.cn";
public static String baseUrl(HttpServletRequest request){
String baseUrl = "";
baseUrl = request.getScheme() +"://" + request.getServerName()
+ (request.getServerPort() == 80 || request.getServerPort() == 443 ? "" : ":" +request.getServerPort())
+ request.getContextPath();
return baseUrl;
}
public static Date str2Date(String date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static void downloadFile(HttpServletResponse response, String fileName, String downFilePath) throws IOException {<FILL_FUNCTION_BODY>}
} |
downFilePath = downFilePath.replace("/", File.separator);
downFilePath = downFilePath.replace("\\", File.separator);
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
FileInputStream in = new FileInputStream(downFilePath);
//创建输出流
OutputStream out = response.getOutputStream();
//创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区当中
while((len=in.read(buffer))>0){
//输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
//关闭文件输入流
in.close();
//关闭输出流
out.close();
| 255 | 230 | 485 |
298 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/EncodeUtils.java | EncodeUtils | urlDecode | class EncodeUtils {
private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final String DEFAULT_URL_ENCODING = "UTF-8";
/**
* Hex编码, byte[]->String.
*/
public static String encodeHex(byte[] input) {
return Hex.encodeHexString(input);
}
/**
* Hex解码, String->byte[].
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException("Hex Decoder exception", e);
}
}
/**
* Base64编码, byte[]->String.
*/
public static String encodeBase64(byte[] input) {
return Base64.encodeBase64String(input);
}
/**
* Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
*/
public static String encodeUrlSafeBase64(byte[] input) {
return Base64.encodeBase64URLSafeString(input);
}
/**
* Base64解码, String->byte[].
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input);
}
/**
* Base62(0_9A_Za_z)编码数字, long->String.
*/
public static String encodeBase62(long num) {
return alphabetEncode(num, 62);
}
/**
* Base62(0_9A_Za_z)解码数字, String->long.
*/
public static long decodeBase62(String str) {
return alphabetDecode(str, 62);
}
private static String alphabetEncode(long num, int base) {
num = Math.abs(num);
StringBuilder sb = new StringBuilder();
for (; num > 0; num /= base) {
sb.append(ALPHABET.charAt((int) (num % base)));
}
return sb.toString();
}
private static long alphabetDecode(String str, int base) {
AssertUtils.hasText(str);
long result = 0;
for (int i = 0; i < str.length(); i++) {
result += ALPHABET.indexOf(str.charAt(i)) * Math.pow(base, i);
}
return result;
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String urlEncode(String part) {
try {
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String urlDecode(String part) {<FILL_FUNCTION_BODY>}
/**
* Html 转码.
*/
public static String htmlEscape(String html) {
return StringEscapeUtils.escapeHtml(html);
}
/**
* Html 解码.
*/
public static String htmlUnescape(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String xmlEscape(String xml) {
return StringEscapeUtils.escapeXml(xml);
}
/**
* Xml 解码.
*/
public static String xmlUnescape(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
} |
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.unchecked(e);
}
| 1,148 | 63 | 1,211 |
299 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/ExceptionUtils.java | ExceptionUtils | unchecked | class ExceptionUtils {
/**
* 将CheckedException转换为UnCheckedException.
*/
public static RuntimeException unchecked(Exception e) {<FILL_FUNCTION_BODY>}
} |
if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException(e.getMessage(), e);
| 59 | 43 | 102 |
300 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/HttpRequest.java | HttpRequest | sendGet | class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {<FILL_FUNCTION_BODY>}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
} |
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
| 638 | 358 | 996 |