gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2017 Globus Ltd.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.globusltd.recyclerview.choice;
import android.os.Bundle;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import com.globusltd.collections.LongArrayList;
/**
* {@link ChoiceMode} that allows multiple choices in a modal selection mode.
*/
public class MultipleModalChoiceMode extends ObservableChoiceMode {
private static final String KEY_MULTIPLE_CHOICE_MODE = "multiple_choice_mode";
private static final String KEY_CHECKED_IDS = "checked_ids";
@NonNull
private final ActionModeCompat mActionModeCompat;
@NonNull
private final ActionModeCallbacks mActionModeCallbacks;
private boolean mStartOnSingleTapEnabled = false;
private boolean mFinishActionModeOnClearEnabled = true;
/**
* Controls choice mode modal. Null when inactive.
*/
@Nullable
private ActionMode mActionMode;
/**
* Running state of which IDs are currently checked.
* If there is a value for a given key, the checked state for that ID is true.
*/
@NonNull
private final LongArrayList mCheckedIds;
public MultipleModalChoiceMode(@NonNull final ActionModeCompat actionModeCompat,
@NonNull final ModalChoiceModeListener listener) {
this(actionModeCompat, listener, null);
}
public MultipleModalChoiceMode(@NonNull final ActionModeCompat actionModeCompat,
@NonNull final ModalChoiceModeListener listener,
@Nullable final Bundle savedInstanceState) {
super();
mActionModeCompat = actionModeCompat;
mActionModeCallbacks = new ActionModeCallbacks(listener);
mCheckedIds = new LongArrayList();
final Bundle state = (savedInstanceState != null ?
savedInstanceState.getBundle(KEY_MULTIPLE_CHOICE_MODE) : null);
if (state != null) {
final LongArrayList checkedIdStates = state.getParcelable(KEY_CHECKED_IDS);
if (checkedIdStates == null) {
throw new IllegalArgumentException("Did you put checked id states to the saved state?");
}
final int count = checkedIdStates.size();
mCheckedIds.clear();
for (int i = 0; i < count; i++) {
mCheckedIds.add(checkedIdStates.get(i));
}
}
}
/**
* Allows to start modal choice on single tap.
* By default long tap is required.
*/
public void setStartOnSingleTapEnabled(final boolean enabled) {
mStartOnSingleTapEnabled = enabled;
}
/**
* Allows action mode be opened when no items are checked.
* By default is enabled.
*/
public void setFinishActionModeOnClearEnabled(final boolean enabled) {
mFinishActionModeOnClearEnabled = enabled;
}
/**
* {@inheritDoc}
*/
@Override
public boolean requiresStableIds() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean requiresLongpress() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isActivated() {
return (mActionMode != null);
}
/**
* {@inheritDoc}
*/
@IntRange(from = 0, to = 1)
@Override
public int getCheckedItemCount() {
return mCheckedIds.size();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isItemChecked(final long itemId) {
return mCheckedIds.contains(itemId);
}
/**
* {@inheritDoc}
*/
@Override
public void setItemChecked(final long itemId, final boolean checked) {
setItemCheckedInternal(itemId, checked, false);
}
private void setItemCheckedInternal(final long itemId, final boolean checked,
final boolean fromUser) {
if (checked) {
startActionMode(fromUser);
}
final int indexOf = mCheckedIds.indexOf(itemId);
if (indexOf > -1) {
mCheckedIds.removeAt(indexOf);
}
if (checked) {
mCheckedIds.add(itemId);
}
if (mActionMode != null) {
mActionModeCallbacks.onItemCheckedStateChanged(mActionMode, itemId, checked, fromUser);
}
notifyItemCheckedChanged(itemId, fromUser);
}
/**
* Returns an unsorted {@link LongArrayList} of checked item ids.
* Don't modify it without copying.
*/
@NonNull
public LongArrayList getCheckedItems() {
return mCheckedIds;
}
/**
* {@inheritDoc}
*/
@Override
public void clearChoices() {
clearChoicesInternal(false);
}
private void clearChoicesInternal(final boolean fromDestroyCallback) {
mCheckedIds.clear();
notifyAllItemsCheckedChanged(false);
if (!fromDestroyCallback && mActionMode != null) {
if (mFinishActionModeOnClearEnabled) {
mActionMode.finish();
} else {
mActionMode.invalidate();
}
}
}
@Override
public boolean onClick(final long itemId) {
if (mActionMode == null && mStartOnSingleTapEnabled) {
setItemCheckedInternal(itemId, true, true);
return true;
} else if (mActionMode != null) {
final boolean checked = !isItemChecked(itemId);
setItemCheckedInternal(itemId, checked, true);
return true;
}
return false;
}
@Override
public boolean onLongClick(final long itemId) {
setItemCheckedInternal(itemId, true, true);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void registerChoiceModeObserver(@NonNull final ChoiceModeObserver observer) {
super.registerChoiceModeObserver(observer);
// Restore action mode when choice mode is registered
if (!mCheckedIds.isEmpty()) {
startActionMode(false);
}
}
private void startActionMode(final boolean fromUser) {
if (mActionMode == null) {
mActionMode = mActionModeCompat.startActionMode(mActionModeCallbacks);
notifyAllItemsCheckedChanged(fromUser);
}
}
/**
* {@inheritDoc}
*/
@Override
public void unregisterChoiceModeObserver(@NonNull final ChoiceModeObserver observer) {
super.unregisterChoiceModeObserver(observer);
// It's safe to call finishActionMode here because normally
// {@link onSaveInstanceState(Bundle)} will be called before
// detach and per-instance state will be saved.
finishActionMode();
}
/**
* Finish and close this action mode. The action mode's {@link ModalChoiceModeListener} will
* have its {@link ModalChoiceModeListener#onDestroyActionMode(ActionMode)} method called.
*/
public void finish() {
clearChoicesInternal(true);
finishActionMode();
}
private void finishActionMode() {
if (mActionMode != null) {
mActionMode.finish();
mActionMode = null;
}
}
/**
* Call this method to retrieve per-instance state before UI component being killed
* so that the state can be restored via constructor.
*
* @param outState Bundle in which to place your saved state.
*/
public void onSaveInstanceState(@NonNull final Bundle outState) {
final Bundle state = new Bundle();
state.putParcelable(KEY_CHECKED_IDS, new LongArrayList(mCheckedIds));
outState.putBundle(KEY_MULTIPLE_CHOICE_MODE, state);
}
private class ActionModeCallbacks implements ModalChoiceModeListener {
private boolean mFinishFromUser;
@NonNull
private ModalChoiceModeListener mModalChoiceModeListener;
private ActionModeCallbacks(@NonNull final ModalChoiceModeListener listener) {
mModalChoiceModeListener = listener;
}
@Override
public boolean onCreateActionMode(final ActionMode mode, final Menu menu) {
return mModalChoiceModeListener.onCreateActionMode(mode, menu);
}
@Override
public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
return mModalChoiceModeListener.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
return mModalChoiceModeListener.onActionItemClicked(mode, item);
}
@Override
public void onDestroyActionMode(final ActionMode mode) {
// Ending selection mode means deselecting everything
clearChoicesInternal(true);
mModalChoiceModeListener.onDestroyActionMode(mode);
mActionMode = null;
notifyAllItemsCheckedChanged(mFinishFromUser);
mFinishFromUser = false;
}
@Override
public void onItemCheckedStateChanged(@NonNull final ActionMode mode, final long itemId,
final boolean checked, final boolean fromUser) {
mode.invalidate();
mModalChoiceModeListener.onItemCheckedStateChanged(mode, itemId, checked, fromUser);
// If there are no items selected we no longer need the selection mode.
if (mFinishActionModeOnClearEnabled && getCheckedItemCount() == 0) {
mFinishFromUser = true;
mode.finish();
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.CRYPTO_XATTR_FILE_ENCRYPTION_INFO;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivilegedExceptionAction;
import java.util.AbstractMap;
import java.util.concurrent.ExecutorService;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.crypto.CipherSuite;
import org.apache.hadoop.crypto.CryptoProtocolVersion;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.UnresolvedLinkException;
import org.apache.hadoop.fs.XAttr;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.hdfs.XAttrHelper;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ZoneReencryptionStatus;
import org.apache.hadoop.hdfs.protocol.SnapshotAccessControlException;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ReencryptionInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ZoneEncryptionInfoProto;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.hdfs.server.namenode.FSDirectory.DirOp;
import org.apache.hadoop.hdfs.server.namenode.ReencryptionUpdater.FileEdekInfo;
import org.apache.hadoop.security.SecurityUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.hadoop.util.Time;
import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.CRYPTO_XATTR_ENCRYPTION_ZONE;
import static org.apache.hadoop.util.Time.monotonicNow;
/**
* Helper class to perform encryption zone operation.
*/
final class FSDirEncryptionZoneOp {
/**
* Private constructor for preventing FSDirEncryptionZoneOp object creation.
* Static-only class.
*/
private FSDirEncryptionZoneOp() {}
/**
* Invoke KeyProvider APIs to generate an encrypted data encryption key for
* an encryption zone. Should not be called with any locks held.
*
* @param fsd fsdirectory
* @param ezKeyName key name of an encryption zone
* @return New EDEK, or null if ezKeyName is null
* @throws IOException
*/
private static EncryptedKeyVersion generateEncryptedDataEncryptionKey(
final FSDirectory fsd, final String ezKeyName) throws IOException {
// must not be holding lock during this operation
assert !fsd.getFSNamesystem().hasReadLock();
assert !fsd.getFSNamesystem().hasWriteLock();
if (ezKeyName == null) {
return null;
}
long generateEDEKStartTime = monotonicNow();
// Generate EDEK with login user (hdfs) so that KMS does not need
// an extra proxy configuration allowing hdfs to proxy its clients and
// KMS does not need configuration to allow non-hdfs user GENERATE_EEK
// operation.
EncryptedKeyVersion edek = SecurityUtil.doAsLoginUser(
new PrivilegedExceptionAction<EncryptedKeyVersion>() {
@Override
public EncryptedKeyVersion run() throws IOException {
try {
return fsd.getProvider().generateEncryptedKey(ezKeyName);
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
});
long generateEDEKTime = monotonicNow() - generateEDEKStartTime;
NameNode.getNameNodeMetrics().addGenerateEDEKTime(generateEDEKTime);
Preconditions.checkNotNull(edek);
return edek;
}
static KeyProvider.Metadata ensureKeyIsInitialized(final FSDirectory fsd,
final String keyName, final String src) throws IOException {
KeyProviderCryptoExtension provider = fsd.getProvider();
if (provider == null) {
throw new IOException("Can't create an encryption zone for " + src
+ " since no key provider is available.");
}
if (keyName == null || keyName.isEmpty()) {
throw new IOException("Must specify a key name when creating an "
+ "encryption zone");
}
EncryptionFaultInjector.getInstance().ensureKeyIsInitialized();
KeyProvider.Metadata metadata = provider.getMetadata(keyName);
if (metadata == null) {
/*
* It would be nice if we threw something more specific than
* IOException when the key is not found, but the KeyProvider API
* doesn't provide for that. If that API is ever changed to throw
* something more specific (e.g. UnknownKeyException) then we can
* update this to match it, or better yet, just rethrow the
* KeyProvider's exception.
*/
throw new IOException("Key " + keyName + " doesn't exist.");
}
// If the provider supports pool for EDEKs, this will fill in the pool
provider.warmUpEncryptedKeys(keyName);
return metadata;
}
/**
* Create an encryption zone on directory path using the specified key.
*
* @param fsd fsdirectory
* @param srcArg the path of a directory which will be the root of the
* encryption zone. The directory must be empty
* @param pc permission checker to check fs permission
* @param cipher cipher
* @param keyName name of a key which must be present in the configured
* KeyProvider
* @param logRetryCache whether to record RPC ids in editlog for retry cache
* rebuilding
* @return FileStatus
* @throws IOException
*/
static FileStatus createEncryptionZone(final FSDirectory fsd,
final String srcArg, final FSPermissionChecker pc, final String cipher,
final String keyName, final boolean logRetryCache) throws IOException {
final CipherSuite suite = CipherSuite.convert(cipher);
List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1);
// For now this is hard coded, as we only support one method.
final CryptoProtocolVersion version =
CryptoProtocolVersion.ENCRYPTION_ZONES;
final INodesInPath iip;
fsd.writeLock();
try {
iip = fsd.resolvePath(pc, srcArg, DirOp.WRITE);
final XAttr ezXAttr = fsd.ezManager.createEncryptionZone(iip, suite,
version, keyName);
xAttrs.add(ezXAttr);
} finally {
fsd.writeUnlock();
}
fsd.getEditLog().logSetXAttrs(iip.getPath(), xAttrs, logRetryCache);
return fsd.getAuditFileInfo(iip);
}
/**
* Get the encryption zone for the specified path.
*
* @param fsd fsdirectory
* @param srcArg the path of a file or directory to get the EZ for
* @param pc permission checker to check fs permission
* @return the EZ with file status.
*/
static Map.Entry<EncryptionZone, FileStatus> getEZForPath(
final FSDirectory fsd, final String srcArg, final FSPermissionChecker pc)
throws IOException {
final INodesInPath iip;
final EncryptionZone ret;
fsd.readLock();
try {
iip = fsd.resolvePath(pc, srcArg, DirOp.READ);
if (fsd.isPermissionEnabled()) {
fsd.checkPathAccess(pc, iip, FsAction.READ);
}
ret = fsd.ezManager.getEZINodeForPath(iip);
} finally {
fsd.readUnlock();
}
FileStatus auditStat = fsd.getAuditFileInfo(iip);
return new AbstractMap.SimpleImmutableEntry<>(ret, auditStat);
}
static EncryptionZone getEZForPath(final FSDirectory fsd,
final INodesInPath iip) throws IOException {
fsd.readLock();
try {
return fsd.ezManager.getEZINodeForPath(iip);
} finally {
fsd.readUnlock();
}
}
static BatchedListEntries<EncryptionZone> listEncryptionZones(
final FSDirectory fsd, final long prevId) throws IOException {
fsd.readLock();
try {
return fsd.ezManager.listEncryptionZones(prevId);
} finally {
fsd.readUnlock();
}
}
static List<XAttr> reencryptEncryptionZone(final FSDirectory fsd,
final INodesInPath iip, final String keyVersionName) throws IOException {
assert keyVersionName != null;
return fsd.ezManager.reencryptEncryptionZone(iip, keyVersionName);
}
static List<XAttr> cancelReencryptEncryptionZone(final FSDirectory fsd,
final INodesInPath iip) throws IOException {
return fsd.ezManager.cancelReencryptEncryptionZone(iip);
}
static BatchedListEntries<ZoneReencryptionStatus> listReencryptionStatus(
final FSDirectory fsd, final long prevId)
throws IOException {
fsd.readLock();
try {
return fsd.ezManager.listReencryptionStatus(prevId);
} finally {
fsd.readUnlock();
}
}
/**
* Update re-encryption progress (submitted). Caller should
* logSync after calling this, outside of the FSN lock.
* <p>
* The reencryption status is updated during SetXAttrs.
*/
static XAttr updateReencryptionSubmitted(final FSDirectory fsd,
final INodesInPath iip, final String ezKeyVersionName)
throws IOException {
assert fsd.hasWriteLock();
Preconditions.checkNotNull(ezKeyVersionName, "ezKeyVersionName is null.");
final ZoneEncryptionInfoProto zoneProto = getZoneEncryptionInfoProto(iip);
Preconditions.checkNotNull(zoneProto, "ZoneEncryptionInfoProto is null.");
final ReencryptionInfoProto newProto = PBHelperClient
.convert(ezKeyVersionName, Time.now(), false, 0, 0, null, null);
final ZoneEncryptionInfoProto newZoneProto = PBHelperClient
.convert(PBHelperClient.convert(zoneProto.getSuite()),
PBHelperClient.convert(zoneProto.getCryptoProtocolVersion()),
zoneProto.getKeyName(), newProto);
final XAttr xattr = XAttrHelper
.buildXAttr(CRYPTO_XATTR_ENCRYPTION_ZONE, newZoneProto.toByteArray());
final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1);
xattrs.add(xattr);
FSDirXAttrOp.unprotectedSetXAttrs(fsd, iip, xattrs,
EnumSet.of(XAttrSetFlag.REPLACE));
return xattr;
}
/**
* Update re-encryption progress (start, checkpoint). Caller should
* logSync after calling this, outside of the FSN lock.
* <p>
* The reencryption status is updated during SetXAttrs.
* Original reencryption status is passed in to get existing information
* such as ezkeyVersionName and submissionTime.
*/
static XAttr updateReencryptionProgress(final FSDirectory fsd,
final INode zoneNode, final ZoneReencryptionStatus origStatus,
final String lastFile, final long numReencrypted, final long numFailures)
throws IOException {
assert fsd.hasWriteLock();
Preconditions.checkNotNull(zoneNode, "Zone node is null");
INodesInPath iip = INodesInPath.fromINode(zoneNode);
final ZoneEncryptionInfoProto zoneProto = getZoneEncryptionInfoProto(iip);
Preconditions.checkNotNull(zoneProto, "ZoneEncryptionInfoProto is null.");
Preconditions.checkNotNull(origStatus, "Null status for " + iip.getPath());
final ReencryptionInfoProto newProto = PBHelperClient
.convert(origStatus.getEzKeyVersionName(),
origStatus.getSubmissionTime(), false,
origStatus.getFilesReencrypted() + numReencrypted,
origStatus.getNumReencryptionFailures() + numFailures, null,
lastFile);
final ZoneEncryptionInfoProto newZoneProto = PBHelperClient
.convert(PBHelperClient.convert(zoneProto.getSuite()),
PBHelperClient.convert(zoneProto.getCryptoProtocolVersion()),
zoneProto.getKeyName(), newProto);
final XAttr xattr = XAttrHelper
.buildXAttr(CRYPTO_XATTR_ENCRYPTION_ZONE, newZoneProto.toByteArray());
final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1);
xattrs.add(xattr);
FSDirXAttrOp.unprotectedSetXAttrs(fsd, iip, xattrs,
EnumSet.of(XAttrSetFlag.REPLACE));
return xattr;
}
/**
* Log re-encrypt complete (cancel, or 100% re-encrypt) to edits.
* Caller should logSync after calling this, outside of the FSN lock.
* <p>
* Original reencryption status is passed in to get existing information,
* this should include whether it is finished due to cancellation.
* The reencryption status is updated during SetXAttrs for completion time.
*/
static List<XAttr> updateReencryptionFinish(final FSDirectory fsd,
final INodesInPath zoneIIP, final ZoneReencryptionStatus origStatus)
throws IOException {
assert origStatus != null;
assert fsd.hasWriteLock();
fsd.ezManager.getReencryptionStatus()
.markZoneCompleted(zoneIIP.getLastINode().getId());
final XAttr xattr =
generateNewXAttrForReencryptionFinish(zoneIIP, origStatus);
final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1);
xattrs.add(xattr);
FSDirXAttrOp.unprotectedSetXAttrs(fsd, zoneIIP, xattrs,
EnumSet.of(XAttrSetFlag.REPLACE));
return xattrs;
}
static XAttr generateNewXAttrForReencryptionFinish(final INodesInPath iip,
final ZoneReencryptionStatus status) throws IOException {
final ZoneEncryptionInfoProto zoneProto = getZoneEncryptionInfoProto(iip);
final ReencryptionInfoProto newRiProto = PBHelperClient
.convert(status.getEzKeyVersionName(), status.getSubmissionTime(),
status.isCanceled(), status.getFilesReencrypted(),
status.getNumReencryptionFailures(), Time.now(), null);
final ZoneEncryptionInfoProto newZoneProto = PBHelperClient
.convert(PBHelperClient.convert(zoneProto.getSuite()),
PBHelperClient.convert(zoneProto.getCryptoProtocolVersion()),
zoneProto.getKeyName(), newRiProto);
final XAttr xattr = XAttrHelper
.buildXAttr(CRYPTO_XATTR_ENCRYPTION_ZONE, newZoneProto.toByteArray());
return xattr;
}
private static ZoneEncryptionInfoProto getZoneEncryptionInfoProto(
final INodesInPath iip) throws IOException {
final XAttr fileXAttr = FSDirXAttrOp.unprotectedGetXAttrByPrefixedName(
iip.getLastINode(), iip.getPathSnapshotId(),
CRYPTO_XATTR_ENCRYPTION_ZONE);
if (fileXAttr == null) {
throw new IOException(
"Could not find reencryption XAttr for file " + iip.getPath());
}
try {
return ZoneEncryptionInfoProto.parseFrom(fileXAttr.getValue());
} catch (InvalidProtocolBufferException e) {
throw new IOException(
"Could not parse file encryption info for " + "inode " + iip
.getPath(), e);
}
}
/**
* Save the batch's edeks to file xattrs.
*/
static void saveFileXAttrsForBatch(FSDirectory fsd,
List<FileEdekInfo> batch) {
assert fsd.getFSNamesystem().hasWriteLock();
assert !fsd.hasWriteLock();
if (batch != null && !batch.isEmpty()) {
for (FileEdekInfo entry : batch) {
final INode inode = fsd.getInode(entry.getInodeId());
// no dir lock, so inode could be removed. no-op if so.
if (inode == null) {
NameNode.LOG.info("Cannot find inode {}, skip saving xattr for"
+ " re-encryption", entry.getInodeId());
continue;
}
fsd.getEditLog().logSetXAttrs(inode.getFullPathName(),
inode.getXAttrFeature().getXAttrs(), false);
}
}
}
/**
* Set the FileEncryptionInfo for an INode.
*
* @param fsd fsdirectory
* @param info file encryption information
* @param flag action when setting xattr. Either CREATE or REPLACE.
* @throws IOException
*/
static void setFileEncryptionInfo(final FSDirectory fsd,
final INodesInPath iip, final FileEncryptionInfo info,
final XAttrSetFlag flag) throws IOException {
// Make the PB for the xattr
final HdfsProtos.PerFileEncryptionInfoProto proto =
PBHelperClient.convertPerFileEncInfo(info);
final byte[] protoBytes = proto.toByteArray();
final XAttr fileEncryptionAttr =
XAttrHelper.buildXAttr(CRYPTO_XATTR_FILE_ENCRYPTION_INFO, protoBytes);
final List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1);
xAttrs.add(fileEncryptionAttr);
fsd.writeLock();
try {
FSDirXAttrOp.unprotectedSetXAttrs(fsd, iip, xAttrs, EnumSet.of(flag));
} finally {
fsd.writeUnlock();
}
}
/**
* This function combines the per-file encryption info (obtained
* from the inode's XAttrs), and the encryption info from its zone, and
* returns a consolidated FileEncryptionInfo instance. Null is returned
* for non-encrypted or raw files.
*
* @param fsd fsdirectory
* @param iip inodes in the path containing the file, passed in to
* avoid obtaining the list of inodes again
* @return consolidated file encryption info; null for non-encrypted files
*/
static FileEncryptionInfo getFileEncryptionInfo(final FSDirectory fsd,
final INodesInPath iip) throws IOException {
if (iip.isRaw() ||
!fsd.ezManager.hasCreatedEncryptionZone() ||
!iip.getLastINode().isFile()) {
return null;
}
fsd.readLock();
try {
EncryptionZone encryptionZone = getEZForPath(fsd, iip);
if (encryptionZone == null) {
// not an encrypted file
return null;
} else if(encryptionZone.getPath() == null
|| encryptionZone.getPath().isEmpty()) {
if (NameNode.LOG.isDebugEnabled()) {
NameNode.LOG.debug("Encryption zone " +
encryptionZone.getPath() + " does not have a valid path.");
}
}
XAttr fileXAttr = FSDirXAttrOp.unprotectedGetXAttrByPrefixedName(
iip.getLastINode(), iip.getPathSnapshotId(),
CRYPTO_XATTR_FILE_ENCRYPTION_INFO);
if (fileXAttr == null) {
NameNode.LOG.warn("Could not find encryption XAttr for file " +
iip.getPath() + " in encryption zone " + encryptionZone.getPath());
return null;
}
final CryptoProtocolVersion version = encryptionZone.getVersion();
final CipherSuite suite = encryptionZone.getSuite();
final String keyName = encryptionZone.getKeyName();
try {
HdfsProtos.PerFileEncryptionInfoProto fileProto =
HdfsProtos.PerFileEncryptionInfoProto.parseFrom(
fileXAttr.getValue());
return PBHelperClient.convert(fileProto, suite, version, keyName);
} catch (InvalidProtocolBufferException e) {
throw new IOException("Could not parse file encryption info for " +
"inode " + iip.getPath(), e);
}
} finally {
fsd.readUnlock();
}
}
/**
* If the file and encryption key are valid, return the encryption info,
* else throw a retry exception. The startFile method generates the EDEK
* outside of the lock so the zone must be reverified.
*
* @param dir fsdirectory
* @param iip inodes in the file path
* @param ezInfo the encryption key
* @return FileEncryptionInfo for the file
* @throws RetryStartFileException if key is inconsistent with current zone
*/
static FileEncryptionInfo getFileEncryptionInfo(FSDirectory dir,
INodesInPath iip, EncryptionKeyInfo ezInfo)
throws RetryStartFileException, IOException {
FileEncryptionInfo feInfo = null;
final EncryptionZone zone = getEZForPath(dir, iip);
if (zone != null) {
// The path is now within an EZ, but we're missing encryption parameters
if (ezInfo == null) {
throw new RetryStartFileException();
}
// Path is within an EZ and we have provided encryption parameters.
// Make sure that the generated EDEK matches the settings of the EZ.
final String ezKeyName = zone.getKeyName();
if (!ezKeyName.equals(ezInfo.edek.getEncryptionKeyName())) {
throw new RetryStartFileException();
}
feInfo = new FileEncryptionInfo(ezInfo.suite, ezInfo.protocolVersion,
ezInfo.edek.getEncryptedKeyVersion().getMaterial(),
ezInfo.edek.getEncryptedKeyIv(),
ezKeyName, ezInfo.edek.getEncryptionKeyVersionName());
}
return feInfo;
}
static boolean isInAnEZ(final FSDirectory fsd, final INodesInPath iip)
throws UnresolvedLinkException, SnapshotAccessControlException,
IOException {
if (!fsd.ezManager.hasCreatedEncryptionZone()) {
return false;
}
fsd.readLock();
try {
return fsd.ezManager.isInAnEZ(iip);
} finally {
fsd.readUnlock();
}
}
/**
* Proactively warm up the edek cache. We'll get all the edek key names,
* then launch up a separate thread to warm them up.
*/
static void warmUpEdekCache(final ExecutorService executor,
final FSDirectory fsd, final int delay, final int interval) {
fsd.readLock();
try {
String[] edeks = fsd.ezManager.getKeyNames();
executor.execute(
new EDEKCacheLoader(edeks, fsd.getProvider(), delay, interval));
} finally {
fsd.readUnlock();
}
}
/**
* EDEKCacheLoader is being run in a separate thread to loop through all the
* EDEKs and warm them up in the KMS cache.
*/
static class EDEKCacheLoader implements Runnable {
private final String[] keyNames;
private final KeyProviderCryptoExtension kp;
private int initialDelay;
private int retryInterval;
EDEKCacheLoader(final String[] names, final KeyProviderCryptoExtension kp,
final int delay, final int interval) {
this.keyNames = names;
this.kp = kp;
this.initialDelay = delay;
this.retryInterval = interval;
}
@Override
public void run() {
NameNode.LOG.info("Warming up {} EDEKs... (initialDelay={}, "
+ "retryInterval={})", keyNames.length, initialDelay, retryInterval);
try {
Thread.sleep(initialDelay);
} catch (InterruptedException ie) {
NameNode.LOG.info("EDEKCacheLoader interrupted before warming up.");
return;
}
final int logCoolDown = 10000; // periodically print error log (if any)
int sinceLastLog = logCoolDown; // always print the first failure
boolean success = false;
IOException lastSeenIOE = null;
long warmUpEDEKStartTime = monotonicNow();
while (true) {
try {
kp.warmUpEncryptedKeys(keyNames);
NameNode.LOG
.info("Successfully warmed up {} EDEKs.", keyNames.length);
success = true;
break;
} catch (IOException ioe) {
lastSeenIOE = ioe;
if (sinceLastLog >= logCoolDown) {
NameNode.LOG.info("Failed to warm up EDEKs.", ioe);
sinceLastLog = 0;
} else {
NameNode.LOG.debug("Failed to warm up EDEKs.", ioe);
}
} catch (Exception e) {
NameNode.LOG.error("Cannot warm up EDEKs.", e);
throw e;
}
try {
Thread.sleep(retryInterval);
} catch (InterruptedException ie) {
NameNode.LOG.info("EDEKCacheLoader interrupted during retry.");
break;
}
sinceLastLog += retryInterval;
}
long warmUpEDEKTime = monotonicNow() - warmUpEDEKStartTime;
NameNode.getNameNodeMetrics().addWarmUpEDEKTime(warmUpEDEKTime);
if (!success) {
NameNode.LOG.warn("Unable to warm up EDEKs.");
if (lastSeenIOE != null) {
NameNode.LOG.warn("Last seen exception:", lastSeenIOE);
}
}
}
}
/**
* If the file is in an encryption zone, we optimistically create an
* EDEK for the file by calling out to the configured KeyProvider.
* Since this typically involves doing an RPC, the fsn lock is yielded.
*
* Since the path can flip-flop between being in an encryption zone and not
* in the meantime, the call MUST re-resolve the IIP and re-check
* preconditions if this method does not return null;
*
* @param fsn the namesystem.
* @param iip the inodes for the path
* @param supportedVersions client's supported versions
* @return EncryptionKeyInfo if the path is in an EZ, else null
*/
static EncryptionKeyInfo getEncryptionKeyInfo(FSNamesystem fsn,
INodesInPath iip, CryptoProtocolVersion[] supportedVersions)
throws IOException {
FSDirectory fsd = fsn.getFSDirectory();
// Nothing to do if the path is not within an EZ
final EncryptionZone zone = getEZForPath(fsd, iip);
if (zone == null) {
EncryptionFaultInjector.getInstance().startFileNoKey();
return null;
}
CryptoProtocolVersion protocolVersion = fsn.chooseProtocolVersion(
zone, supportedVersions);
CipherSuite suite = zone.getSuite();
String ezKeyName = zone.getKeyName();
Preconditions.checkNotNull(protocolVersion);
Preconditions.checkNotNull(suite);
Preconditions.checkArgument(!suite.equals(CipherSuite.UNKNOWN),
"Chose an UNKNOWN CipherSuite!");
Preconditions.checkNotNull(ezKeyName);
// Generate EDEK while not holding the fsn lock.
fsn.writeUnlock();
try {
EncryptionFaultInjector.getInstance().startFileBeforeGenerateKey();
return new EncryptionKeyInfo(protocolVersion, suite, ezKeyName,
generateEncryptedDataEncryptionKey(fsd, ezKeyName));
} finally {
fsn.writeLock();
EncryptionFaultInjector.getInstance().startFileAfterGenerateKey();
}
}
static class EncryptionKeyInfo {
final CryptoProtocolVersion protocolVersion;
final CipherSuite suite;
final String ezKeyName;
final KeyProviderCryptoExtension.EncryptedKeyVersion edek;
EncryptionKeyInfo(
CryptoProtocolVersion protocolVersion, CipherSuite suite,
String ezKeyName, KeyProviderCryptoExtension.EncryptedKeyVersion edek) {
this.protocolVersion = protocolVersion;
this.suite = suite;
this.ezKeyName = ezKeyName;
this.edek = edek;
}
}
/**
* Get the current key version name for the given EZ. This will first drain
* the provider's local cache, then generate a new edek.
* <p>
* The encryption key version of the newly generated edek will be used as
* the target key version of this re-encryption - meaning all edeks'
* keyVersion are compared with it, and only sent to the KMS for re-encryption
* when the version is different.
* <p>
* Note: KeyProvider has a getCurrentKey interface, but that is under
* a different ACL. HDFS should not try to operate on additional ACLs, but
* rather use the generate ACL it already has.
*/
static String getCurrentKeyVersion(final FSDirectory dir,
final FSPermissionChecker pc, final String zone) throws IOException {
assert dir.getProvider() != null;
assert !dir.hasReadLock();
final String keyName = FSDirEncryptionZoneOp.getKeyNameForZone(dir,
pc, zone);
if (keyName == null) {
throw new IOException(zone + " is not an encryption zone.");
}
// drain the local cache of the key provider.
// Do not invalidateCache on the server, since that's the responsibility
// when rolling the key version.
dir.getProvider().drain(keyName);
final EncryptedKeyVersion edek;
try {
edek = dir.getProvider().generateEncryptedKey(keyName);
} catch (GeneralSecurityException gse) {
throw new IOException(gse);
}
Preconditions.checkNotNull(edek);
return edek.getEncryptionKeyVersionName();
}
/**
* Resolve the zone to an inode, find the encryption zone info associated with
* that inode, and return the key name. Does not contact the KMS.
*/
static String getKeyNameForZone(final FSDirectory dir,
final FSPermissionChecker pc, final String zone) throws IOException {
assert dir.getProvider() != null;
final INodesInPath iip;
dir.readLock();
try {
iip = dir.resolvePath(pc, zone, DirOp.READ);
dir.ezManager.checkEncryptionZoneRoot(iip.getLastINode(), zone);
return dir.ezManager.getKeyName(iip);
} finally {
dir.readUnlock();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.thrift.struct;
import static org.apache.parquet.thrift.struct.ThriftTypeID.BOOL;
import static org.apache.parquet.thrift.struct.ThriftTypeID.BYTE;
import static org.apache.parquet.thrift.struct.ThriftTypeID.DOUBLE;
import static org.apache.parquet.thrift.struct.ThriftTypeID.ENUM;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I16;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I32;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I64;
import static org.apache.parquet.thrift.struct.ThriftTypeID.LIST;
import static org.apache.parquet.thrift.struct.ThriftTypeID.MAP;
import static org.apache.parquet.thrift.struct.ThriftTypeID.SET;
import static org.apache.parquet.thrift.struct.ThriftTypeID.STRING;
import static org.apache.parquet.thrift.struct.ThriftTypeID.STRUCT;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* Descriptor for a Thrift class.
* Used to persist the thrift schema
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "id")
@JsonSubTypes({
@JsonSubTypes.Type(value=ThriftType.BoolType.class, name="BOOL"),
@JsonSubTypes.Type(value=ThriftType.ByteType.class, name="BYTE"),
@JsonSubTypes.Type(value=ThriftType.DoubleType.class, name="DOUBLE"),
@JsonSubTypes.Type(value=ThriftType.EnumType.class, name="ENUM"),
@JsonSubTypes.Type(value=ThriftType.I16Type.class, name="I16"),
@JsonSubTypes.Type(value=ThriftType.I32Type.class, name="I32"),
@JsonSubTypes.Type(value=ThriftType.I64Type.class, name="I64"),
@JsonSubTypes.Type(value=ThriftType.ListType.class, name="LIST"),
@JsonSubTypes.Type(value=ThriftType.MapType.class, name="MAP"),
@JsonSubTypes.Type(value=ThriftType.SetType.class, name="SET"),
@JsonSubTypes.Type(value=ThriftType.StringType.class, name="STRING"),
@JsonSubTypes.Type(value=ThriftType.StructType.class, name="STRUCT")
})
public abstract class ThriftType {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ThriftType)) return false;
ThriftType that = (ThriftType) o;
if (type != that.type) return false;
return true;
}
@Override
public int hashCode() {
return type != null ? type.hashCode() : 0;
}
public static ThriftType fromJSON(String json) {
return JSON.fromJSON(json, ThriftType.class);
}
public String toJSON() {
return JSON.toJSON(this);
}
@Override
public String toString() {
return toJSON();
}
public interface StateVisitor<R, S> {
R visit(MapType mapType, S state);
R visit(SetType setType, S state);
R visit(ListType listType, S state);
R visit(StructType structType, S state);
R visit(EnumType enumType, S state);
R visit(BoolType boolType, S state);
R visit(ByteType byteType, S state);
R visit(DoubleType doubleType, S state);
R visit(I16Type i16Type, S state);
R visit(I32Type i32Type, S state);
R visit(I64Type i64Type, S state);
R visit(StringType stringType, S state);
}
/**
* @deprecated will be removed in 2.0.0; use StateVisitor instead.
*/
public interface TypeVisitor {
void visit(MapType mapType);
void visit(SetType setType);
void visit(ListType listType);
void visit(StructType structType);
void visit(EnumType enumType);
void visit(BoolType boolType);
void visit(ByteType byteType);
void visit(DoubleType doubleType);
void visit(I16Type i16Type);
void visit(I32Type i32Type);
void visit(I64Type i64Type);
void visit(StringType stringType);
}
/**
* @deprecated will be removed in 2.0.0.
*/
@Deprecated
public static abstract class ComplexTypeVisitor implements TypeVisitor {
@Override
final public void visit(EnumType enumType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(BoolType boolType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(ByteType byteType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(DoubleType doubleType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I16Type i16Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I32Type i32Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I64Type i64Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(StringType stringType) {
throw new IllegalArgumentException("Expected complex type");
}
}
public static class StructType extends ThriftType {
private final List<ThriftField> children;
private final ThriftField[] childById;
/**
* Whether a struct is a union or a regular struct is not always known, because it was not always
* written to the metadata files.
*
* We should always know this in the write path, but may not in the read path.
*/
public enum StructOrUnionType {
STRUCT,
UNION,
UNKNOWN
}
private final StructOrUnionType structOrUnionType;
@Deprecated
public StructType(List<ThriftField> children) {
this(children, null);
}
@JsonCreator
public StructType(@JsonProperty("children") List<ThriftField> children,
@JsonProperty("structOrUnionType") StructOrUnionType structOrUnionType) {
super(STRUCT);
this.structOrUnionType = structOrUnionType == null ? StructOrUnionType.STRUCT : structOrUnionType;
this.children = children;
int maxId = 0;
if (children != null) {
for (ThriftField thriftField : children) {
maxId = Math.max(maxId, thriftField.getFieldId());
}
childById = new ThriftField[maxId + 1];
for (ThriftField thriftField : children) {
childById[thriftField.getFieldId()] = thriftField;
}
} else {
childById = null;
}
}
public List<ThriftField> getChildren() {
return children;
}
@JsonIgnore
public ThriftField getChildById(short id) {
if (id >= childById.length) {
return null;
} else {
return childById[id];
}
}
@JsonProperty("structOrUnionType")
public StructOrUnionType getStructOrUnionType() {
return structOrUnionType;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StructType that = (StructType) o;
if (!Arrays.equals(childById, that.childById)) return false;
return true;
}
@Override
public int hashCode() {
int result = childById != null ? Arrays.hashCode(childById) : 0;
return result;
}
}
public static class MapType extends ThriftType {
private final ThriftField key;
private final ThriftField value;
@JsonCreator
public MapType(@JsonProperty("key") ThriftField key, @JsonProperty("value") ThriftField value) {
super(MAP);
this.key = key;
this.value = value;
}
public ThriftField getKey() {
return key;
}
public ThriftField getValue() {
return value;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MapType)) return false;
if (!super.equals(o)) return false;
MapType mapType = (MapType) o;
if (!key.equals(mapType.key)) return false;
if (!value.equals(mapType.value)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + key.hashCode();
result = 31 * result + value.hashCode();
return result;
}
}
public static class SetType extends ThriftType {
private final ThriftField values;
@JsonCreator
public SetType(@JsonProperty("values") ThriftField values) {
super(SET);
this.values = values;
}
public ThriftField getValues() {
return values;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SetType)) return false;
if (!super.equals(o)) return false;
SetType setType = (SetType) o;
if (!values.equals(setType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class ListType extends ThriftType {
private final ThriftField values;
@JsonCreator
public ListType(@JsonProperty("values") ThriftField values) {
super(LIST);
this.values = values;
}
public ThriftField getValues() {
return values;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ListType)) return false;
if (!super.equals(o)) return false;
ListType listType = (ListType) o;
if (!values.equals(listType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class EnumValue {
private final int id;
private final String name;
@JsonCreator
public EnumValue(@JsonProperty("id") int id, @JsonProperty("name") String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnumValue)) return false;
EnumValue enumValue = (EnumValue) o;
if (id != enumValue.id) return false;
if (name != null ? !name.equals(enumValue.name) : enumValue.name != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
public static class EnumType extends ThriftType {
private final List<EnumValue> values;
private Map<Integer,EnumValue> idEnumLookup;
@JsonCreator
public EnumType(@JsonProperty("values") List<EnumValue> values) {
super(ENUM);
this.values = values;
}
public Iterable<EnumValue> getValues() {
return new Iterable<EnumValue>() {
@Override
public Iterator<EnumValue> iterator() {
return values.iterator();
}
};
}
public EnumValue getEnumValueById(int id) {
prepareEnumLookUp();
return idEnumLookup.get(id);
}
private void prepareEnumLookUp() {
if (idEnumLookup == null) {
idEnumLookup=new HashMap<Integer, EnumValue>();
for (EnumValue value : values) {
idEnumLookup.put(value.getId(),value);
}
}
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnumType)) return false;
if (!super.equals(o)) return false;
EnumType enumType = (EnumType) o;
if (!values.equals(enumType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class BoolType extends ThriftType {
@JsonCreator
public BoolType() {
super(BOOL);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class ByteType extends ThriftType {
@JsonCreator
public ByteType() {
super(BYTE);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class DoubleType extends ThriftType {
@JsonCreator
public DoubleType() {
super(DOUBLE);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I16Type extends ThriftType {
@JsonCreator
public I16Type() {
super(I16);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I32Type extends ThriftType {
@JsonCreator
public I32Type() {
super(I32);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I64Type extends ThriftType {
@JsonCreator
public I64Type() {
super(I64);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class StringType extends ThriftType {
private boolean binary = false;
@JsonCreator
public StringType() {
super(STRING);
}
public boolean isBinary() {
return binary;
}
public void setBinary(boolean binary) {
this.binary = binary;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
private final ThriftTypeID type;
private ThriftType(ThriftTypeID type) {
super();
this.type = type;
}
public abstract void accept(TypeVisitor visitor);
public abstract <R, S> R accept(StateVisitor<R, S> visitor, S state);
@JsonIgnore
public ThriftTypeID getType() {
return this.type;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.connector.hbase;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.connector.hbase.source.HBaseInputFormat;
import org.apache.flink.connector.hbase.source.HBaseTableSource;
import org.apache.flink.connector.hbase.util.HBaseTableSchema;
import org.apache.flink.connector.hbase.util.HBaseTestBase;
import org.apache.flink.connector.hbase.util.PlannerType;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.bridge.java.BatchTableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.api.internal.TableImpl;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.factories.TableFactoryService;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.planner.runtime.utils.BatchTableEnvUtil;
import org.apache.flink.table.planner.runtime.utils.TableEnvUtil;
import org.apache.flink.table.planner.sinks.CollectRowTableSink;
import org.apache.flink.table.planner.sinks.CollectTableSink;
import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
import org.apache.flink.table.runtime.utils.StreamITCase;
import org.apache.flink.table.sinks.TableSink;
import org.apache.flink.table.sources.TableSource;
import org.apache.flink.test.util.TestBaseUtils;
import org.apache.flink.types.Row;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import scala.Option;
import static org.apache.flink.connector.hbase.util.PlannerType.OLD_PLANNER;
import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_PROPERTY_VERSION;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_TYPE;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_VERSION;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_TABLE_NAME;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_TYPE_VALUE_HBASE;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_VERSION_VALUE_143;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_ZK_QUORUM;
import static org.apache.flink.table.descriptors.Schema.SCHEMA;
import static org.junit.Assert.assertEquals;
/**
* IT cases for HBase connector (including HBaseTableSource and HBaseTableSink).
*/
@RunWith(Parameterized.class)
public class HBaseConnectorITCase extends HBaseTestBase {
@Parameterized.Parameter
public PlannerType planner;
@Parameterized.Parameter(1)
public boolean isLegacyConnector;
@Override
protected PlannerType planner() {
return planner;
}
@Parameterized.Parameters(name = "planner = {0}, legacy = {1}")
public static Object[] parameters() {
return new Object[][]{
new Object[]{PlannerType.BLINK_PLANNER, true},
new Object[]{PlannerType.BLINK_PLANNER, false},
new Object[]{PlannerType.OLD_PLANNER, true}
};
}
// -------------------------------------------------------------------------------------
// HBaseTableSource tests
// -------------------------------------------------------------------------------------
@Test
public void testTableSourceFullScan() throws Exception {
TableEnvironment tEnv = createBatchTableEnv();
if (isLegacyConnector) {
HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
hbaseTable.setRowKey("rowkey", Integer.class);
((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
} else {
tEnv.executeSql(
"CREATE TABLE hTable (" +
" family1 ROW<col1 INT>," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
" rowkey INT," +
" PRIMARY KEY (rowkey) NOT ENFORCED" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
Table table = tEnv.sqlQuery("SELECT " +
" h.family1.col1, " +
" h.family2.col1, " +
" h.family2.col2, " +
" h.family3.col1, " +
" h.family3.col2, " +
" h.family3.col3 " +
"FROM hTable AS h");
List<Row> results = collectBatchResult(table);
String expected =
"10,Hello-1,100,1.01,false,Welt-1\n" +
"20,Hello-2,200,2.02,true,Welt-2\n" +
"30,Hello-3,300,3.03,false,Welt-3\n" +
"40,null,400,4.04,true,Welt-4\n" +
"50,Hello-5,500,5.05,false,Welt-5\n" +
"60,Hello-6,600,6.06,true,Welt-6\n" +
"70,Hello-7,700,7.07,false,Welt-7\n" +
"80,null,800,8.08,true,Welt-8\n";
TestBaseUtils.compareResultAsText(results, expected);
}
@Test
public void testTableSourceProjection() throws Exception {
TableEnvironment tEnv = createBatchTableEnv();
if (isLegacyConnector) {
HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
hbaseTable.setRowKey("rowkey", Integer.class);
((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
} else {
tEnv.executeSql(
"CREATE TABLE hTable (" +
" family1 ROW<col1 INT>," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
" rowkey INT," +
" PRIMARY KEY (rowkey) NOT ENFORCED" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
Table table = tEnv.sqlQuery("SELECT " +
" h.family1.col1, " +
" h.family3.col1, " +
" h.family3.col2, " +
" h.family3.col3 " +
"FROM hTable AS h");
List<Row> results = collectBatchResult(table);
String expected =
"10,1.01,false,Welt-1\n" +
"20,2.02,true,Welt-2\n" +
"30,3.03,false,Welt-3\n" +
"40,4.04,true,Welt-4\n" +
"50,5.05,false,Welt-5\n" +
"60,6.06,true,Welt-6\n" +
"70,7.07,false,Welt-7\n" +
"80,8.08,true,Welt-8\n";
TestBaseUtils.compareResultAsText(results, expected);
}
@Test
public void testTableSourceFieldOrder() throws Exception {
TableEnvironment tEnv = createBatchTableEnv();
if (isLegacyConnector) {
HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
// shuffle order of column registration
hbaseTable.setRowKey("rowkey", Integer.class);
hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
} else {
tEnv.executeSql(
"CREATE TABLE hTable (" +
" rowkey INT PRIMARY KEY," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
" family1 ROW<col1 INT>" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
Table table = tEnv.sqlQuery("SELECT * FROM hTable AS h");
List<Row> results = collectBatchResult(table);
String expected =
"1,Hello-1,100,1.01,false,Welt-1,10\n" +
"2,Hello-2,200,2.02,true,Welt-2,20\n" +
"3,Hello-3,300,3.03,false,Welt-3,30\n" +
"4,null,400,4.04,true,Welt-4,40\n" +
"5,Hello-5,500,5.05,false,Welt-5,50\n" +
"6,Hello-6,600,6.06,true,Welt-6,60\n" +
"7,Hello-7,700,7.07,false,Welt-7,70\n" +
"8,null,800,8.08,true,Welt-8,80\n";
TestBaseUtils.compareResultAsText(results, expected);
}
@Test
public void testTableSourceReadAsByteArray() throws Exception {
TableEnvironment tEnv = createBatchTableEnv();
if (isLegacyConnector) {
// fetch row2 from the table till the end
HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
hbaseTable.addColumn(FAMILY2, F2COL1, byte[].class);
hbaseTable.addColumn(FAMILY2, F2COL2, byte[].class);
hbaseTable.setRowKey("rowkey", Integer.class);
((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
} else {
tEnv.executeSql(
"CREATE TABLE hTable (" +
" family2 ROW<col1 BYTES, col2 BYTES>," +
" rowkey INT" + // no primary key syntax
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
tEnv.registerFunction("toUTF8", new ToUTF8());
tEnv.registerFunction("toLong", new ToLong());
Table table = tEnv.sqlQuery(
"SELECT " +
" toUTF8(h.family2.col1), " +
" toLong(h.family2.col2) " +
"FROM hTable AS h"
);
List<Row> results = collectBatchResult(table);
String expected =
"Hello-1,100\n" +
"Hello-2,200\n" +
"Hello-3,300\n" +
"null,400\n" +
"Hello-5,500\n" +
"Hello-6,600\n" +
"Hello-7,700\n" +
"null,800\n";
TestBaseUtils.compareResultAsText(results, expected);
}
@Test
public void testTableInputFormat() throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Tuple1<Integer>> result = env
.createInput(new InputFormatForTestTable(getConf()))
.reduce((ReduceFunction<Tuple1<Integer>>) (v1, v2) -> Tuple1.of(v1.f0 + v2.f0));
List<Tuple1<Integer>> resultSet = result.collect();
assertEquals(1, resultSet.size());
assertEquals(360, (int) resultSet.get(0).f0);
}
// -------------------------------------------------------------------------------------
// HBaseTableSink tests
// -------------------------------------------------------------------------------------
// prepare a source collection.
private static final List<Row> testData1 = new ArrayList<>();
private static final RowTypeInfo testTypeInfo1 = new RowTypeInfo(
new TypeInformation[]{Types.INT, Types.INT, Types.STRING, Types.LONG, Types.DOUBLE,
Types.BOOLEAN, Types.STRING, Types.SQL_TIMESTAMP, Types.SQL_DATE, Types.SQL_TIME},
new String[]{"rowkey", "f1c1", "f2c1", "f2c2", "f3c1", "f3c2", "f3c3", "f4c1", "f4c2", "f4c3"});
static {
testData1.add(Row.of(1, 10, "Hello-1", 100L, 1.01, false, "Welt-1",
Timestamp.valueOf("2019-08-18 19:00:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:00:00")));
testData1.add(Row.of(2, 20, "Hello-2", 200L, 2.02, true, "Welt-2",
Timestamp.valueOf("2019-08-18 19:01:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:01:00")));
testData1.add(Row.of(3, 30, "Hello-3", 300L, 3.03, false, "Welt-3",
Timestamp.valueOf("2019-08-18 19:02:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:02:00")));
testData1.add(Row.of(4, 40, null, 400L, 4.04, true, "Welt-4",
Timestamp.valueOf("2019-08-18 19:03:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:03:00")));
testData1.add(Row.of(5, 50, "Hello-5", 500L, 5.05, false, "Welt-5",
Timestamp.valueOf("2019-08-19 19:10:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:10:00")));
testData1.add(Row.of(6, 60, "Hello-6", 600L, 6.06, true, "Welt-6",
Timestamp.valueOf("2019-08-19 19:20:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:20:00")));
testData1.add(Row.of(7, 70, "Hello-7", 700L, 7.07, false, "Welt-7",
Timestamp.valueOf("2019-08-19 19:30:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:30:00")));
testData1.add(Row.of(8, 80, null, 800L, 8.08, true, "Welt-8",
Timestamp.valueOf("2019-08-19 19:40:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:40:00")));
}
@Test
public void testTableSink() throws Exception {
StreamExecutionEnvironment execEnv = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(execEnv, streamSettings);
if (isLegacyConnector) {
HBaseTableSchema schema = new HBaseTableSchema();
schema.addColumn(FAMILY1, F1COL1, Integer.class);
schema.addColumn(FAMILY2, F2COL1, String.class);
schema.addColumn(FAMILY2, F2COL2, Long.class);
schema.setRowKey("rk", Integer.class);
schema.addColumn(FAMILY3, F3COL1, Double.class);
schema.addColumn(FAMILY3, F3COL2, Boolean.class);
schema.addColumn(FAMILY3, F3COL3, String.class);
Map<String, String> tableProperties = new HashMap<>();
tableProperties.put("connector.type", "hbase");
tableProperties.put("connector.version", "1.4.3");
tableProperties.put("connector.property-version", "1");
tableProperties.put("connector.table-name", TEST_TABLE_2);
tableProperties.put("connector.zookeeper.quorum", getZookeeperQuorum());
tableProperties.put("connector.zookeeper.znode.parent", "/hbase");
DescriptorProperties descriptorProperties = new DescriptorProperties(true);
descriptorProperties.putTableSchema(SCHEMA, schema.convertsToTableSchema());
descriptorProperties.putProperties(tableProperties);
TableSink tableSink = TableFactoryService
.find(HBaseTableFactory.class, descriptorProperties.asMap())
.createTableSink(descriptorProperties.asMap());
((TableEnvironmentInternal) tEnv).registerTableSinkInternal("hbase", tableSink);
} else {
tEnv.executeSql(
"CREATE TABLE hbase (" +
" family1 ROW<col1 INT>," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" rk INT," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'," +
" 'zookeeper.znode.parent' = '/hbase'" +
")");
}
DataStream<Row> ds = execEnv.fromCollection(testData1).returns(testTypeInfo1);
tEnv.createTemporaryView("src", ds);
String query = "INSERT INTO hbase SELECT ROW(f1c1), ROW(f2c1, f2c2), rowkey, ROW(f3c1, f3c2, f3c3) FROM src";
TableEnvUtil.execInsertSqlAndWaitResult(tEnv, query);
// start a batch scan job to verify contents in HBase table
// start a batch scan job to verify contents in HBase table
TableEnvironment batchTableEnv = createBatchTableEnv();
if (isLegacyConnector) {
HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_2);
hbaseTable.setRowKey("rowkey", Integer.class);
hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
((TableEnvironmentInternal) batchTableEnv).registerTableSourceInternal("hTable", hbaseTable);
} else {
batchTableEnv.executeSql(
"CREATE TABLE hTable (" +
" rowkey INT," +
" family1 ROW<col1 INT>," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
Table table = batchTableEnv.sqlQuery(
"SELECT " +
" h.rowkey, " +
" h.family1.col1, " +
" h.family2.col1, " +
" h.family2.col2, " +
" h.family3.col1, " +
" h.family3.col2, " +
" h.family3.col3 " +
"FROM hTable AS h"
);
List<Row> results = collectBatchResult(table);
String expected =
"1,10,Hello-1,100,1.01,false,Welt-1\n" +
"2,20,Hello-2,200,2.02,true,Welt-2\n" +
"3,30,Hello-3,300,3.03,false,Welt-3\n" +
"4,40,null,400,4.04,true,Welt-4\n" +
"5,50,Hello-5,500,5.05,false,Welt-5\n" +
"6,60,Hello-6,600,6.06,true,Welt-6\n" +
"7,70,Hello-7,700,7.07,false,Welt-7\n" +
"8,80,null,800,8.08,true,Welt-8\n";
TestBaseUtils.compareResultAsText(results, expected);
}
@Test
public void testTableSourceSinkWithDDL() throws Exception {
StreamExecutionEnvironment execEnv = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(execEnv, streamSettings);
DataStream<Row> ds = execEnv.fromCollection(testData1).returns(testTypeInfo1);
tEnv.createTemporaryView("src", ds);
// register hbase table
String quorum = getZookeeperQuorum();
String ddl;
if (isLegacyConnector) {
ddl = "CREATE TABLE hbase (\n" +
" rowkey INT," +
" family1 ROW<col1 INT>,\n" +
" family2 ROW<col1 VARCHAR, col2 BIGINT>,\n" +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 VARCHAR>,\n" +
" family4 ROW<col1 TIMESTAMP(3), col2 DATE, col3 TIME(3)>\n" +
") WITH (\n" +
" 'connector.type' = 'hbase',\n" +
" 'connector.version' = '1.4.3',\n" +
" 'connector.table-name' = 'testTable3',\n" +
" 'connector.zookeeper.quorum' = '" + quorum + "',\n" +
" 'connector.zookeeper.znode.parent' = '/hbase' " +
")";
} else {
ddl = "CREATE TABLE hbase (\n" +
" rowkey INT," +
" family1 ROW<col1 INT>,\n" +
" family2 ROW<col1 VARCHAR, col2 BIGINT>,\n" +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 VARCHAR>,\n" +
" family4 ROW<col1 TIMESTAMP(3), col2 DATE, col3 TIME(3)>\n" +
") WITH (\n" +
" 'connector' = 'hbase-1.4',\n" +
" 'table-name' = 'testTable3',\n" +
" 'zookeeper.quorum' = '" + quorum + "',\n" +
" 'zookeeper.znode.parent' = '/hbase' " +
")";
}
tEnv.executeSql(ddl);
String query = "INSERT INTO hbase " +
"SELECT rowkey, ROW(f1c1), ROW(f2c1, f2c2), ROW(f3c1, f3c2, f3c3), ROW(f4c1, f4c2, f4c3) " +
"FROM src";
TableEnvUtil.execInsertSqlAndWaitResult(tEnv, query);
// start a batch scan job to verify contents in HBase table
TableEnvironment batchTableEnv = createBatchTableEnv();
batchTableEnv.executeSql(ddl);
Table table = batchTableEnv.sqlQuery(
"SELECT " +
" h.rowkey, " +
" h.family1.col1, " +
" h.family2.col1, " +
" h.family2.col2, " +
" h.family3.col1, " +
" h.family3.col2, " +
" h.family3.col3, " +
" h.family4.col1, " +
" h.family4.col2, " +
" h.family4.col3 " +
"FROM hbase AS h"
);
List<Row> results = collectBatchResult(table);
String expected =
"1,10,Hello-1,100,1.01,false,Welt-1,2019-08-18 19:00:00.0,2019-08-18,19:00:00\n" +
"2,20,Hello-2,200,2.02,true,Welt-2,2019-08-18 19:01:00.0,2019-08-18,19:01:00\n" +
"3,30,Hello-3,300,3.03,false,Welt-3,2019-08-18 19:02:00.0,2019-08-18,19:02:00\n" +
"4,40,null,400,4.04,true,Welt-4,2019-08-18 19:03:00.0,2019-08-18,19:03:00\n" +
"5,50,Hello-5,500,5.05,false,Welt-5,2019-08-19 19:10:00.0,2019-08-19,19:10:00\n" +
"6,60,Hello-6,600,6.06,true,Welt-6,2019-08-19 19:20:00.0,2019-08-19,19:20:00\n" +
"7,70,Hello-7,700,7.07,false,Welt-7,2019-08-19 19:30:00.0,2019-08-19,19:30:00\n" +
"8,80,null,800,8.08,true,Welt-8,2019-08-19 19:40:00.0,2019-08-19,19:40:00\n";
TestBaseUtils.compareResultAsText(results, expected);
}
// -------------------------------------------------------------------------------------
// HBase lookup source tests
// -------------------------------------------------------------------------------------
// prepare a source collection.
private static final List<Row> testData2 = new ArrayList<>();
private static final RowTypeInfo testTypeInfo2 = new RowTypeInfo(
new TypeInformation[]{Types.INT, Types.LONG, Types.STRING},
new String[]{"a", "b", "c"});
static {
testData2.add(Row.of(1, 1L, "Hi"));
testData2.add(Row.of(2, 2L, "Hello"));
testData2.add(Row.of(3, 2L, "Hello world"));
testData2.add(Row.of(3, 3L, "Hello world!"));
}
@Test
public void testHBaseLookupTableSource() throws Exception {
if (OLD_PLANNER.equals(planner)) {
// lookup table source is only supported in blink planner, skip for old planner
return;
}
StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment streamTableEnv = StreamTableEnvironment.create(streamEnv, streamSettings);
StreamITCase.clear();
// prepare a source table
String srcTableName = "src";
DataStream<Row> ds = streamEnv.fromCollection(testData2).returns(testTypeInfo2);
Table in = streamTableEnv.fromDataStream(ds, $("a"), $("b"), $("c"), $("proc").proctime());
streamTableEnv.registerTable(srcTableName, in);
if (isLegacyConnector) {
Map<String, String> tableProperties = hbaseTableProperties();
TableSource<?> source = TableFactoryService
.find(HBaseTableFactory.class, tableProperties)
.createTableSource(tableProperties);
((TableEnvironmentInternal) streamTableEnv).registerTableSourceInternal("hbaseLookup", source);
} else {
streamTableEnv.executeSql(
"CREATE TABLE hbaseLookup (" +
" family1 ROW<col1 INT>," +
" rk INT," +
" family2 ROW<col1 STRING, col2 BIGINT>," +
" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
") WITH (" +
" 'connector' = 'hbase-1.4'," +
" 'table-name' = '" + TEST_TABLE_1 + "'," +
" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
")");
}
// perform a temporal table join query
String query = "SELECT a,family1.col1, family3.col3 FROM src " +
"JOIN hbaseLookup FOR SYSTEM_TIME AS OF src.proc as h ON src.a = h.rk";
Table result = streamTableEnv.sqlQuery(query);
DataStream<Row> resultSet = streamTableEnv.toAppendStream(result, Row.class);
resultSet.addSink(new StreamITCase.StringSink<>());
streamEnv.execute();
List<String> expected = new ArrayList<>();
expected.add("1,10,Welt-1");
expected.add("2,20,Welt-2");
expected.add("3,30,Welt-3");
expected.add("3,30,Welt-3");
StreamITCase.compareWithList(expected);
}
private static Map<String, String> hbaseTableProperties() {
Map<String, String> properties = new HashMap<>();
properties.put(CONNECTOR_TYPE, CONNECTOR_TYPE_VALUE_HBASE);
properties.put(CONNECTOR_VERSION, CONNECTOR_VERSION_VALUE_143);
properties.put(CONNECTOR_PROPERTY_VERSION, "1");
properties.put(CONNECTOR_TABLE_NAME, TEST_TABLE_1);
properties.put(CONNECTOR_ZK_QUORUM, getZookeeperQuorum());
// schema
String[] columnNames = {FAMILY1, ROWKEY, FAMILY2, FAMILY3};
TypeInformation<Row> f1 = Types.ROW_NAMED(new String[]{F1COL1}, Types.INT);
TypeInformation<Row> f2 = Types.ROW_NAMED(new String[]{F2COL1, F2COL2}, Types.STRING, Types.LONG);
TypeInformation<Row> f3 = Types.ROW_NAMED(new String[]{F3COL1, F3COL2, F3COL3}, Types.DOUBLE, Types.BOOLEAN, Types.STRING);
TypeInformation[] columnTypes = new TypeInformation[]{f1, Types.INT, f2, f3};
DescriptorProperties descriptorProperties = new DescriptorProperties(true);
TableSchema tableSchema = new TableSchema(columnNames, columnTypes);
descriptorProperties.putTableSchema(SCHEMA, tableSchema);
descriptorProperties.putProperties(properties);
return descriptorProperties.asMap();
}
// ------------------------------- Utilities -------------------------------------------------
/**
* Creates a Batch {@link TableEnvironment} depends on the {@link #planner} context.
*/
private TableEnvironment createBatchTableEnv() {
if (OLD_PLANNER.equals(planner)) {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
return BatchTableEnvironment.create(env, new TableConfig());
} else {
return TableEnvironment.create(batchSettings);
}
}
/**
* Collects batch result depends on the {@link #planner} context.
*/
private List<Row> collectBatchResult(Table table) throws Exception {
TableImpl tableImpl = (TableImpl) table;
if (OLD_PLANNER.equals(planner)) {
BatchTableEnvironment batchTableEnv = (BatchTableEnvironment) tableImpl.getTableEnvironment();
DataSet<Row> resultSet = batchTableEnv.toDataSet(table, Row.class);
return resultSet.collect();
} else {
TableImpl t = (TableImpl) table;
TableSchema schema = t.getSchema();
List<TypeInformation> types = new ArrayList<>();
for (TypeInformation typeInfo : t.getSchema().getFieldTypes()) {
// convert LOCAL_DATE_TIME to legacy TIMESTAMP to make the output consistent with flink batch planner
if (typeInfo.equals(Types.LOCAL_DATE_TIME)) {
types.add(Types.SQL_TIMESTAMP);
} else if (typeInfo.equals(Types.LOCAL_DATE)) {
types.add(Types.SQL_DATE);
} else if (typeInfo.equals(Types.LOCAL_TIME)) {
types.add(Types.SQL_TIME);
} else {
types.add(typeInfo);
}
}
CollectRowTableSink sink = new CollectRowTableSink();
CollectTableSink<Row> configuredSink = (CollectTableSink<Row>) sink.configure(
schema.getFieldNames(), types.toArray(new TypeInformation[0]));
return JavaScalaConversionUtil.toJava(
BatchTableEnvUtil.collect(
t.getTableEnvironment(), table, configuredSink, Option.apply("JOB")));
}
}
/**
* A {@link ScalarFunction} that maps byte arrays to UTF-8 strings.
*/
public static class ToUTF8 extends ScalarFunction {
private static final long serialVersionUID = 1L;
public String eval(byte[] bytes) {
return Bytes.toString(bytes);
}
}
/**
* A {@link ScalarFunction} that maps byte array to longs.
*/
public static class ToLong extends ScalarFunction {
private static final long serialVersionUID = 1L;
public long eval(byte[] bytes) {
return Bytes.toLong(bytes);
}
}
/**
* A {@link HBaseInputFormat} for testing.
*/
public static class InputFormatForTestTable extends HBaseInputFormat<Tuple1<Integer>> {
private static final long serialVersionUID = 1L;
public InputFormatForTestTable(org.apache.hadoop.conf.Configuration hConf) {
super(hConf);
}
@Override
protected Scan getScanner() {
return new Scan();
}
@Override
protected String getTableName() {
return TEST_TABLE_1;
}
@Override
protected Tuple1<Integer> mapResultToTuple(Result r) {
return new Tuple1<>(Bytes.toInt(r.getValue(Bytes.toBytes(FAMILY1), Bytes.toBytes(F1COL1))));
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.logging.*;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.mapreduce.CounterGroup;
import org.apache.hadoop.util.StringUtils;
/**
* A set of named counters.
*
* <p><code>Counters</code> represent global counters, defined either by the
* Map-Reduce framework or applications. Each <code>Counter</code> can be of
* any {@link Enum} type.</p>
*
* <p><code>Counters</code> are bunched into {@link Group}s, each comprising of
* counters from a particular <code>Enum</code> class.
*/
public class Counters implements Writable, Iterable<Counters.Group> {
private static final Log LOG = LogFactory.getLog(Counters.class);
private static final char GROUP_OPEN = '{';
private static final char GROUP_CLOSE = '}';
private static final char COUNTER_OPEN = '[';
private static final char COUNTER_CLOSE = ']';
private static final char UNIT_OPEN = '(';
private static final char UNIT_CLOSE = ')';
private static char[] charsToEscape = {GROUP_OPEN, GROUP_CLOSE,
COUNTER_OPEN, COUNTER_CLOSE,
UNIT_OPEN, UNIT_CLOSE};
private static final JobConf conf = new JobConf();
/** limit on the size of the name of the group **/
private static final int GROUP_NAME_LIMIT =
conf.getInt("mapreduce.job.counters.group.name.max", 128);
/** limit on the size of the counter name **/
private static final int COUNTER_NAME_LIMIT =
conf.getInt("mapreduce.job.counters.counter.name.max", 64);
/** limit on counters **/
public static int MAX_COUNTER_LIMIT =
conf.getInt("mapreduce.job.counters.limit", // deprecated in 0.23
conf.getInt("mapreduce.job.counters.max", 120));
/** the max groups allowed **/
public static final int MAX_GROUP_LIMIT =
conf.getInt("mapreduce.job.counters.groups.max", 50);
/** the number of current counters**/
private int numCounters = 0;
//private static Log log = LogFactory.getLog("Counters.class");
/**
* A counter record, comprising its name and value.
*/
public static class Counter extends org.apache.hadoop.mapreduce.Counter {
Counter() {
}
Counter(String name, String displayName, long value) {
super(name, displayName);
increment(value);
}
public void setDisplayName(String newName) {
super.setDisplayName(newName);
}
/**
* Returns the compact stringified version of the counter in the format
* [(actual-name)(display-name)(value)]
*/
public synchronized String makeEscapedCompactString() {
// First up, obtain the strings that need escaping. This will help us
// determine the buffer length apriori.
String escapedName = escape(getName());
String escapedDispName = escape(getDisplayName());
long currentValue = this.getValue();
int length = escapedName.length() + escapedDispName.length() + 4;
length += 8; // For the following delimiting characters
StringBuilder builder = new StringBuilder(length);
builder.append(COUNTER_OPEN);
// Add the counter name
builder.append(UNIT_OPEN);
builder.append(escapedName);
builder.append(UNIT_CLOSE);
// Add the display name
builder.append(UNIT_OPEN);
builder.append(escapedDispName);
builder.append(UNIT_CLOSE);
// Add the value
builder.append(UNIT_OPEN);
builder.append(currentValue);
builder.append(UNIT_CLOSE);
builder.append(COUNTER_CLOSE);
return builder.toString();
}
// Checks for (content) equality of two (basic) counters
synchronized boolean contentEquals(Counter c) {
return this.equals(c);
}
/**
* What is the current value of this counter?
* @return the current value
*/
public synchronized long getCounter() {
return getValue();
}
}
/**
* <code>Group</code> of counters, comprising of counters from a particular
* counter {@link Enum} class.
*
* <p><code>Group</code>handles localization of the class name and the
* counter names.</p>
*/
public class Group implements Writable, Iterable<Counter> {
private String groupName;
private String displayName;
private Map<String, Counter> subcounters = new HashMap<String, Counter>();
// Optional ResourceBundle for localization of group and counter names.
private ResourceBundle bundle = null;
Group(String groupName) {
try {
bundle = CounterGroup.getResourceBundle(groupName);
}
catch (MissingResourceException neverMind) {
}
this.groupName = groupName;
this.displayName = localize("CounterGroupName", groupName);
if (LOG.isDebugEnabled()) {
LOG.debug("Creating group " + groupName + " with " +
(bundle == null ? "nothing" : "bundle"));
}
}
/**
* Returns raw name of the group. This is the name of the enum class
* for this group of counters.
*/
public String getName() {
return groupName;
}
/**
* Returns localized name of the group. This is the same as getName() by
* default, but different if an appropriate ResourceBundle is found.
*/
public String getDisplayName() {
return displayName;
}
/**
* Set the display name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* Returns the compact stringified version of the group in the format
* {(actual-name)(display-name)(value)[][][]} where [] are compact strings for the
* counters within.
*/
public String makeEscapedCompactString() {
String[] subcountersArray = new String[subcounters.size()];
// First up, obtain the strings that need escaping. This will help us
// determine the buffer length apriori.
String escapedName = escape(getName());
String escapedDispName = escape(getDisplayName());
int i = 0;
int length = escapedName.length() + escapedDispName.length();
for (Counter counter : subcounters.values()) {
String escapedStr = counter.makeEscapedCompactString();
subcountersArray[i++] = escapedStr;
length += escapedStr.length();
}
length += 6; // for all the delimiting characters below
StringBuilder builder = new StringBuilder(length);
builder.append(GROUP_OPEN); // group start
// Add the group name
builder.append(UNIT_OPEN);
builder.append(escapedName);
builder.append(UNIT_CLOSE);
// Add the display name
builder.append(UNIT_OPEN);
builder.append(escapedDispName);
builder.append(UNIT_CLOSE);
// write the value
for(String str : subcountersArray) {
builder.append(str);
}
builder.append(GROUP_CLOSE); // group end
return builder.toString();
}
@Override
public int hashCode() {
return subcounters.hashCode();
}
/**
* Checks for (content) equality of Groups
*/
@Override
public synchronized boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null && obj instanceof Group) {
Group g = (Group) obj;
if (size() == g.size()) {
isEqual = true;
for (Map.Entry<String, Counter> entry : subcounters.entrySet()) {
String key = entry.getKey();
Counter c1 = entry.getValue();
Counter c2 = g.getCounterForName(key);
if (!c1.contentEquals(c2)) {
isEqual = false;
break;
}
}
}
}
return isEqual;
}
/**
* Returns the value of the specified counter, or 0 if the counter does
* not exist.
*/
public synchronized long getCounter(String counterName) {
for(Counter counter: subcounters.values()) {
if (counter != null && counter.getDisplayName().equals(counterName)) {
return counter.getValue();
}
}
return 0L;
}
/**
* Get the counter for the given id and create it if it doesn't exist.
* @param id the numeric id of the counter within the group
* @param name the internal counter name
* @return the counter
* @deprecated use {@link #getCounter(String)} instead
*/
@Deprecated
public Counter getCounter(int id, String name) {
return getCounterForName(name);
}
/**
* Get the counter for the given name and create it if it doesn't exist.
* @param name the internal counter name
* @return the counter
*/
public Counter getCounterForName(String name) {
synchronized(Counters.this) { // lock ordering: Counters then Group
synchronized (this) {
String shortName = getShortName(name, COUNTER_NAME_LIMIT);
Counter result = subcounters.get(shortName);
if (result == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding " + shortName);
}
numCounters = (numCounters == 0) ? Counters.this.size(): numCounters;
if (numCounters >= MAX_COUNTER_LIMIT) {
throw new CountersExceededException("Error: Exceeded limits on number of counters - "
+ "Counters=" + numCounters + " Limit=" + MAX_COUNTER_LIMIT);
}
result = new Counter(shortName, localize(shortName + ".name", shortName), 0L);
subcounters.put(shortName, result);
numCounters++;
}
return result;
}
}
}
/**
* Returns the number of counters in this group.
*/
public synchronized int size() {
return subcounters.size();
}
/**
* Looks up key in the ResourceBundle and returns the corresponding value.
* If the bundle or the key doesn't exist, returns the default value.
*/
private String localize(String key, String defaultValue) {
String result = defaultValue;
if (bundle != null) {
try {
result = bundle.getString(key);
}
catch (MissingResourceException mre) {
}
}
return result;
}
public synchronized void write(DataOutput out) throws IOException {
Text.writeString(out, displayName);
WritableUtils.writeVInt(out, subcounters.size());
for(Counter counter: subcounters.values()) {
counter.write(out);
}
}
public synchronized void readFields(DataInput in) throws IOException {
displayName = Text.readString(in);
subcounters.clear();
int size = WritableUtils.readVInt(in);
for(int i=0; i < size; i++) {
Counter counter = new Counter();
counter.readFields(in);
subcounters.put(counter.getName(), counter);
}
}
public synchronized Iterator<Counter> iterator() {
return new ArrayList<Counter>(subcounters.values()).iterator();
}
}
// Map from group name (enum class name) to map of int (enum ordinal) to
// counter record (name-value pair).
private Map<String,Group> counters = new HashMap<String, Group>();
/**
* A cache from enum values to the associated counter. Dramatically speeds up
* typical usage.
*/
private Map<Enum, Counter> cache = new IdentityHashMap<Enum, Counter>();
/**
* Returns the names of all counter classes.
* @return Set of counter names.
*/
public synchronized Collection<String> getGroupNames() {
return counters.keySet();
}
public synchronized Iterator<Group> iterator() {
return counters.values().iterator();
}
/**
* Returns the named counter group, or an empty group if there is none
* with the specified name.
*/
public synchronized Group getGroup(String groupName) {
String shortGroupName = getShortName(groupName, GROUP_NAME_LIMIT);
Group result = counters.get(shortGroupName);
if (result == null) {
/** check if we have exceeded the max number on groups **/
if (counters.size() > MAX_GROUP_LIMIT) {
throw new RuntimeException(
"Error: Exceeded limits on number of groups in counters - " +
"Groups=" + counters.size() +" Limit=" + MAX_GROUP_LIMIT);
}
result = new Group(shortGroupName);
counters.put(shortGroupName, result);
}
return result;
}
/**
* Find the counter for the given enum. The same enum will always return the
* same counter.
* @param key the counter key
* @return the matching counter object
*/
public synchronized Counter findCounter(Enum key) {
Counter counter = cache.get(key);
if (counter == null) {
Group group = getGroup(key.getDeclaringClass().getName());
if (group != null) {
counter = group.getCounterForName(key.toString());
if (counter != null) cache.put(key, counter);
}
}
return counter;
}
/**
* Find a counter given the group and the name.
* @param group the name of the group
* @param name the internal name of the counter
* @return the counter for that name
*/
public synchronized Counter findCounter(String group, String name) {
Group retGroup = getGroup(group);
return (retGroup == null) ? null: retGroup.getCounterForName(name);
}
/**
* Find a counter by using strings
* @param group the name of the group
* @param id the id of the counter within the group (0 to N-1)
* @param name the internal name of the counter
* @return the counter for that name
* @deprecated
*/
@Deprecated
public synchronized Counter findCounter(String group, int id, String name) {
Group retGroup = getGroup(group);
return (retGroup == null) ? null: retGroup.getCounterForName(name);
}
/**
* Increments the specified counter by the specified amount, creating it if
* it didn't already exist.
* @param key identifies a counter
* @param amount amount by which counter is to be incremented
*/
public synchronized void incrCounter(Enum key, long amount) {
findCounter(key).increment(amount);
}
/**
* Increments the specified counter by the specified amount, creating it if
* it didn't already exist.
* @param group the name of the group
* @param counter the internal name of the counter
* @param amount amount by which counter is to be incremented
*/
public synchronized void incrCounter(String group, String counter, long amount) {
Group retGroup = getGroup(group);
if (retGroup != null) {
Counter retCounter = retGroup.getCounterForName(counter);
if (retCounter != null ) {
retCounter.increment(amount);
}
}
}
/**
* Returns current value of the specified counter, or 0 if the counter
* does not exist.
*/
public synchronized long getCounter(Enum key) {
Counter retCounter = findCounter(key);
return (retCounter == null) ? 0 : retCounter.getValue();
}
/**
* Increments multiple counters by their amounts in another Counters
* instance.
* @param other the other Counters instance
*/
public synchronized void incrAllCounters(Counters other) {
for (Group otherGroup: other) {
Group group = getGroup(otherGroup.getName());
if (group == null) {
continue;
}
group.displayName = otherGroup.displayName;
for (Counter otherCounter : otherGroup) {
Counter counter = group.getCounterForName(otherCounter.getName());
if (counter == null) {
continue;
}
counter.setDisplayName(otherCounter.getDisplayName());
counter.increment(otherCounter.getValue());
}
}
}
/**
* Convenience method for computing the sum of two sets of counters.
*/
public static Counters sum(Counters a, Counters b) {
Counters counters = new Counters();
counters.incrAllCounters(a);
counters.incrAllCounters(b);
return counters;
}
/**
* Returns the total number of counters, by summing the number of counters
* in each group.
*/
public synchronized int size() {
int result = 0;
for (Group group : this) {
result += group.size();
}
return result;
}
/**
* Write the set of groups.
* The external format is:
* #groups (groupName group)*
*
* i.e. the number of groups followed by 0 or more groups, where each
* group is of the form:
*
* groupDisplayName #counters (false | true counter)*
*
* where each counter is of the form:
*
* name (false | true displayName) value
*/
public synchronized void write(DataOutput out) throws IOException {
out.writeInt(counters.size());
for (Group group: counters.values()) {
Text.writeString(out, group.getName());
group.write(out);
}
}
/**
* Read a set of groups.
*/
public synchronized void readFields(DataInput in) throws IOException {
int numClasses = in.readInt();
counters.clear();
while (numClasses-- > 0) {
String groupName = Text.readString(in);
Group group = new Group(groupName);
group.readFields(in);
counters.put(groupName, group);
}
}
/**
* Logs the current counter values.
* @param log The log to use.
*/
public void log(Log log) {
log.info("Counters: " + size());
for(Group group: this) {
log.info(" " + group.getDisplayName());
for (Counter counter: group) {
log.info(" " + counter.getDisplayName() + "=" +
counter.getCounter());
}
}
}
/**
* Return textual representation of the counter values.
*/
public synchronized String toString() {
StringBuilder sb = new StringBuilder("Counters: " + size());
for (Group group: this) {
sb.append("\n\t" + group.getDisplayName());
for (Counter counter: group) {
sb.append("\n\t\t" + counter.getDisplayName() + "=" +
counter.getCounter());
}
}
return sb.toString();
}
/**
* Convert a counters object into a single line that is easy to parse.
* @return the string with "name=value" for each counter and separated by ","
*/
public synchronized String makeCompactString() {
StringBuffer buffer = new StringBuffer();
boolean first = true;
for(Group group: this){
for(Counter counter: group) {
if (first) {
first = false;
} else {
buffer.append(',');
}
buffer.append(group.getDisplayName());
buffer.append('.');
buffer.append(counter.getDisplayName());
buffer.append(':');
buffer.append(counter.getCounter());
}
}
return buffer.toString();
}
/**
* Represent the counter in a textual format that can be converted back to
* its object form
* @return the string in the following format
* {(groupname)(group-displayname)[(countername)(displayname)(value)][][]}{}{}
*/
public synchronized String makeEscapedCompactString() {
String[] groupsArray = new String[counters.size()];
int i = 0;
int length = 0;
// First up, obtain the escaped string for each group so that we can
// determine the buffer length apriori.
for (Group group : this) {
String escapedString = group.makeEscapedCompactString();
groupsArray[i++] = escapedString;
length += escapedString.length();
}
// Now construct the buffer
StringBuilder builder = new StringBuilder(length);
for (String group : groupsArray) {
builder.append(group);
}
return builder.toString();
}
/**
* return the short name of a counter/group name
* truncates from beginning.
* @param name the name of a group or counter
* @param limit the limit of characters
* @return the short name
*/
static String getShortName(String name, int limit) {
return (name.length() > limit ?
name.substring(name.length() - limit, name.length()): name);
}
// Extracts a block (data enclosed within delimeters) ignoring escape
// sequences. Throws ParseException if an incomplete block is found else
// returns null.
private static String getBlock(String str, char open, char close,
IntWritable index) throws ParseException {
StringBuilder split = new StringBuilder();
int next = StringUtils.findNext(str, open, StringUtils.ESCAPE_CHAR,
index.get(), split);
split.setLength(0); // clear the buffer
if (next >= 0) {
++next; // move over '('
next = StringUtils.findNext(str, close, StringUtils.ESCAPE_CHAR,
next, split);
if (next >= 0) {
++next; // move over ')'
index.set(next);
return split.toString(); // found a block
} else {
throw new ParseException("Unexpected end of block", next);
}
}
return null; // found nothing
}
/**
* Convert a stringified counter representation into a counter object. Note
* that the counter can be recovered if its stringified using
* {@link #makeEscapedCompactString()}.
* @return a Counter
*/
public static Counters fromEscapedCompactString(String compactString)
throws ParseException {
Counters counters = new Counters();
IntWritable index = new IntWritable(0);
// Get the group to work on
String groupString =
getBlock(compactString, GROUP_OPEN, GROUP_CLOSE, index);
while (groupString != null) {
IntWritable groupIndex = new IntWritable(0);
// Get the actual name
String groupName =
getBlock(groupString, UNIT_OPEN, UNIT_CLOSE, groupIndex);
groupName = unescape(groupName);
// Get the display name
String groupDisplayName =
getBlock(groupString, UNIT_OPEN, UNIT_CLOSE, groupIndex);
groupDisplayName = unescape(groupDisplayName);
// Get the counters
Group group = counters.getGroup(groupName);
group.setDisplayName(groupDisplayName);
String counterString =
getBlock(groupString, COUNTER_OPEN, COUNTER_CLOSE, groupIndex);
while (counterString != null) {
IntWritable counterIndex = new IntWritable(0);
// Get the actual name
String counterName =
getBlock(counterString, UNIT_OPEN, UNIT_CLOSE, counterIndex);
counterName = unescape(counterName);
// Get the display name
String counterDisplayName =
getBlock(counterString, UNIT_OPEN, UNIT_CLOSE, counterIndex);
counterDisplayName = unescape(counterDisplayName);
// Get the value
long value =
Long.parseLong(getBlock(counterString, UNIT_OPEN, UNIT_CLOSE,
counterIndex));
// Add the counter
Counter counter = group.getCounterForName(counterName);
counter.setDisplayName(counterDisplayName);
counter.increment(value);
// Get the next counter
counterString =
getBlock(groupString, COUNTER_OPEN, COUNTER_CLOSE, groupIndex);
}
groupString = getBlock(compactString, GROUP_OPEN, GROUP_CLOSE, index);
}
return counters;
}
// Escapes all the delimiters for counters i.e {,[,(,),],}
private static String escape(String string) {
return StringUtils.escapeString(string, StringUtils.ESCAPE_CHAR,
charsToEscape);
}
// Unescapes all the delimiters for counters i.e {,[,(,),],}
private static String unescape(String string) {
return StringUtils.unEscapeString(string, StringUtils.ESCAPE_CHAR,
charsToEscape);
}
@Override
public synchronized int hashCode() {
return counters.hashCode();
}
@Override
public synchronized boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null && obj instanceof Counters) {
Counters other = (Counters) obj;
if (size() == other.size()) {
isEqual = true;
for (Map.Entry<String, Group> entry : this.counters.entrySet()) {
String key = entry.getKey();
Group sourceGroup = entry.getValue();
Group targetGroup = other.getGroup(key);
if (!sourceGroup.equals(targetGroup)) {
isEqual = false;
break;
}
}
}
}
return isEqual;
}
/**
* Counter exception thrown when the number of counters exceed
* the limit
*/
public static class CountersExceededException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CountersExceededException(String msg) {
super(msg);
}
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2013-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this content except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.directorytree;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.openide.util.Cancellable;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.coreutils.FileUtil;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.autopsy.datamodel.ContentUtils.ExtractFscContentVisitor;
import org.sleuthkit.datamodel.AbstractFile;
/**
* Extracts AbstractFiles to a location selected by the user.
*/
public final class ExtractAction extends AbstractAction {
private Logger logger = Logger.getLogger(ExtractAction.class.getName());
private String userDefinedExportPath;
// This class is a singleton to support multi-selection of nodes, since
// org.openide.nodes.NodeOp.findActions(Node[] nodes) will only pick up an Action if every
// node in the array returns a reference to the same action object from Node.getActions(boolean).
private static ExtractAction instance;
public static synchronized ExtractAction getInstance() {
if (null == instance) {
instance = new ExtractAction();
}
return instance;
}
/**
* Private constructor for the action.
*/
private ExtractAction() {
super(NbBundle.getMessage(ExtractAction.class, "ExtractAction.title.extractFiles.text"));
}
/**
* Asks user to choose destination, then extracts content to destination
* (recursing on directories).
*
* @param e The action event.
*/
@Override
public void actionPerformed(ActionEvent e) {
Collection<? extends AbstractFile> selectedFiles = Utilities.actionsGlobalContext().lookupAll(AbstractFile.class);
if (selectedFiles.size() > 1) {
extractFiles(e, selectedFiles);
} else if (selectedFiles.size() == 1) {
AbstractFile source = selectedFiles.iterator().next();
if (source.isDir()) {
extractFiles(e, selectedFiles);
} else {
extractFile(e, selectedFiles.iterator().next());
}
}
}
/**
* Called when user has selected a single file to extract
*
* @param event
* @param selectedFile Selected file
*/
@NbBundle.Messages({"ExtractAction.noOpenCase.errMsg=No open case available."})
private void extractFile(ActionEvent event, AbstractFile selectedFile) {
Case openCase;
try {
openCase = Case.getCurrentCaseThrows();
} catch (NoCurrentCaseException ex) {
JOptionPane.showMessageDialog((Component) event.getSource(), Bundle.ExtractAction_noOpenCase_errMsg());
logger.log(Level.INFO, "Exception while getting open case.", ex); //NON-NLS
return;
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(getExportDirectory(openCase)));
// If there is an attribute name, change the ":". Otherwise the extracted file will be hidden
fileChooser.setSelectedFile(new File(FileUtil.escapeFileName(selectedFile.getName())));
if (fileChooser.showSaveDialog((Component) event.getSource()) == JFileChooser.APPROVE_OPTION) {
updateExportDirectory(fileChooser.getSelectedFile().getParent(), openCase);
ArrayList<FileExtractionTask> fileExtractionTasks = new ArrayList<>();
fileExtractionTasks.add(new FileExtractionTask(selectedFile, fileChooser.getSelectedFile()));
runExtractionTasks(event, fileExtractionTasks);
}
}
/**
* Called when a user has selected multiple files to extract
*
* @param event
* @param selectedFiles Selected files
*/
private void extractFiles(ActionEvent event, Collection<? extends AbstractFile> selectedFiles) {
Case openCase;
try {
openCase = Case.getCurrentCaseThrows();
} catch (NoCurrentCaseException ex) {
JOptionPane.showMessageDialog((Component) event.getSource(), Bundle.ExtractAction_noOpenCase_errMsg());
logger.log(Level.INFO, "Exception while getting open case.", ex); //NON-NLS
return;
}
JFileChooser folderChooser = new JFileChooser();
folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
folderChooser.setCurrentDirectory(new File(getExportDirectory(openCase)));
if (folderChooser.showSaveDialog((Component) event.getSource()) == JFileChooser.APPROVE_OPTION) {
File destinationFolder = folderChooser.getSelectedFile();
if (!destinationFolder.exists()) {
try {
destinationFolder.mkdirs();
} catch (Exception ex) {
JOptionPane.showMessageDialog((Component) event.getSource(), NbBundle.getMessage(this.getClass(),
"ExtractAction.extractFiles.cantCreateFolderErr.msg"));
logger.log(Level.INFO, "Unable to create folder(s) for user " + destinationFolder.getAbsolutePath(), ex); //NON-NLS
return;
}
}
updateExportDirectory(destinationFolder.getPath(), openCase);
/*
* get the unique set of files from the list. A user once reported
* extraction taking days because it was extracting the same PST
* file 20k times. They selected 20k email messages in the tree and
* chose to extract them.
*/
Set<AbstractFile> uniqueFiles = new HashSet<>(selectedFiles);
// make a task for each file
ArrayList<FileExtractionTask> fileExtractionTasks = new ArrayList<>();
for (AbstractFile source : uniqueFiles) {
// If there is an attribute name, change the ":". Otherwise the extracted file will be hidden
fileExtractionTasks.add(new FileExtractionTask(source, new File(destinationFolder, source.getId() + "-" + FileUtil.escapeFileName(source.getName()))));
}
runExtractionTasks(event, fileExtractionTasks);
}
}
/**
* Get the export directory path.
*
* @param openCase The current case.
*
* @return The export directory path.
*/
private String getExportDirectory(Case openCase) {
String caseExportPath = openCase.getExportDirectory();
if (userDefinedExportPath == null) {
return caseExportPath;
}
File file = new File(userDefinedExportPath);
if (file.exists() == false || file.isDirectory() == false) {
return caseExportPath;
}
return userDefinedExportPath;
}
/**
* Update the default export directory. If the directory path matches the
* case export directory, then the directory used will always match the
* export directory of any given case. Otherwise, the path last used will be
* saved.
*
* @param exportPath The export path.
* @param openCase The current case.
*/
private void updateExportDirectory(String exportPath, Case openCase) {
if (exportPath.equalsIgnoreCase(openCase.getExportDirectory())) {
userDefinedExportPath = null;
} else {
userDefinedExportPath = exportPath;
}
}
/**
* Execute a series of file extraction tasks.
*
* @param event ActionEvent whose source will be used for
* centering popup dialogs.
* @param fileExtractionTasks List of file extraction tasks.
*/
private void runExtractionTasks(ActionEvent event, List<FileExtractionTask> fileExtractionTasks) {
// verify all of the sources and destinations are OK
for (Iterator<FileExtractionTask> it = fileExtractionTasks.iterator(); it.hasNext();) {
FileExtractionTask task = it.next();
if (ContentUtils.isDotDirectory(task.source)) {
//JOptionPane.showMessageDialog((Component) e.getSource(), "Cannot extract virtual " + task.source.getName() + " directory.", "File is Virtual Directory", JOptionPane.WARNING_MESSAGE);
it.remove();
continue;
}
/*
* This code assumes that each destination is unique. We previously
* satisfied that by adding the unique ID.
*/
if (task.destination.exists()) {
if (JOptionPane.showConfirmDialog((Component) event.getSource(),
NbBundle.getMessage(this.getClass(), "ExtractAction.confDlg.destFileExist.msg", task.destination.getAbsolutePath()),
NbBundle.getMessage(this.getClass(), "ExtractAction.confDlg.destFileExist.title"),
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (!FileUtil.deleteFileDir(task.destination)) {
JOptionPane.showMessageDialog((Component) event.getSource(),
NbBundle.getMessage(this.getClass(), "ExtractAction.msgDlg.cantOverwriteFile.msg", task.destination.getAbsolutePath()));
it.remove();
}
} else {
it.remove();
}
}
}
// launch a thread to do the work
if (!fileExtractionTasks.isEmpty()) {
try {
FileExtracter extracter = new FileExtracter(fileExtractionTasks);
extracter.execute();
} catch (Exception ex) {
logger.log(Level.WARNING, "Unable to start background file extraction thread", ex); //NON-NLS
}
} else {
MessageNotifyUtil.Message.info(
NbBundle.getMessage(this.getClass(), "ExtractAction.notifyDlg.noFileToExtr.msg"));
}
}
/**
* Stores source and destination for file extraction.
*/
private class FileExtractionTask {
AbstractFile source;
File destination;
/**
* Create an instance of the FileExtractionTask.
*
* @param source The file to be extracted.
* @param destination The destination for the extraction.
*/
FileExtractionTask(AbstractFile source, File destination) {
this.source = source;
this.destination = destination;
}
}
/**
* Thread that does the actual extraction work
*/
private class FileExtracter extends SwingWorker<Object, Void> {
private final Logger logger = Logger.getLogger(FileExtracter.class.getName());
private ProgressHandle progress;
private final List<FileExtractionTask> extractionTasks;
/**
* Create an instance of the FileExtracter.
*
* @param extractionTasks List of file extraction tasks.
*/
FileExtracter(List<FileExtractionTask> extractionTasks) {
this.extractionTasks = extractionTasks;
}
@Override
protected Object doInBackground() throws Exception {
if (extractionTasks.isEmpty()) {
return null;
}
// Setup progress bar.
final String displayName = NbBundle.getMessage(this.getClass(), "ExtractAction.progress.extracting");
progress = ProgressHandle.createHandle(displayName, new Cancellable() {
@Override
public boolean cancel() {
if (progress != null) {
progress.setDisplayName(
NbBundle.getMessage(this.getClass(), "ExtractAction.progress.cancellingExtraction", displayName));
}
return ExtractAction.FileExtracter.this.cancel(true);
}
});
progress.start();
progress.switchToIndeterminate();
/*
* @@@ Add back in -> Causes exceptions int workUnits = 0; for
* (FileExtractionTask task : extractionTasks) { workUnits +=
* calculateProgressBarWorkUnits(task.source); }
* progress.switchToDeterminate(workUnits);
*/
// Do the extraction tasks.
for (FileExtractionTask task : this.extractionTasks) {
// @@@ Note, we are no longer passing in progress
ExtractFscContentVisitor.extract(task.source, task.destination, null, this);
}
return null;
}
@Override
protected void done() {
boolean msgDisplayed = false;
try {
super.get();
} catch (InterruptedException | ExecutionException ex) {
logger.log(Level.SEVERE, "Fatal error during file extraction", ex); //NON-NLS
MessageNotifyUtil.Message.info(
NbBundle.getMessage(this.getClass(), "ExtractAction.done.notifyMsg.extractErr", ex.getMessage()));
msgDisplayed = true;
} finally {
progress.finish();
if (!this.isCancelled() && !msgDisplayed) {
MessageNotifyUtil.Message.info(
NbBundle.getMessage(this.getClass(), "ExtractAction.done.notifyMsg.fileExtr.text"));
}
}
}
/**
* Calculate the number of work units for the progress bar.
*
* @param file File whose children will be reviewed to get the number of
* work units.
*
* @return The number of work units.
*/
/*
* private int calculateProgressBarWorkUnits(AbstractFile file) { int
* workUnits = 0; if (file.isFile()) { workUnits += file.getSize(); }
* else { try { for (Content child : file.getChildren()) { if (child
* instanceof AbstractFile) { workUnits +=
* calculateProgressBarWorkUnits((AbstractFile) child); } } } catch
* (TskCoreException ex) { logger.log(Level.SEVERE, "Could not get
* children of content", ex); //NON-NLS } } return workUnits;
}
*/
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.service.component.instance;
import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.registry.client.api.RegistryConstants;
import org.apache.hadoop.registry.client.binding.RegistryPathUtils;
import org.apache.hadoop.registry.client.binding.RegistryUtils;
import org.apache.hadoop.registry.client.types.ServiceRecord;
import org.apache.hadoop.registry.client.types.yarn.PersistencePolicies;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.client.api.NMClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.service.ServiceScheduler;
import org.apache.hadoop.yarn.service.api.records.Artifact;
import org.apache.hadoop.yarn.service.api.records.ContainerState;
import org.apache.hadoop.yarn.service.component.Component;
import org.apache.hadoop.yarn.service.component.ComponentEvent;
import org.apache.hadoop.yarn.service.component.ComponentEventType;
import org.apache.hadoop.yarn.service.component.ComponentRestartPolicy;
import org.apache.hadoop.yarn.service.monitor.probe.ProbeStatus;
import org.apache.hadoop.yarn.service.registry.YarnRegistryViewForProviders;
import org.apache.hadoop.yarn.service.timelineservice.ServiceTimelinePublisher;
import org.apache.hadoop.yarn.service.utils.ServiceUtils;
import org.apache.hadoop.yarn.state.InvalidStateTransitionException;
import org.apache.hadoop.yarn.state.SingleArcTransition;
import org.apache.hadoop.yarn.state.StateMachine;
import org.apache.hadoop.yarn.state.StateMachineFactory;
import org.apache.hadoop.yarn.util.BoundedAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import static org.apache.hadoop.registry.client.types.yarn.YarnRegistryAttributes.*;
import static org.apache.hadoop.yarn.api.records.ContainerExitStatus.KILLED_BY_APPMASTER;
import static org.apache.hadoop.yarn.service.component.instance.ComponentInstanceEventType.*;
import static org.apache.hadoop.yarn.service.component.instance.ComponentInstanceState.*;
public class ComponentInstance implements EventHandler<ComponentInstanceEvent>,
Comparable<ComponentInstance> {
private static final Logger LOG =
LoggerFactory.getLogger(ComponentInstance.class);
private static final String FAILED_BEFORE_LAUNCH_DIAG =
"failed before launch";
private StateMachine<ComponentInstanceState, ComponentInstanceEventType,
ComponentInstanceEvent> stateMachine;
private Component component;
private final ReadLock readLock;
private final WriteLock writeLock;
private ComponentInstanceId compInstanceId = null;
private Path compInstanceDir;
private Container container;
private YarnRegistryViewForProviders yarnRegistryOperations;
private FileSystem fs;
private boolean timelineServiceEnabled = false;
private ServiceTimelinePublisher serviceTimelinePublisher;
private ServiceScheduler scheduler;
private BoundedAppender diagnostics = new BoundedAppender(64 * 1024);
private volatile ScheduledFuture containerStatusFuture;
private volatile ContainerStatus status;
private long containerStartedTime = 0;
// This container object is used for rest API query
private org.apache.hadoop.yarn.service.api.records.Container containerSpec;
private String serviceVersion;
private static final StateMachineFactory<ComponentInstance,
ComponentInstanceState, ComponentInstanceEventType,
ComponentInstanceEvent>
stateMachineFactory =
new StateMachineFactory<ComponentInstance, ComponentInstanceState,
ComponentInstanceEventType, ComponentInstanceEvent>(INIT)
.addTransition(INIT, STARTED, START,
new ContainerStartedTransition())
.addTransition(INIT, INIT, STOP,
// container failed before launching, nothing to cleanup from registry
// This could happen if NMClient#startContainerAsync failed, container
// will be completed, but COMP_INSTANCE is still at INIT.
new ContainerStoppedTransition(true))
//From Running
.addTransition(STARTED, INIT, STOP,
new ContainerStoppedTransition())
.addTransition(STARTED, READY, BECOME_READY,
new ContainerBecomeReadyTransition())
// FROM READY
.addTransition(READY, STARTED, BECOME_NOT_READY,
new ContainerBecomeNotReadyTransition())
.addTransition(READY, INIT, STOP, new ContainerStoppedTransition())
.addTransition(READY, UPGRADING, UPGRADE,
new ContainerUpgradeTransition())
.addTransition(UPGRADING, UPGRADING, UPGRADE,
new ContainerUpgradeTransition())
.addTransition(UPGRADING, READY, BECOME_READY,
new ContainerBecomeReadyTransition())
.addTransition(UPGRADING, INIT, STOP, new ContainerStoppedTransition())
.installTopology();
public ComponentInstance(Component component,
ComponentInstanceId compInstanceId) {
this.stateMachine = stateMachineFactory.make(this);
this.component = component;
this.compInstanceId = compInstanceId;
this.scheduler = component.getScheduler();
this.yarnRegistryOperations =
component.getScheduler().getYarnRegistryOperations();
this.serviceTimelinePublisher =
component.getScheduler().getServiceTimelinePublisher();
if (YarnConfiguration
.timelineServiceV2Enabled(component.getScheduler().getConfig())) {
this.timelineServiceEnabled = true;
}
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
this.readLock = lock.readLock();
this.writeLock = lock.writeLock();
this.fs = scheduler.getContext().fs.getFileSystem();
}
private static class ContainerStartedTransition extends BaseTransition {
@Override public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
// Query container status for ip and host
boolean cancelOnSuccess = true;
if (compInstance.getCompSpec().getArtifact() != null && compInstance
.getCompSpec().getArtifact().getType() == Artifact.TypeEnum.DOCKER) {
// A docker container might get a different IP if the container is
// relaunched by the NM, so we need to keep checking the status.
// This is a temporary fix until the NM provides a callback for
// container relaunch (see YARN-8265).
cancelOnSuccess = false;
}
compInstance.containerStatusFuture =
compInstance.scheduler.executorService.scheduleAtFixedRate(
new ContainerStatusRetriever(compInstance.scheduler,
event.getContainerId(), compInstance, cancelOnSuccess), 0, 1,
TimeUnit.SECONDS);
long containerStartTime = System.currentTimeMillis();
try {
ContainerTokenIdentifier containerTokenIdentifier = BuilderUtils
.newContainerTokenIdentifier(compInstance.getContainer()
.getContainerToken());
containerStartTime = containerTokenIdentifier.getCreationTime();
} catch (Exception e) {
LOG.info("Could not get container creation time, using current time");
}
org.apache.hadoop.yarn.service.api.records.Container container =
new org.apache.hadoop.yarn.service.api.records.Container();
container.setId(event.getContainerId().toString());
container.setLaunchTime(new Date(containerStartTime));
container.setState(ContainerState.RUNNING_BUT_UNREADY);
container.setBareHost(compInstance.getNodeId().getHost());
container.setComponentInstanceName(compInstance.getCompInstanceName());
if (compInstance.containerSpec != null) {
// remove the previous container.
compInstance.getCompSpec().removeContainer(compInstance.containerSpec);
}
compInstance.containerSpec = container;
compInstance.getCompSpec().addContainer(container);
compInstance.containerStartedTime = containerStartTime;
compInstance.component.incRunningContainers();
compInstance.serviceVersion = compInstance.scheduler.getApp()
.getVersion();
if (compInstance.timelineServiceEnabled) {
compInstance.serviceTimelinePublisher
.componentInstanceStarted(container, compInstance);
}
}
}
private static class ContainerBecomeReadyTransition extends BaseTransition {
@Override
public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
compInstance.containerSpec.setState(ContainerState.READY);
if (compInstance.getState().equals(ComponentInstanceState.UPGRADING)) {
compInstance.component.incContainersReady(false);
compInstance.component.decContainersThatNeedUpgrade();
compInstance.serviceVersion = compInstance.component.getUpgradeEvent()
.getUpgradeVersion();
ComponentEvent checkState = new ComponentEvent(
compInstance.component.getName(), ComponentEventType.CHECK_STABLE);
compInstance.scheduler.getDispatcher().getEventHandler().handle(
checkState);
} else {
compInstance.component.incContainersReady(true);
}
if (compInstance.timelineServiceEnabled) {
compInstance.serviceTimelinePublisher
.componentInstanceBecomeReady(compInstance.containerSpec);
}
}
}
private static class ContainerBecomeNotReadyTransition extends BaseTransition {
@Override
public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
compInstance.containerSpec.setState(ContainerState.RUNNING_BUT_UNREADY);
compInstance.component.decContainersReady(true);
}
}
@VisibleForTesting
static void handleComponentInstanceRelaunch(
ComponentInstance compInstance, ComponentInstanceEvent event,
boolean failureBeforeLaunch) {
Component comp = compInstance.getComponent();
// Do we need to relaunch the service?
boolean hasContainerFailed = hasContainerFailed(event.getStatus());
ComponentRestartPolicy restartPolicy = comp.getRestartPolicyHandler();
if (restartPolicy.shouldRelaunchInstance(compInstance, event.getStatus())) {
// re-ask the failed container.
comp.requestContainers(1);
comp.reInsertPendingInstance(compInstance);
StringBuilder builder = new StringBuilder();
builder.append(compInstance.getCompInstanceId()).append(": ");
builder.append(event.getContainerId()).append(" completed. Reinsert back to pending list and requested ");
builder.append("a new container.").append(System.lineSeparator());
builder.append(" exitStatus=").append(failureBeforeLaunch ? null : event.getStatus().getExitStatus());
builder.append(", diagnostics=");
builder.append(failureBeforeLaunch ? FAILED_BEFORE_LAUNCH_DIAG : event.getStatus().getDiagnostics());
if (event.getStatus().getExitStatus() != 0) {
LOG.error(builder.toString());
} else {
LOG.info(builder.toString());
}
} else {
// When no relaunch, update component's #succeeded/#failed
// instances.
if (hasContainerFailed) {
comp.markAsFailed(compInstance);
} else {
comp.markAsSucceeded(compInstance);
}
LOG.info(compInstance.getCompInstanceId() + (!hasContainerFailed ?
" succeeded" :
" failed") + " without retry, exitStatus=" + event.getStatus());
comp.getScheduler().terminateServiceIfAllComponentsFinished();
}
}
public static boolean hasContainerFailed(ContainerStatus containerStatus) {
//Mark conainer as failed if we cant get its exit status i.e null?
return containerStatus == null || containerStatus.getExitStatus() !=
ContainerExitStatus.SUCCESS;
}
private static class ContainerStoppedTransition extends BaseTransition {
// whether the container failed before launched by AM or not.
boolean failedBeforeLaunching = false;
public ContainerStoppedTransition(boolean failedBeforeLaunching) {
this.failedBeforeLaunching = failedBeforeLaunching;
}
public ContainerStoppedTransition() {
this(false);
}
@Override
public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
Component comp = compInstance.component;
String containerDiag =
compInstance.getCompInstanceId() + ": " + (failedBeforeLaunching ?
FAILED_BEFORE_LAUNCH_DIAG : event.getStatus().getDiagnostics());
compInstance.diagnostics.append(containerDiag + System.lineSeparator());
compInstance.cancelContainerStatusRetriever();
if (compInstance.getState().equals(ComponentInstanceState.UPGRADING)) {
compInstance.component.decContainersThatNeedUpgrade();
}
if (compInstance.getState().equals(READY)) {
compInstance.component.decContainersReady(true);
}
compInstance.component.decRunningContainers();
// Should we fail (terminate) the service?
boolean shouldFailService = false;
final ServiceScheduler scheduler = comp.getScheduler();
scheduler.getAmRMClient().releaseAssignedContainer(
event.getContainerId());
// Check if it exceeds the failure threshold, but only if health threshold
// monitor is not enabled
if (!comp.isHealthThresholdMonitorEnabled()
&& comp.currentContainerFailure
.get() > comp.maxContainerFailurePerComp) {
String exitDiag = MessageFormat.format(
"[COMPONENT {0}]: Failed {1} times, exceeded the limit - {2}. Shutting down now... "
+ System.lineSeparator(),
comp.getName(), comp.currentContainerFailure.get(), comp.maxContainerFailurePerComp);
compInstance.diagnostics.append(exitDiag);
// append to global diagnostics that will be reported to RM.
scheduler.getDiagnostics().append(containerDiag);
scheduler.getDiagnostics().append(exitDiag);
LOG.warn(exitDiag);
shouldFailService = true;
}
if (!failedBeforeLaunching) {
// clean up registry
// If the container failed before launching, no need to cleanup registry,
// because it was not registered before.
// hdfs dir content will be overwritten when a new container gets started,
// so no need remove.
compInstance.scheduler.executorService
.submit(() -> compInstance.cleanupRegistry(event.getContainerId()));
if (compInstance.timelineServiceEnabled) {
// record in ATS
compInstance.serviceTimelinePublisher
.componentInstanceFinished(event.getContainerId(),
event.getStatus().getExitStatus(), containerDiag);
}
compInstance.containerSpec.setState(ContainerState.STOPPED);
}
// remove the failed ContainerId -> CompInstance mapping
scheduler.removeLiveCompInstance(event.getContainerId());
// According to component restart policy, handle container restart
// or finish the service (if all components finished)
handleComponentInstanceRelaunch(compInstance, event,
failedBeforeLaunching);
if (shouldFailService) {
scheduler.getTerminationHandler().terminate(-1);
}
}
}
private static class ContainerUpgradeTransition extends BaseTransition {
@Override
public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
compInstance.containerSpec.setState(ContainerState.UPGRADING);
compInstance.component.decContainersReady(false);
ComponentEvent upgradeEvent = compInstance.component.getUpgradeEvent();
compInstance.scheduler.getContainerLaunchService()
.reInitCompInstance(compInstance.scheduler.getApp(), compInstance,
compInstance.container,
compInstance.component.createLaunchContext(
upgradeEvent.getTargetSpec(),
upgradeEvent.getUpgradeVersion()));
}
}
public ComponentInstanceState getState() {
this.readLock.lock();
try {
return this.stateMachine.getCurrentState();
} finally {
this.readLock.unlock();
}
}
/**
* Returns the version of service at which the instance is at.
*/
public String getServiceVersion() {
this.readLock.lock();
try {
return this.serviceVersion;
} finally {
this.readLock.unlock();
}
}
/**
* Returns the state of the container in the container spec.
*/
public ContainerState getContainerState() {
this.readLock.lock();
try {
return this.containerSpec.getState();
} finally {
this.readLock.unlock();
}
}
@Override
public void handle(ComponentInstanceEvent event) {
try {
writeLock.lock();
ComponentInstanceState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (InvalidStateTransitionException e) {
LOG.error(getCompInstanceId() + ": Invalid event " + event.getType() +
" at " + oldState, e);
}
if (oldState != getState()) {
LOG.info(getCompInstanceId() + " Transitioned from " + oldState + " to "
+ getState() + " on " + event.getType() + " event");
}
} finally {
writeLock.unlock();
}
}
public void setContainer(Container container) {
this.container = container;
this.compInstanceId.setContainerId(container.getId());
}
public String getCompInstanceName() {
return compInstanceId.getCompInstanceName();
}
public ContainerStatus getContainerStatus() {
return status;
}
public void updateContainerStatus(ContainerStatus status) {
this.status = status;
org.apache.hadoop.yarn.service.api.records.Container container =
getCompSpec().getContainer(status.getContainerId().toString());
boolean doRegistryUpdate = true;
if (container != null) {
String existingIP = container.getIp();
String newIP = StringUtils.join(",", status.getIPs());
container.setIp(newIP);
container.setHostname(status.getHost());
if (existingIP != null && newIP.equals(existingIP)) {
doRegistryUpdate = false;
}
if (timelineServiceEnabled && doRegistryUpdate) {
serviceTimelinePublisher.componentInstanceIPHostUpdated(container);
}
}
if (doRegistryUpdate) {
cleanupRegistry(status.getContainerId());
LOG.info(
getCompInstanceId() + " new IP = " + status.getIPs() + ", host = "
+ status.getHost() + ", updating registry");
updateServiceRecord(yarnRegistryOperations, status);
}
}
public String getCompName() {
return compInstanceId.getCompName();
}
public void setCompInstanceDir(Path dir) {
this.compInstanceDir = dir;
}
public Component getComponent() {
return component;
}
public Container getContainer() {
return container;
}
public ComponentInstanceId getCompInstanceId() {
return compInstanceId;
}
public NodeId getNodeId() {
return this.container.getNodeId();
}
private org.apache.hadoop.yarn.service.api.records.Component getCompSpec() {
return component.getComponentSpec();
}
private static class BaseTransition implements
SingleArcTransition<ComponentInstance, ComponentInstanceEvent> {
@Override public void transition(ComponentInstance compInstance,
ComponentInstanceEvent event) {
}
}
public ProbeStatus ping() {
if (component.getProbe() == null) {
ProbeStatus status = new ProbeStatus();
status.setSuccess(true);
return status;
}
return component.getProbe().ping(this);
}
// Write service record into registry
private void updateServiceRecord(
YarnRegistryViewForProviders yarnRegistry, ContainerStatus status) {
ServiceRecord record = new ServiceRecord();
String containerId = status.getContainerId().toString();
record.set(YARN_ID, containerId);
record.description = getCompInstanceName();
record.set(YARN_PERSISTENCE, PersistencePolicies.CONTAINER);
record.set(YARN_IP, status.getIPs().get(0));
record.set(YARN_HOSTNAME, status.getHost());
record.set(YARN_COMPONENT, component.getName());
try {
yarnRegistry
.putComponent(RegistryPathUtils.encodeYarnID(containerId), record);
} catch (IOException e) {
LOG.error(
"Failed to update service record in registry: " + containerId + "");
}
}
// Called when user flexed down the container and ContainerStoppedTransition
// is not executed in this case.
// Release the container, dec running,
// cleanup registry, hdfs dir, and send record to ATS
public void destroy() {
LOG.info(getCompInstanceId() + ": Flexed down by user, destroying.");
diagnostics.append(getCompInstanceId() + ": Flexed down by user");
// update metrics
if (getState() == STARTED) {
component.decRunningContainers();
}
if (getState() == READY) {
component.decContainersReady(true);
component.decRunningContainers();
}
getCompSpec().removeContainer(containerSpec);
if (container == null) {
LOG.info(getCompInstanceId() + " no container is assigned when " +
"destroying");
return;
}
ContainerId containerId = container.getId();
scheduler.removeLiveCompInstance(containerId);
component.getScheduler().getAmRMClient()
.releaseAssignedContainer(containerId);
if (timelineServiceEnabled) {
serviceTimelinePublisher.componentInstanceFinished(containerId,
KILLED_BY_APPMASTER, diagnostics.toString());
}
cancelContainerStatusRetriever();
scheduler.executorService.submit(() ->
cleanupRegistryAndCompHdfsDir(containerId));
}
private void cleanupRegistry(ContainerId containerId) {
String cid = RegistryPathUtils.encodeYarnID(containerId.toString());
try {
yarnRegistryOperations.deleteComponent(getCompInstanceId(), cid);
} catch (IOException e) {
LOG.error(getCompInstanceId() + ": Failed to delete registry", e);
}
}
//TODO Maybe have a dedicated cleanup service.
public void cleanupRegistryAndCompHdfsDir(ContainerId containerId) {
cleanupRegistry(containerId);
try {
if (compInstanceDir != null && fs.exists(compInstanceDir)) {
boolean deleted = fs.delete(compInstanceDir, true);
if (!deleted) {
LOG.error(getCompInstanceId()
+ ": Failed to delete component instance dir: "
+ compInstanceDir);
} else {
LOG.info(getCompInstanceId() + ": Deleted component instance dir: "
+ compInstanceDir);
}
}
} catch (IOException e) {
LOG.warn(getCompInstanceId() + ": Failed to delete directory", e);
}
}
// Query container status until ip and hostname are available and update
// the service record into registry service
private static class ContainerStatusRetriever implements Runnable {
private ContainerId containerId;
private NodeId nodeId;
private NMClient nmClient;
private ComponentInstance instance;
private boolean cancelOnSuccess;
ContainerStatusRetriever(ServiceScheduler scheduler,
ContainerId containerId, ComponentInstance instance, boolean
cancelOnSuccess) {
this.containerId = containerId;
this.nodeId = instance.getNodeId();
this.nmClient = scheduler.getNmClient().getClient();
this.instance = instance;
this.cancelOnSuccess = cancelOnSuccess;
}
@Override public void run() {
ContainerStatus status = null;
try {
status = nmClient.getContainerStatus(containerId, nodeId);
} catch (Exception e) {
if (e instanceof YarnException) {
throw new YarnRuntimeException(
instance.compInstanceId + " Failed to get container status on "
+ nodeId + " , cancelling.", e);
}
LOG.error(instance.compInstanceId + " Failed to get container status on "
+ nodeId + ", will try again", e);
return;
}
if (ServiceUtils.isEmpty(status.getIPs()) || ServiceUtils
.isUnset(status.getHost())) {
return;
}
instance.updateContainerStatus(status);
if (cancelOnSuccess) {
LOG.info(
instance.compInstanceId + " IP = " + status.getIPs() + ", host = "
+ status.getHost() + ", cancel container status retriever");
instance.containerStatusFuture.cancel(false);
}
}
}
private void cancelContainerStatusRetriever() {
if (containerStatusFuture != null && !containerStatusFuture.isDone()) {
containerStatusFuture.cancel(true);
}
}
public String getHostname() {
String domain = getComponent().getScheduler().getConfig()
.get(RegistryConstants.KEY_DNS_DOMAIN);
String hostname;
if (domain == null || domain.isEmpty()) {
hostname = MessageFormat
.format("{0}.{1}.{2}", getCompInstanceName(),
getComponent().getContext().service.getName(),
RegistryUtils.currentUser());
} else {
hostname = MessageFormat
.format("{0}.{1}.{2}.{3}", getCompInstanceName(),
getComponent().getContext().service.getName(),
RegistryUtils.currentUser(), domain);
}
return hostname;
}
@Override
public int compareTo(ComponentInstance to) {
return getCompInstanceId().compareTo(to.getCompInstanceId());
}
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ComponentInstance instance = (ComponentInstance) o;
if (containerStartedTime != instance.containerStartedTime)
return false;
return compInstanceId.equals(instance.compInstanceId);
}
@Override public int hashCode() {
int result = compInstanceId.hashCode();
result = 31 * result + (int) (containerStartedTime ^ (containerStartedTime
>>> 32));
return result;
}
/**
* Returns container spec.
*/
public org.apache.hadoop.yarn.service.api.records
.Container getContainerSpec() {
readLock.lock();
try {
return containerSpec;
} finally {
readLock.unlock();
}
}
}
| |
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package io.nodyn.dns;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;
/**
* A class that tries to locate name servers and the search path to
* be appended to unqualified names.
* <p/>
* The following are attempted, in order, until one succeeds.
* <UL>
* <LI>The properties 'dns.server' and 'dns.search' (comma delimited lists)
* are checked. The servers can either be IP addresses or hostnames
* (which are resolved using Java's built in DNS support).
* <LI>The sun.net.dns.ResolverConfiguration class is queried.
* <LI>On Unix, /etc/resolv.conf is parsed.
* <LI>On Windows, ipconfig/winipcfg is called and its output parsed. This
* may fail for non-English versions on Windows.
* <LI>"localhost" is used as the nameserver, and the search path is empty.
* </UL>
* <p/>
* These routines will be called internally when creating Resolvers/Lookups
* without explicitly specifying server names, and can also be called
* directly if desired.
*
* @author Brian Wellington
* @author <a href="mailto:yannick@meudal.net">Yannick Meudal</a>
* @author <a href="mailto:arnt@gulbrandsen.priv.no">Arnt Gulbrandsen</a>
*/
public class ResolverConfig {
private String[] servers = null;
private int ndots = -1;
private static ResolverConfig currentConfig;
static {
refresh();
}
public ResolverConfig() {
if (findProperty()) {
return;
}
if (findSunJVM()) {
return;
}
if (this.servers == null) {
String OS = System.getProperty("os.name");
String vendor = System.getProperty("java.vendor");
if (OS.indexOf("Windows") != -1) {
if (OS.indexOf("95") != -1 ||
OS.indexOf("98") != -1 ||
OS.indexOf("ME") != -1)
find95();
else
findNT();
} else if (OS.indexOf("NetWare") != -1) {
findNetware();
} else if (vendor.indexOf("Android") != -1) {
findAndroid();
} else {
findUnix();
}
}
}
private void
addServer(String server, List list) {
if (list.contains(server)) {
return;
}
list.add(server);
}
private int
parseNdots(String token) {
token = token.substring(6);
try {
int ndots = Integer.parseInt(token);
if (ndots >= 0) {
return ndots;
}
} catch (NumberFormatException e) {
}
return -1;
}
private void
configureFromLists(List lserver) {
if (servers == null && lserver.size() > 0) {
servers = (String[]) lserver.toArray(new String[0]);
}
}
private void
configureNdots(int lndots) {
if (ndots < 0 && lndots > 0)
ndots = lndots;
}
/**
* Looks in the system properties to find servers and a search path.
* Servers are defined by dns.server=server1,server2...
* The search path is defined by dns.search=domain1,domain2...
*/
private boolean findProperty() {
String prop;
List lserver = new ArrayList(0);
StringTokenizer st;
prop = System.getProperty("dns.server");
if (prop != null) {
st = new StringTokenizer(prop, ",");
while (st.hasMoreTokens())
addServer(st.nextToken(), lserver);
}
configureFromLists(lserver);
return (servers != null);
}
/**
* Uses the undocumented Sun DNS implementation to determine the configuration.
* This doesn't work or even compile with all JVMs (gcj, for example).
*/
private boolean
findSunJVM() {
List lserver = new ArrayList(0);
List lserver_tmp;
try {
Class[] noClasses = new Class[0];
Object[] noObjects = new Object[0];
String resConfName = "sun.net.dns.ResolverConfiguration";
Class resConfClass = Class.forName(resConfName);
Object resConf;
// ResolverConfiguration resConf = ResolverConfiguration.open();
Method open = resConfClass.getDeclaredMethod("open", noClasses);
resConf = open.invoke(null, noObjects);
// lserver_tmp = resConf.nameservers();
Method nameservers = resConfClass.getMethod("nameservers",
noClasses);
lserver_tmp = (List) nameservers.invoke(resConf, noObjects);
} catch (Exception e) {
return false;
}
if (lserver_tmp.size() == 0)
return false;
if (lserver_tmp.size() > 0) {
Iterator it = lserver_tmp.iterator();
while (it.hasNext())
addServer((String) it.next(), lserver);
}
configureFromLists(lserver);
return true;
}
/**
* Looks in /etc/resolv.conf to find servers and a search path.
* "nameserver" lines specify servers. "domain" and "search" lines
* define the search path.
*/
private void
findResolvConf(String file) {
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
return;
}
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
List lserver = new ArrayList(0);
int lndots = -1;
try {
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("nameserver")) {
StringTokenizer st = new StringTokenizer(line);
st.nextToken(); /* skip nameserver */
addServer(st.nextToken(), lserver);
} else if (line.startsWith("domain")) {
continue;
} else if (line.startsWith("search")) {
continue;
} else if (line.startsWith("options")) {
StringTokenizer st = new StringTokenizer(line);
st.nextToken(); /* skip options */
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.startsWith("ndots:")) {
lndots = parseNdots(token);
}
}
}
}
br.close();
} catch (IOException e) {
}
configureFromLists(lserver);
configureNdots(lndots);
}
private void
findUnix() {
findResolvConf("/etc/resolv.conf");
}
private void
findNetware() {
findResolvConf("sys:/etc/resolv.cfg");
}
/**
* Parses the output of winipcfg or ipconfig.
*/
private void
findWin(InputStream in, Locale locale) {
String packageName = ResolverConfig.class.getPackage().getName();
String resPackageName = packageName + ".windows.DNSServer";
ResourceBundle res;
if (locale != null)
res = ResourceBundle.getBundle(resPackageName, locale);
else
res = ResourceBundle.getBundle(resPackageName);
String host_name = res.getString("host_name");
String primary_dns_suffix = res.getString("primary_dns_suffix");
String dns_suffix = res.getString("dns_suffix");
String dns_servers = res.getString("dns_servers");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
try {
List lserver = new ArrayList();
String line = null;
boolean readingServers = false;
boolean readingSearches = false;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
if (!st.hasMoreTokens()) {
readingServers = false;
readingSearches = false;
continue;
}
String s = st.nextToken();
if (line.indexOf(":") != -1) {
readingServers = false;
readingSearches = false;
}
if (line.indexOf(host_name) != -1) {
while (st.hasMoreTokens()) {
s = st.nextToken();
}
} else if (line.indexOf(primary_dns_suffix) != -1) {
while (st.hasMoreTokens()) {
s = st.nextToken();
}
readingSearches = true;
} else if (readingSearches || line.indexOf(dns_suffix) != -1) {
while (st.hasMoreTokens()) {
s = st.nextToken();
}
if (s.equals(":")) {
continue;
}
readingSearches = true;
} else if (readingServers || line.indexOf(dns_servers) != -1) {
while (st.hasMoreTokens()) {
s = st.nextToken();
}
if (s.equals(":")) {
continue;
}
readingServers = true;
}
}
configureFromLists(lserver);
} catch (IOException e) {
}
return;
}
private void
findWin(InputStream in) {
String property = "org.xbill.DNS.windows.parse.buffer";
final int defaultBufSize = 8 * 1024;
int bufSize = Integer.getInteger(property, defaultBufSize).intValue();
BufferedInputStream b = new BufferedInputStream(in, bufSize);
b.mark(bufSize);
findWin(b, null);
if (servers == null) {
try {
b.reset();
} catch (IOException e) {
return;
}
findWin(b, new Locale("", ""));
}
}
/**
* Calls winipcfg and parses the result to find servers and a search path.
*/
private void
find95() {
String s = "winipcfg.out";
try {
Process p;
p = Runtime.getRuntime().exec("winipcfg /all /batch " + s);
p.waitFor();
File f = new File(s);
findWin(new FileInputStream(f));
new File(s).delete();
} catch (Exception e) {
return;
}
}
/**
* Calls ipconfig and parses the result to find servers and a search path.
*/
private void
findNT() {
try {
Process p;
p = Runtime.getRuntime().exec("ipconfig /all");
findWin(p.getInputStream());
p.destroy();
} catch (Exception e) {
return;
}
}
/**
* Parses the output of getprop, which is the only way to get DNS
* info on Android. getprop might disappear in future releases, so
* this code comes with a use-by date.
*/
private void
findAndroid() {
// This originally looked for all lines containing .dns; but
// http://code.google.com/p/android/issues/detail?id=2207#c73
// indicates that net.dns* should always be the active nameservers, so
// we use those.
final String re1 = "^\\d+(\\.\\d+){3}$";
final String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
ArrayList lserver = new ArrayList();
try {
Class SystemProperties =
Class.forName("android.os.SystemProperties");
Method method =
SystemProperties.getMethod("get",
new Class[]{String.class});
final String[] netdns = new String[]{"net.dns1", "net.dns2",
"net.dns3", "net.dns4"};
for (int i = 0; i < netdns.length; i++) {
Object[] args = new Object[]{netdns[i]};
String v = (String) method.invoke(null, args);
if (v != null &&
(v.matches(re1) || v.matches(re2)) &&
!lserver.contains(v))
lserver.add(v);
}
} catch (Exception e) {
// ignore resolutely
}
configureFromLists(lserver);
}
/**
* Returns all located servers
*/
public String[] servers() {
return servers;
}
/**
* Returns the first located server
*/
public String
server() {
if (servers == null)
return null;
return servers[0];
}
/**
* Returns the located ndots value, or the default (1) if not configured.
* Note that ndots can only be configured in a resolv.conf file, and will only
* take effect if ResolverConfig uses resolv.conf directly (that is, if the
* JVM does not include the sun.net.dns.ResolverConfiguration class).
*/
public int ndots() {
if (ndots < 0) {
return 1;
}
return ndots;
}
/**
* Gets the current configuration
*/
public static synchronized ResolverConfig getCurrentConfig() {
return currentConfig;
}
/**
* Gets the current configuration
*/
public static void refresh() {
ResolverConfig newConfig = new ResolverConfig();
synchronized (ResolverConfig.class) {
currentConfig = newConfig;
}
}
}
| |
package net.minecraft.block.state;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.BlockPistonBase;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class BlockPistonStructureHelper
{
private final World field_177261_a;
private final BlockPos field_177259_b;
private final BlockPos field_177260_c;
private final EnumFacing field_177257_d;
private final List field_177258_e = Lists.newArrayList();
private final List field_177256_f = Lists.newArrayList();
private static final String __OBFID = "CL_00002033";
public BlockPistonStructureHelper(World worldIn, BlockPos p_i45664_2_, EnumFacing p_i45664_3_, boolean p_i45664_4_)
{
this.field_177261_a = worldIn;
this.field_177259_b = p_i45664_2_;
if (p_i45664_4_)
{
this.field_177257_d = p_i45664_3_;
this.field_177260_c = p_i45664_2_.offset(p_i45664_3_);
}
else
{
this.field_177257_d = p_i45664_3_.getOpposite();
this.field_177260_c = p_i45664_2_.offset(p_i45664_3_, 2);
}
}
public boolean func_177253_a()
{
this.field_177258_e.clear();
this.field_177256_f.clear();
Block var1 = this.field_177261_a.getBlockState(this.field_177260_c).getBlock();
if (!BlockPistonBase.func_180696_a(var1, this.field_177261_a, this.field_177260_c, this.field_177257_d, false))
{
if (var1.getMobilityFlag() != 1)
{
return false;
}
else
{
this.field_177256_f.add(this.field_177260_c);
return true;
}
}
else if (!this.func_177251_a(this.field_177260_c))
{
return false;
}
else
{
for (int var2 = 0; var2 < this.field_177258_e.size(); ++var2)
{
BlockPos var3 = (BlockPos)this.field_177258_e.get(var2);
if (this.field_177261_a.getBlockState(var3).getBlock() == Blocks.slime_block && !this.func_177250_b(var3))
{
return false;
}
}
return true;
}
}
private boolean func_177251_a(BlockPos p_177251_1_)
{
Block var2 = this.field_177261_a.getBlockState(p_177251_1_).getBlock();
if (var2.getMaterial() == Material.air)
{
return true;
}
else if (!BlockPistonBase.func_180696_a(var2, this.field_177261_a, p_177251_1_, this.field_177257_d, false))
{
return true;
}
else if (p_177251_1_.equals(this.field_177259_b))
{
return true;
}
else if (this.field_177258_e.contains(p_177251_1_))
{
return true;
}
else
{
int var3 = 1;
if (var3 + this.field_177258_e.size() > 12)
{
return false;
}
else
{
while (var2 == Blocks.slime_block)
{
BlockPos var4 = p_177251_1_.offset(this.field_177257_d.getOpposite(), var3);
var2 = this.field_177261_a.getBlockState(var4).getBlock();
if (var2.getMaterial() == Material.air || !BlockPistonBase.func_180696_a(var2, this.field_177261_a, var4, this.field_177257_d, false) || var4.equals(this.field_177259_b))
{
break;
}
++var3;
if (var3 + this.field_177258_e.size() > 12)
{
return false;
}
}
int var10 = 0;
int var5;
for (var5 = var3 - 1; var5 >= 0; --var5)
{
this.field_177258_e.add(p_177251_1_.offset(this.field_177257_d.getOpposite(), var5));
++var10;
}
var5 = 1;
while (true)
{
BlockPos var6 = p_177251_1_.offset(this.field_177257_d, var5);
int var7 = this.field_177258_e.indexOf(var6);
if (var7 > -1)
{
this.func_177255_a(var10, var7);
for (int var8 = 0; var8 <= var7 + var10; ++var8)
{
BlockPos var9 = (BlockPos)this.field_177258_e.get(var8);
if (this.field_177261_a.getBlockState(var9).getBlock() == Blocks.slime_block && !this.func_177250_b(var9))
{
return false;
}
}
return true;
}
var2 = this.field_177261_a.getBlockState(var6).getBlock();
if (var2.getMaterial() == Material.air)
{
return true;
}
if (!BlockPistonBase.func_180696_a(var2, this.field_177261_a, var6, this.field_177257_d, true) || var6.equals(this.field_177259_b))
{
return false;
}
if (var2.getMobilityFlag() == 1)
{
this.field_177256_f.add(var6);
return true;
}
if (this.field_177258_e.size() >= 12)
{
return false;
}
this.field_177258_e.add(var6);
++var10;
++var5;
}
}
}
}
private void func_177255_a(int p_177255_1_, int p_177255_2_)
{
ArrayList var3 = Lists.newArrayList();
ArrayList var4 = Lists.newArrayList();
ArrayList var5 = Lists.newArrayList();
var3.addAll(this.field_177258_e.subList(0, p_177255_2_));
var4.addAll(this.field_177258_e.subList(this.field_177258_e.size() - p_177255_1_, this.field_177258_e.size()));
var5.addAll(this.field_177258_e.subList(p_177255_2_, this.field_177258_e.size() - p_177255_1_));
this.field_177258_e.clear();
this.field_177258_e.addAll(var3);
this.field_177258_e.addAll(var4);
this.field_177258_e.addAll(var5);
}
private boolean func_177250_b(BlockPos p_177250_1_)
{
EnumFacing[] var2 = EnumFacing.values();
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4)
{
EnumFacing var5 = var2[var4];
if (var5.getAxis() != this.field_177257_d.getAxis() && !this.func_177251_a(p_177250_1_.offset(var5)))
{
return false;
}
}
return true;
}
public List func_177254_c()
{
return this.field_177258_e;
}
public List func_177252_d()
{
return this.field_177256_f;
}
}
| |
package de.samdev.absgdx.framework.menu.elements;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import de.samdev.absgdx.framework.GameSettings;
import de.samdev.absgdx.framework.menu.GUITextureProvider;
import de.samdev.absgdx.framework.menu.attributes.ImageBehavior;
import de.samdev.absgdx.framework.menu.events.MenuImageListener;
/**
* A simple Texture Display
*/
public class MenuImage extends MenuBaseElement {
private TextureRegion[] animation = null;
private int animationLength = 1;
private float frameDuration = 0;
protected float animationPos = 0f;
protected boolean isAnimationPaused = false;
private ImageBehavior behavior = ImageBehavior.FIT;
/**
* Creates a new MenuImage
*/
public MenuImage() {
super();
}
/**
* Creates a new MenuImage
*
* @param identifier the unique button identifier
*/
public MenuImage(String identifier) {
super(identifier);
}
/**
* Creates a new MenuImage
*
* @param identifier the unique button identifier
* @param texprovider the texture provider for this element
*/
public MenuImage(String identifier, GUITextureProvider texprovider) {
super(identifier, texprovider);
}
@Override
public void render(SpriteBatch sbatch, BitmapFont font, int offX, int offY) {
if (getWidth() == 0 || getHeight() == 0) return;
TextureRegion image = getTexture();
if (image == null || image.getTexture() == null) return;
if (getTextureProvider().hasPaddingTextures(getClass())) {
renderPaddingTexture(sbatch, offX, offY);
}
float texWidth;
float texHeight;
switch (behavior) {
case STRETCH:
texWidth = getWidth();
texHeight = getHeight();
sbatch.draw(image, getPositionX(), getPositionY() + getHeight(), getWidth(), -getHeight());
break;
case FIT:
texWidth = getWidth();
texHeight = getHeight();
if (texWidth / texHeight > image.getRegionWidth() * 1f/ image.getRegionHeight()) {
texWidth = texHeight * (image.getRegionWidth() * 1f / image.getRegionHeight());
} else {
texHeight = texWidth * (image.getRegionHeight() * 1f / image.getRegionWidth());
}
break;
case NOSCALE:
texWidth = image.getRegionWidth();
texHeight = image.getRegionHeight();
break;
default:
texWidth = image.getRegionWidth();
texHeight = image.getRegionHeight();
break;
}
sbatch.draw(image, offX + getPositionX(), offY + getPositionY() + texHeight, texWidth, -texHeight);
}
@Override
public void renderCustom(SpriteBatch sbatch, ShapeRenderer srenderer, BitmapFont font, int offX, int offY) {
// NOP
}
@Override
public void renderDebug(ShapeRenderer srenderer, GameSettings settings, int offX, int offY) {
if (settings.debugMenuImageAnimation.isActive() && isAnimated()) {
srenderer.begin(ShapeType.Filled);
{
srenderer.setColor(settings.debugMenuBordersColor.get());
srenderer.rect(offX + getPositionX(), offY + getPositionY(), (animationPos/animationLength) * getWidth(), 3);
srenderer.rect(offX + getPositionX() + getWidth(), offY + getPositionY() + getHeight(), -(animationPos/animationLength) * getWidth(), -4);
srenderer.rect(offX + getPositionX(), offY + getPositionY() + getHeight(), 3, -(animationPos/animationLength) * getHeight());
srenderer.rect(offX + getPositionX() + getWidth(), offY + getPositionY(), -4, (animationPos/animationLength) * getHeight());
}
srenderer.end();
}
}
/**
* Gets the current texture - the return value can change every cycle, don't cache this
*
* @return the texture
*/
public TextureRegion getTexture() {
if (animation == null) return null;
return animation[(int)animationPos];
}
@Override
public void update(float delta) {
if (isAnimated()) {
animationPos += (delta/frameDuration);
animationPos %= animationLength;
}
}
/**
* If the Image is animated
*
* @return if animationLength > 1
*/
public boolean isAnimated() {
return animationLength > 1 && ! isAnimationPaused;
}
/**
* Adds a new listener
*
* @param l the new listener
*/
public void addImageListener(MenuImageListener l) {
super.addElementListener(l);
}
@Override
public MenuBaseElement getElementAt(int x, int y) {
return this;
}
/**
* Set the displayed texture (not animated)
*
* @param texture the new texture
*/
public void setImage(TextureRegion texture) {
this.animation = new TextureRegion[]{texture};
this.animationLength = 1;
this.frameDuration = 0;
this.animationPos = 0;
this.isAnimationPaused = false;
}
/**
* Set the displayed texture (animation)
*
* @param textures the new animation array
* @param animationDuration The duration for one *full* cycle (all frames)
*/
public void setImage(TextureRegion[] textures, float animationDuration) {
this.animation = textures;
this.animationLength = textures.length;
this.frameDuration = animationDuration / animationLength;
this.animationPos = 0;
this.isAnimationPaused = false;
}
/**
* @return the current display behavior
*/
public ImageBehavior getBehavior() {
return behavior;
}
/**
* Set the texture behavior (resize)
*
* @param behavior the new behavior
*/
public void setBehavior(ImageBehavior behavior) {
this.behavior = behavior;
}
@Override
public List<MenuBaseElement> getDirectInnerElements() {
List<MenuBaseElement> result = new ArrayList<MenuBaseElement>();
return result;
}
@Override
public MenuBaseElement getElementByID(String id) {
return identifier.equals(id) ? this : null;
}
}
| |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.testing.NullPointerTester;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.SortedMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Unit test for {@link MinMaxPriorityQueue}.
*
* @author Alexei Stolboushkin
* @author Sverre Sundsdal
*/
public class MinMaxPriorityQueueTest extends TestCase {
private Ordering<Integer> SOME_COMPARATOR = Ordering.natural().reverse();
// Overkill alert! Test all combinations of 0-2 options during creation.
public void testCreation_simple() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.create();
assertEquals(11, queue.capacity());
checkUnbounded(queue);
checkNatural(queue);
}
public void testCreation_comparator() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.orderedBy(SOME_COMPARATOR)
.create();
assertEquals(11, queue.capacity());
checkUnbounded(queue);
assertSame(SOME_COMPARATOR, queue.comparator());
}
public void testCreation_expectedSize() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.expectedSize(8)
.create();
assertEquals(8, queue.capacity());
checkUnbounded(queue);
checkNatural(queue);
}
public void testCreation_expectedSize_comparator() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.orderedBy(SOME_COMPARATOR)
.expectedSize(8)
.create();
assertEquals(8, queue.capacity());
checkUnbounded(queue);
assertSame(SOME_COMPARATOR, queue.comparator());
}
public void testCreation_maximumSize() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.maximumSize(42)
.create();
assertEquals(11, queue.capacity());
assertEquals(42, queue.maximumSize);
checkNatural(queue);
}
public void testCreation_comparator_maximumSize() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.orderedBy(SOME_COMPARATOR)
.maximumSize(42)
.create();
assertEquals(11, queue.capacity());
assertEquals(42, queue.maximumSize);
assertSame(SOME_COMPARATOR, queue.comparator());
}
public void testCreation_expectedSize_maximumSize() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.expectedSize(8)
.maximumSize(42)
.create();
assertEquals(8, queue.capacity());
assertEquals(42, queue.maximumSize);
checkNatural(queue);
}
private static final List<Integer> NUMBERS =
ImmutableList.of(4, 8, 15, 16, 23, 42);
public void testCreation_withContents() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.create(NUMBERS);
assertEquals(6, queue.size());
assertEquals(11, queue.capacity());
checkUnbounded(queue);
checkNatural(queue);
}
public void testCreation_comparator_withContents() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.orderedBy(SOME_COMPARATOR)
.create(NUMBERS);
assertEquals(6, queue.size());
assertEquals(11, queue.capacity());
checkUnbounded(queue);
assertSame(SOME_COMPARATOR, queue.comparator());
}
public void testCreation_expectedSize_withContents() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.expectedSize(8)
.create(NUMBERS);
assertEquals(6, queue.size());
assertEquals(8, queue.capacity());
checkUnbounded(queue);
checkNatural(queue);
}
public void testCreation_maximumSize_withContents() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.maximumSize(42)
.create(NUMBERS);
assertEquals(6, queue.size());
assertEquals(11, queue.capacity());
assertEquals(42, queue.maximumSize);
checkNatural(queue);
}
// Now test everything at once
public void testCreation_allOptions() {
MinMaxPriorityQueue<Integer> queue = MinMaxPriorityQueue
.orderedBy(SOME_COMPARATOR)
.expectedSize(8)
.maximumSize(42)
.create(NUMBERS);
assertEquals(6, queue.size());
assertEquals(8, queue.capacity());
assertEquals(42, queue.maximumSize);
assertSame(SOME_COMPARATOR, queue.comparator());
}
// TODO: tests that check the weird interplay between expected size,
// maximum size, size of initial contents, default capacity...
private static void checkNatural(MinMaxPriorityQueue<Integer> queue) {
assertSame(Ordering.natural(), queue.comparator());
}
private static void checkUnbounded(MinMaxPriorityQueue<Integer> queue) {
assertEquals(Integer.MAX_VALUE, queue.maximumSize);
}
public void testHeapIntact() {
Random random = new Random(0);
int heapSize = 999;
int numberOfModifications = 500;
MinMaxPriorityQueue<Integer> mmHeap =
MinMaxPriorityQueue.expectedSize(heapSize).create();
/*
* this map would contain the same exact elements as the MinMaxHeap; the
* value in the map is the number of occurrences of the key.
*/
SortedMap<Integer, AtomicInteger> replica = Maps.newTreeMap();
assertTrue("Empty heap should be OK", mmHeap.isIntact());
for (int i = 0; i < heapSize; i++) {
int randomInt = random.nextInt();
mmHeap.offer(randomInt);
insertIntoReplica(replica, randomInt);
}
assertTrue("MinMaxHeap not intact after " + heapSize + " insertions",
mmHeap.isIntact());
assertEquals(heapSize, mmHeap.size());
int currentHeapSize = heapSize;
for (int i = 0; i < numberOfModifications; i++) {
if (random.nextBoolean()) {
/* insert a new element */
int randomInt = random.nextInt();
mmHeap.offer(randomInt);
insertIntoReplica(replica, randomInt);
currentHeapSize++;
} else {
/* remove either min or max */
if (random.nextBoolean()) {
removeMinFromReplica(replica, mmHeap.poll());
} else {
removeMaxFromReplica(replica, mmHeap.pollLast());
}
for (Integer v : replica.keySet()) {
assertTrue("MinMax queue has lost " + v, mmHeap.contains(v));
}
assertTrue(mmHeap.isIntact());
currentHeapSize--;
assertEquals(currentHeapSize, mmHeap.size());
}
}
assertEquals(currentHeapSize, mmHeap.size());
assertTrue("Heap not intact after " + numberOfModifications +
" random mixture of operations", mmHeap.isIntact());
}
public void testSmall() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.add(1);
mmHeap.add(4);
mmHeap.add(2);
mmHeap.add(3);
assertEquals(4, (int) mmHeap.pollLast());
assertEquals(3, (int) mmHeap.peekLast());
assertEquals(3, (int) mmHeap.pollLast());
assertEquals(1, (int) mmHeap.peek());
assertEquals(2, (int) mmHeap.peekLast());
assertEquals(2, (int) mmHeap.pollLast());
assertEquals(1, (int) mmHeap.peek());
assertEquals(1, (int) mmHeap.peekLast());
assertEquals(1, (int) mmHeap.pollLast());
assertNull(mmHeap.peek());
assertNull(mmHeap.peekLast());
assertNull(mmHeap.pollLast());
}
public void testSmallMinHeap() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.add(1);
mmHeap.add(3);
mmHeap.add(2);
assertEquals(1, (int) mmHeap.peek());
assertEquals(1, (int) mmHeap.poll());
assertEquals(3, (int) mmHeap.peekLast());
assertEquals(2, (int) mmHeap.peek());
assertEquals(2, (int) mmHeap.poll());
assertEquals(3, (int) mmHeap.peekLast());
assertEquals(3, (int) mmHeap.peek());
assertEquals(3, (int) mmHeap.poll());
assertNull(mmHeap.peekLast());
assertNull(mmHeap.peek());
assertNull(mmHeap.poll());
}
public void testRemove() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 2, 3, 4, 47, 1, 5, 3, 0));
assertTrue("Heap is not intact initally", mmHeap.isIntact());
assertEquals(9, mmHeap.size());
mmHeap.remove(5);
assertEquals(8, mmHeap.size());
assertTrue("Heap is not intact after remove()", mmHeap.isIntact());
assertEquals(47, (int) mmHeap.pollLast());
assertEquals(4, (int) mmHeap.pollLast());
mmHeap.removeAll(Lists.newArrayList(2, 3));
assertEquals(3, mmHeap.size());
assertTrue("Heap is not intact after removeAll()", mmHeap.isIntact());
}
public void testContains() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 1, 2));
assertEquals(3, mmHeap.size());
assertFalse("Heap does not contain null", mmHeap.contains(null));
assertFalse("Heap does not contain 3", mmHeap.contains(3));
assertFalse("Heap does not contain 3", mmHeap.remove(3));
assertEquals(3, mmHeap.size());
assertTrue("Heap is not intact after remove()", mmHeap.isIntact());
assertTrue("Heap contains two 1's", mmHeap.contains(1));
assertTrue("Heap contains two 1's", mmHeap.remove(1));
assertTrue("Heap contains 1", mmHeap.contains(1));
assertTrue("Heap contains 1", mmHeap.remove(1));
assertFalse("Heap does not contain 1", mmHeap.contains(1));
assertTrue("Heap contains 2", mmHeap.remove(2));
assertEquals(0, mmHeap.size());
assertFalse("Heap does not contain anything", mmHeap.contains(1));
assertFalse("Heap does not contain anything", mmHeap.remove(2));
}
public void testIteratorPastEndException() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 2));
Iterator<Integer> it = mmHeap.iterator();
assertTrue("Iterator has reached end prematurely", it.hasNext());
it.next();
it.next();
try {
it.next();
fail("No exception thrown when iterating past end of heap");
} catch (NoSuchElementException e) {
// expected error
}
}
public void testIteratorConcurrentModification() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(1, 2, 3, 4));
Iterator<Integer> it = mmHeap.iterator();
assertTrue("Iterator has reached end prematurely", it.hasNext());
it.next();
it.next();
mmHeap.remove(4);
try {
it.next();
fail("No exception thrown when iterating a modified heap");
} catch (ConcurrentModificationException e) {
// expected error
}
}
/**
* Tests a failure caused by fix to childless uncle issue.
*/
public void testIteratorRegressionChildlessUncle() {
final ArrayList<Integer> initial = Lists.newArrayList(
1, 15, 13, 8, 9, 10, 11, 14);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create(initial);
assertTrue("State " + Arrays.toString(q.toArray()), q.isIntact());
q.remove(9);
q.remove(11);
q.remove(10);
// Now we're in the critical state: [1, 15, 13, 8, 14]
// Removing 8 while iterating caused duplicates in iteration result.
List<Integer> result = Lists.newArrayListWithCapacity(initial.size());
for (Iterator<Integer> iter = q.iterator(); iter.hasNext();) {
Integer value = iter.next();
result.add(value);
if (value == 8) {
iter.remove();
}
}
assertTrue(q.isIntact());
ASSERT.that(result).hasContentsAnyOrder(1, 15, 13, 8, 14);
}
/**
* This tests a special case of the removeAt() call. Moving an element
* sideways on the heap could break the invariants. Sometimes we need to
* bubble an element up instead of trickling down. See implementation.
*/
public void testInvalidatingRemove() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(
1, 20, 1000, 2, 3, 30, 40, 10, 11, 12, 13, 300, 400, 500, 600));
assertEquals(15, mmHeap.size());
assertTrue("Heap is not intact initially", mmHeap.isIntact());
mmHeap.remove(12);
assertEquals(14, mmHeap.size());
assertTrue("Heap is not intact after remove()", mmHeap.isIntact());
}
/**
* This tests a more obscure special case, but otherwise similar to above.
*/
public void testInvalidatingRemove2() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
List<Integer> values = Lists.newArrayList(
1, 20, 1000, 2, 3, 30, 40, 10, 11, 12, 13, 300, 400, 500, 600, 4, 5,
6, 7, 8, 9, 4, 5, 200, 250);
mmHeap.addAll(values);
assertEquals(25, mmHeap.size());
assertTrue("Heap is not intact initially", mmHeap.isIntact());
mmHeap.remove(2);
assertEquals(24, mmHeap.size());
assertTrue("Heap is not intact after remove()", mmHeap.isIntact());
values.removeAll(Lists.newArrayList(2));
assertEquals(values.size(), mmHeap.size());
assertTrue(values.containsAll(mmHeap));
assertTrue(mmHeap.containsAll(values));
}
public void testIteratorInvalidatingIteratorRemove() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(
1, 20, 100, 2, 3, 30, 40));
assertEquals(7, mmHeap.size());
assertTrue("Heap is not intact initially", mmHeap.isIntact());
Iterator<Integer> it = mmHeap.iterator();
assertEquals((Integer) 1, it.next());
assertEquals((Integer) 20, it.next());
assertEquals((Integer) 100, it.next());
assertEquals((Integer) 2, it.next());
it.remove();
assertFalse(mmHeap.contains(2));
assertTrue(it.hasNext());
assertEquals((Integer) 3, it.next());
assertTrue(it.hasNext());
assertEquals((Integer) 30, it.next());
assertTrue(it.hasNext());
assertEquals((Integer) 40, it.next());
assertFalse(it.hasNext());
assertEquals(6, mmHeap.size());
assertTrue("Heap is not intact after remove()", mmHeap.isIntact());
assertFalse(mmHeap.contains(2));
// This tests that it.remove() above actually changed the order. It
// indicates that the value 40 was stored in forgetMeNot, so it is
// returned in the last call to it.next(). Without it, 30 should be the last
// item returned by the iterator.
Integer lastItem = 0;
for (Integer tmp : mmHeap) {
lastItem = tmp;
}
assertEquals((Integer) 30, lastItem);
}
/**
* This tests a special case where removeAt has to trickle an element
* first down one level from a min to a max level, then up one level above
* the index of the removed element.
* It also tests that skipMe in the iterator plays nicely with
* forgetMeNot.
*/
public void testIteratorInvalidatingIteratorRemove2() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.create();
mmHeap.addAll(Lists.newArrayList(
1, 20, 1000, 2, 3, 30, 40, 10, 11, 12, 13, 200, 300, 500, 400));
assertTrue("Heap is not intact initially", mmHeap.isIntact());
Iterator<Integer> it = mmHeap.iterator();
assertEquals((Integer) 1, it.next());
assertEquals((Integer) 20, it.next());
assertEquals((Integer) 1000, it.next());
assertEquals((Integer) 2, it.next());
it.remove();
assertTrue("Heap is not intact after remove", mmHeap.isIntact());
assertEquals((Integer) 10, it.next());
assertEquals((Integer) 3, it.next());
it.remove();
assertTrue("Heap is not intact after remove", mmHeap.isIntact());
assertEquals((Integer) 12, it.next());
assertEquals((Integer) 30, it.next());
assertEquals((Integer) 40, it.next());
// Skipping 20
assertEquals((Integer) 11, it.next());
// Skipping 400
assertEquals((Integer) 13, it.next());
assertEquals((Integer) 200, it.next());
assertEquals((Integer) 300, it.next());
// Last two from forgetMeNot.
assertEquals((Integer) 400, it.next());
assertEquals((Integer) 500, it.next());
}
public void testRemoveFromStringHeap() {
MinMaxPriorityQueue<String> mmHeap =
MinMaxPriorityQueue.expectedSize(5).create();
Collections.addAll(mmHeap,
"foo", "bar", "foobar", "barfoo", "larry", "sergey", "eric");
assertTrue("Heap is not intact initially", mmHeap.isIntact());
assertEquals("bar", mmHeap.peek());
assertEquals("sergey", mmHeap.peekLast());
assertEquals(7, mmHeap.size());
assertTrue("Could not remove larry", mmHeap.remove("larry"));
assertEquals(6, mmHeap.size());
assertFalse("heap contains larry which has been removed",
mmHeap.contains("larry"));
assertTrue("heap does not contain sergey",
mmHeap.contains("sergey"));
assertTrue("Could not remove larry", mmHeap.removeAll(
Lists.newArrayList("sergey", "eric")));
assertFalse("Could remove nikesh which is not in the heap",
mmHeap.remove("nikesh"));
assertEquals(4, mmHeap.size());
}
public void testCreateWithOrdering() {
MinMaxPriorityQueue<String> mmHeap =
MinMaxPriorityQueue.orderedBy(Ordering.natural().reverse()).create();
Collections.addAll(mmHeap,
"foo", "bar", "foobar", "barfoo", "larry", "sergey", "eric");
assertTrue("Heap is not intact initially", mmHeap.isIntact());
assertEquals("sergey", mmHeap.peek());
assertEquals("bar", mmHeap.peekLast());
}
public void testCreateWithCapacityAndOrdering() {
MinMaxPriorityQueue<Integer> mmHeap = MinMaxPriorityQueue.orderedBy(
Ordering.natural().reverse()).expectedSize(5).create();
Collections.addAll(mmHeap, 1, 7, 2, 56, 2, 5, 23, 68, 0, 3);
assertTrue("Heap is not intact initially", mmHeap.isIntact());
assertEquals(68, (int) mmHeap.peek());
assertEquals(0, (int) mmHeap.peekLast());
}
private <T extends Comparable<T>> void runIterator(
final List<T> values, int steps) throws Exception {
IteratorTester<T> tester =
new IteratorTester<T>(
steps,
IteratorFeature.MODIFIABLE,
Lists.newLinkedList(values),
IteratorTester.KnownOrder.UNKNOWN_ORDER) {
private MinMaxPriorityQueue<T> mmHeap;
@Override protected Iterator<T> newTargetIterator() {
mmHeap = MinMaxPriorityQueue.create(values);
return mmHeap.iterator();
}
@Override protected void verify(List<T> elements) {
assertEquals(Sets.newHashSet(elements),
Sets.newHashSet(mmHeap.iterator()));
assertTrue("Invalid MinMaxHeap: " + mmHeap.toString(),
mmHeap.isIntact());
}
};
tester.ignoreSunJavaBug6529795();
tester.test();
}
public void testIteratorTester() throws Exception {
Random random = new Random(0);
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 3; i++) {
list.add(random.nextInt());
}
runIterator(list, 6);
}
public void testIteratorTesterLarger() throws Exception {
runIterator(Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 5);
}
public void testRemoveAt() {
long seed = new Random().nextLong();
Random random = new Random(seed);
int heapSize = 999;
int numberOfModifications = 500;
MinMaxPriorityQueue<Integer> mmHeap =
MinMaxPriorityQueue.expectedSize(heapSize).create();
for (int i = 0; i < heapSize; i++) {
mmHeap.add(random.nextInt());
}
for (int i = 0; i < numberOfModifications; i++) {
mmHeap.removeAt(random.nextInt(mmHeap.size()));
assertTrue("Modification " + i + " of seed " + seed, mmHeap.isIntact());
mmHeap.add(random.nextInt());
assertTrue("Modification " + i + " of seed " + seed, mmHeap.isIntact());
}
}
/**
* Regression test for bug found.
*/
public void testCorrectOrdering_regression() {
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue
.create(ImmutableList.of(3, 5, 1, 4, 7));
List<Integer> expected = ImmutableList.of(1, 3, 4, 5, 7);
List<Integer> actual = new ArrayList<Integer>(5);
for (int i = 0; i < expected.size(); i++) {
actual.add(q.pollFirst());
}
assertEquals(expected, actual);
}
public void testCorrectOrdering_smallHeapsPollFirst() {
for (int size = 2; size < 16; size++) {
for (int attempts = 0; attempts < size * (size - 1); attempts++) {
ArrayList<Integer> elements = createOrderedList(size);
List<Integer> expected = ImmutableList.copyOf(elements);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
long seed = insertRandomly(elements, q);
while (!q.isEmpty()) {
elements.add(q.pollFirst());
}
assertEquals("Using seed " + seed, expected, elements);
}
}
}
public void testCorrectOrdering_smallHeapsPollLast() {
for (int size = 2; size < 16; size++) {
for (int attempts = 0; attempts < size * (size - 1); attempts++) {
ArrayList<Integer> elements = createOrderedList(size);
List<Integer> expected = ImmutableList.copyOf(elements);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
long seed = insertRandomly(elements, q);
while (!q.isEmpty()) {
elements.add(0, q.pollLast());
}
assertEquals("Using seed " + seed, expected, elements);
}
}
}
public void testCorrectOrdering_mediumHeapsPollFirst() {
for (int attempts = 0; attempts < 5000; attempts++) {
int size = new Random().nextInt(256) + 16;
ArrayList<Integer> elements = createOrderedList(size);
List<Integer> expected = ImmutableList.copyOf(elements);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
long seed = insertRandomly(elements, q);
while (!q.isEmpty()) {
elements.add(q.pollFirst());
}
assertEquals("Using seed " + seed, expected, elements);
}
}
/**
* Regression test for bug found in random testing.
*/
public void testCorrectOrdering_73ElementBug() {
int size = 73;
long seed = 7522346378524621981L;
ArrayList<Integer> elements = createOrderedList(size);
List<Integer> expected = ImmutableList.copyOf(elements);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
insertRandomly(elements, q, new Random(seed));
assertTrue(q.isIntact());
while (!q.isEmpty()) {
elements.add(q.pollFirst());
assertTrue("State " + Arrays.toString(q.toArray()), q.isIntact());
}
assertEquals("Using seed " + seed, expected, elements);
}
public void testCorrectOrdering_mediumHeapsPollLast() {
for (int attempts = 0; attempts < 5000; attempts++) {
int size = new Random().nextInt(256) + 16;
ArrayList<Integer> elements = createOrderedList(size);
List<Integer> expected = ImmutableList.copyOf(elements);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
long seed = insertRandomly(elements, q);
while (!q.isEmpty()) {
elements.add(0, q.pollLast());
}
assertEquals("Using seed " + seed, expected, elements);
}
}
public void testCorrectOrdering_randomAccess() {
long seed = new Random().nextLong();
Random random = new Random(seed);
PriorityQueue<Integer> control = new PriorityQueue<Integer>();
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
for (int i = 0; i < 73; i++) { // 73 is a childless uncle case.
Integer element = random.nextInt();
control.add(element);
assertTrue(q.add(element));
}
assertTrue("State " + Arrays.toString(q.toArray()), q.isIntact());
for (int i = 0; i < 500000; i++) {
if (random.nextBoolean()) {
Integer element = random.nextInt();
control.add(element);
q.add(element);
} else {
assertEquals("Using seed " + seed, control.poll(), q.pollFirst());
}
}
while (!control.isEmpty()) {
assertEquals("Using seed " + seed, control.poll(), q.pollFirst());
}
assertTrue(q.isEmpty());
}
/**
* Regression test for b/4124577
*/
public void testRegression_dataCorruption() {
int size = 8;
List<Integer> expected = createOrderedList(size);
MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create(expected);
List<Integer> contents = Lists.newArrayList(expected);
List<Integer> elements = Lists.newArrayListWithCapacity(size);
while (!q.isEmpty()) {
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
Integer next = q.pollFirst();
contents.remove(next);
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
for (int i = 0; i <= size; i++) {
q.add(i);
contents.add(i);
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
q.add(next);
contents.add(next);
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
q.remove(i);
assertTrue(contents.remove(Integer.valueOf(i)));
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
assertEquals(next, q.poll());
contents.remove(next);
ASSERT.that(q).hasContentsAnyOrder(contents.toArray(new Integer[0]));
}
elements.add(next);
}
assertEquals(expected, elements);
}
/**
* Returns the seed used for the randomization.
*/
private long insertRandomly(ArrayList<Integer> elements,
MinMaxPriorityQueue<Integer> q) {
long seed = new Random().nextLong();
Random random = new Random(seed);
insertRandomly(elements, q, random);
return seed;
}
private void insertRandomly(ArrayList<Integer> elements, MinMaxPriorityQueue<Integer> q,
Random random) {
while (!elements.isEmpty()) {
int selectedIndex = random.nextInt(elements.size());
q.offer(elements.remove(selectedIndex));
}
}
private ArrayList<Integer> createOrderedList(int size) {
ArrayList<Integer> elements = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
elements.add(i);
}
return elements;
}
public void testIsEvenLevel() {
assertTrue(MinMaxPriorityQueue.isEvenLevel(0));
assertFalse(MinMaxPriorityQueue.isEvenLevel(1));
assertFalse(MinMaxPriorityQueue.isEvenLevel(2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(3));
assertFalse(MinMaxPriorityQueue.isEvenLevel((1 << 10) - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 10) - 1));
int i = 1 << 29;
assertTrue(MinMaxPriorityQueue.isEvenLevel(i - 2));
assertFalse(MinMaxPriorityQueue.isEvenLevel(i - 1));
assertFalse(MinMaxPriorityQueue.isEvenLevel(i));
i = 1 << 30;
assertFalse(MinMaxPriorityQueue.isEvenLevel(i - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(i - 1));
assertTrue(MinMaxPriorityQueue.isEvenLevel(i));
// 1 << 31 is negative because of overflow, 1 << 31 - 1 is positive
// since isEvenLevel adds 1, we need to do - 2.
assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 31) - 2));
assertTrue(MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE - 1));
try {
MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1);
fail("Should overflow");
} catch (IllegalStateException e) {
// expected
}
try {
MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE);
fail("Should overflow");
} catch (IllegalStateException e) {
// expected
}
try {
MinMaxPriorityQueue.isEvenLevel(1 << 31);
fail("Should be negative");
} catch (IllegalStateException e) {
// expected
}
try {
MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE);
fail("Should be negative");
} catch (IllegalStateException e) {
// expected
}
}
public void testNullPointers() throws Exception {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicConstructors(MinMaxPriorityQueue.class);
tester.testAllPublicStaticMethods(MinMaxPriorityQueue.class);
tester.testAllPublicInstanceMethods(MinMaxPriorityQueue.<String>create());
}
private static void insertIntoReplica(
Map<Integer, AtomicInteger> replica,
int newValue) {
if (replica.containsKey(newValue)) {
replica.get(newValue).incrementAndGet();
} else {
replica.put(newValue, new AtomicInteger(1));
}
}
private static void removeMinFromReplica(
SortedMap<Integer, AtomicInteger> replica,
int minValue) {
Integer replicatedMinValue = replica.firstKey();
assertEquals(replicatedMinValue, (Integer) minValue);
removeFromReplica(replica, replicatedMinValue);
}
private static void removeMaxFromReplica(
SortedMap<Integer, AtomicInteger> replica,
int maxValue) {
Integer replicatedMaxValue = replica.lastKey();
assertTrue("maxValue is incorrect", replicatedMaxValue == maxValue);
removeFromReplica(replica, replicatedMaxValue);
}
private static void removeFromReplica(
Map<Integer, AtomicInteger> replica, int value) {
AtomicInteger numOccur = replica.get(value);
if (numOccur.decrementAndGet() == 0) {
replica.remove(value);
}
}
}
| |
/* Copyright 2020 Telstra Open Source
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openkilda.wfm.topology.network.storm.bolt.bfd.worker;
import org.openkilda.messaging.command.CommandData;
import org.openkilda.messaging.command.grpc.CreateLogicalPortRequest;
import org.openkilda.messaging.command.grpc.DeleteLogicalPortRequest;
import org.openkilda.messaging.error.ErrorData;
import org.openkilda.messaging.error.ErrorType;
import org.openkilda.messaging.floodlight.request.RemoveBfdSession;
import org.openkilda.messaging.floodlight.request.SetupBfdSession;
import org.openkilda.messaging.floodlight.response.BfdSessionResponse;
import org.openkilda.messaging.info.grpc.CreateLogicalPortResponse;
import org.openkilda.messaging.info.grpc.DeleteLogicalPortResponse;
import org.openkilda.messaging.model.NoviBfdSession;
import org.openkilda.messaging.model.grpc.LogicalPortType;
import org.openkilda.model.Switch;
import org.openkilda.model.SwitchId;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.persistence.repositories.SwitchRepository;
import org.openkilda.wfm.error.PipelineException;
import org.openkilda.wfm.share.hubandspoke.WorkerBolt;
import org.openkilda.wfm.share.model.Endpoint;
import org.openkilda.wfm.topology.network.storm.bolt.GrpcRouter;
import org.openkilda.wfm.topology.network.storm.bolt.SpeakerEncoder;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.BfdHub;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubGrpcErrorResponseCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubPortCreateResponseCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubPortDeleteResponseCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubSessionResponseCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.hub.command.BfdHubSessionTimeoutCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.worker.command.BfdWorkerCommand;
import org.openkilda.wfm.topology.network.storm.bolt.bfd.worker.response.BfdWorkerAsyncResponse;
import org.openkilda.wfm.topology.network.storm.bolt.speaker.SpeakerRouter;
import lombok.extern.slf4j.Slf4j;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Optional;
@Slf4j
public class BfdWorker extends WorkerBolt {
public static final String BOLT_ID = WorkerBolt.ID + ".bfd";
public static final String FIELD_ID_PAYLOAD = SpeakerEncoder.FIELD_ID_PAYLOAD;
public static final String FIELD_ID_KEY = SpeakerEncoder.FIELD_ID_KEY;
public static final String STREAM_HUB_ID = "hub";
private static final Fields STREAM_FIELDS = new Fields(FIELD_ID_KEY, FIELD_ID_PAYLOAD, FIELD_ID_CONTEXT);
public static final String STREAM_SPEAKER_ID = "speaker";
public static final Fields STREAM_SPEAKER_FIELDS = STREAM_FIELDS;
public static final String STREAM_GRPC_ID = "grpc";
public static final Fields STREAM_GRPC_FIELDS = STREAM_FIELDS;
private final PersistenceManager persistenceManager;
private transient SwitchRepository switchRepository;
public BfdWorker(Config config, PersistenceManager persistenceManager) {
super(config);
this.persistenceManager = persistenceManager;
}
@Override
protected void dispatch(Tuple input) throws Exception {
String source = input.getSourceComponent();
if (GrpcRouter.BOLT_ID.equals(source)) {
dispatchResponse(input);
} else {
super.dispatch(input);
}
}
@Override
protected void onHubRequest(Tuple input) throws PipelineException {
BfdWorkerCommand command = pullHubCommand(input);
command.apply(this);
}
@Override
protected void onAsyncResponse(Tuple requestTuple, Tuple responseTuple) throws PipelineException {
String source = responseTuple.getSourceComponent();
BfdWorkerAsyncResponse response;
if (SpeakerRouter.BOLT_ID.equals(source)) {
response = pullAsyncResponse(responseTuple, SpeakerRouter.FIELD_ID_INPUT);
} else if (GrpcRouter.BOLT_ID.equals(source)) {
response = pullAsyncResponse(responseTuple, GrpcRouter.FIELD_ID_PAYLOAD);
} else {
unhandledInput(responseTuple);
return;
}
BfdWorkerCommand request = pullHubCommand(requestTuple);
response.consume(this, request);
}
@Override
protected void onRequestTimeout(Tuple request) {
try {
handleTimeout(request, BfdHub.FIELD_ID_COMMAND);
} catch (PipelineException e) {
log.error("Unable to unpack original tuple in timeout processing - {}", e.getMessage());
}
}
// -- commands processing --
public void processBfdSetupRequest(String key, NoviBfdSession bfdSession) {
SetupBfdSession payload = new SetupBfdSession(bfdSession);
emitSpeakerRequest(key, payload);
}
public void processBfdRemoveRequest(String key, NoviBfdSession bfdSession) {
RemoveBfdSession payload = new RemoveBfdSession(bfdSession);
emitSpeakerRequest(key, payload);
}
public void processBfdSessionResponse(String requestId, Endpoint logical, BfdSessionResponse response) {
emitResponseToHub(getCurrentTuple(), makeHubTuple(
requestId, new BfdHubSessionResponseCommand(requestId, logical, response)));
}
/**
* Send logical port (BFD) create request.
*/
public void processPortCreateRequest(String requestId, Endpoint logical, int physicalPortNumber) {
Optional<String> address = lookupSwitchAddress(logical.getDatapath());
if (! address.isPresent()) {
processPortCrudErrorResponse(requestId, logical, makeSwitchAddressNotFoundError(logical.getDatapath()));
return;
}
CreateLogicalPortRequest request = new CreateLogicalPortRequest(
address.get(), Collections.singletonList(physicalPortNumber), logical.getPortNumber(),
LogicalPortType.BFD);
emit(STREAM_GRPC_ID, getCurrentTuple(), makeGrpcTuple(requestId, request));
}
/**
* Send logical port (BFD) delete request.
*/
public void processPortDeleteRequest(String requestId, Endpoint logical) {
Optional<String> address = lookupSwitchAddress(logical.getDatapath());
if (!address.isPresent()) {
processPortCrudErrorResponse(requestId, logical, makeSwitchAddressNotFoundError(logical.getDatapath()));
return;
}
DeleteLogicalPortRequest request = new DeleteLogicalPortRequest(address.get(), logical.getPortNumber());
emit(STREAM_GRPC_ID, getCurrentTuple(), makeGrpcTuple(requestId, request));
}
public void processPortCreateResponse(String requestId, Endpoint logical, CreateLogicalPortResponse response) {
emitResponseToHub(getCurrentTuple(), makeHubTuple(requestId, new BfdHubPortCreateResponseCommand(
requestId, logical, response)));
}
public void processPortDeleteResponse(String requestId, Endpoint logical, DeleteLogicalPortResponse response) {
emitResponseToHub(getCurrentTuple(), makeHubTuple(requestId, new BfdHubPortDeleteResponseCommand(
requestId, logical, response)));
}
public void processPortCrudErrorResponse(String requestId, Endpoint logical, ErrorData response) {
emitResponseToHub(getCurrentTuple(), makeHubTuple(requestId, new BfdHubGrpcErrorResponseCommand(
requestId, logical, response)));
}
public void processSessionRequestTimeout(String requestId, Endpoint logical) {
emitResponseToHub(
getCurrentTuple(), makeHubTuple(requestId, new BfdHubSessionTimeoutCommand(requestId, logical)));
}
public void processPortRequestTimeout(String requestID, Endpoint logical) {
emitResponseToHub(getCurrentTuple(), makeHubTuple(requestID, new BfdHubGrpcErrorResponseCommand(
requestID, logical, null)));
}
// -- setup --
@Override
protected void init() {
super.init();
switchRepository = persistenceManager.getRepositoryFactory().createSwitchRepository();
}
@Override
public void declareOutputFields(OutputFieldsDeclarer streamManager) {
super.declareOutputFields(streamManager); // it will define HUB stream
streamManager.declareStream(STREAM_SPEAKER_ID, STREAM_SPEAKER_FIELDS);
streamManager.declareStream(STREAM_GRPC_ID, STREAM_GRPC_FIELDS);
}
// -- private/service methods --
private void handleTimeout(Tuple request, String field) throws PipelineException {
BfdWorkerCommand command = pullValue(request, field, BfdWorkerCommand.class);
command.timeout(this);
}
public void emitSpeakerRequest(String key, CommandData payload) {
emit(STREAM_SPEAKER_ID, getCurrentTuple(), makeSpeakerTuple(key, payload));
}
private Optional<String> lookupSwitchAddress(SwitchId switchId) {
Optional<Switch> sw = switchRepository.findById(switchId);
if (! sw.isPresent()) {
return Optional.empty();
}
InetSocketAddress address = sw.get().getSocketAddress();
return Optional.of(address.getAddress().getHostAddress());
}
private ErrorData makeSwitchAddressNotFoundError(SwitchId switchId) {
String message = String.format("Can't determine switch %s ip address", switchId);
return new ErrorData(ErrorType.INTERNAL_ERROR, message, "");
}
private BfdWorkerCommand pullHubCommand(Tuple tuple) throws PipelineException {
return pullValue(tuple, BfdHub.FIELD_ID_COMMAND, BfdWorkerCommand.class);
}
private BfdWorkerAsyncResponse pullAsyncResponse(Tuple tuple, String field) throws PipelineException {
return pullValue(tuple, field, BfdWorkerAsyncResponse.class);
}
private Values makeHubTuple(String key, BfdHubCommand command) {
return new Values(key, command, getCommandContext());
}
private Values makeSpeakerTuple(String key, CommandData payload) {
return makeGenericKafkaProduceTuple(key, payload);
}
private Values makeGrpcTuple(String key, CommandData payload) {
return makeGenericKafkaProduceTuple(key, payload);
}
private Values makeGenericKafkaProduceTuple(String key, CommandData payload) {
return new Values(key, payload, getCommandContext());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.uima.adapter.vinci.util;
import java.util.Stack;
import org.apache.vinci.transport.document.AFrame;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
// TODO: Auto-generated Javadoc
/**
* A SAX content handler that builds a VinciFrame corresponding to the SAX events received.
*
*
*/
public class SaxVinciFrameBuilder extends DefaultHandler implements ContentHandler {
/** The m open frames. */
private Stack mOpenFrames;
/** The m current frame name. */
private String mCurrentFrameName;
/** The m current frame attrs. */
private Attributes mCurrentFrameAttrs;
/** The m char content buffer. */
private StringBuffer mCharContentBuffer;
/**
* Sets the parent frame, to which frames built by the object will be added. This MUST be called
* before parsing a document.
*
* @param aParentFrame
* the parent frame
*/
public void setParentFrame(AFrame aParentFrame) {
mOpenFrames = new Stack();
mOpenFrames.push(aParentFrame);
}
/**
* Start document.
*
* @throws SAXException
* the SAX exception
* @see org.xml.sax.ContentHandler#startDocument()
*/
@Override
public void startDocument() throws SAXException {
mCurrentFrameName = null;
mCurrentFrameAttrs = null;
mCharContentBuffer = new StringBuffer();
}
/**
* Called for each start tag encountered.
*
* @param namespaceURI
* Required if the namespaces property is true.
* @param localName
* The local name (without prefix), or the empty string if Namespace processing is not
* being performed.
* @param qualifiedName
* The qualified name (with prefix), or the empty string if qualified names are not
* available.
* @param attributes
* The specified or defaulted attributes.
* @throws SAXException
* the SAX exception
*/
@Override
public void startElement(String namespaceURI, String localName, String qualifiedName,
org.xml.sax.Attributes attributes) throws SAXException {
// I would like to create a VinciFrame here and put it on the
// mOpenFrames stack, but I don't know whether to create a VinciFrame or
// a FrameLeaf until I see whether there are child elements. So instead
// the element information is stored temporarily until the next call to
// startElement (indicating a non-leaf) or endElement (indicating a leaf)
// first, check to see whether we have a frame for which this temporary info
// was stored from the previous call to startElement.
if (mCurrentFrameName != null) {
// create a non-leaf frame
AFrame frame = new AFrame();
// add this frame to its parent frame
// (the one on top of stack)
AFrame parent = (AFrame) mOpenFrames.peek();
org.apache.vinci.transport.Attributes vinciAttrs = parent.aadd(mCurrentFrameName, frame);
// set attributes
if (mCurrentFrameAttrs != null) {
for (int i = 0; i < mCurrentFrameAttrs.getLength(); i++) {
String attrName = getName(mCurrentFrameAttrs.getLocalName(i),
mCurrentFrameAttrs.getQName(i));
vinciAttrs.fadd(attrName, mCurrentFrameAttrs.getValue(i));
}
}
// put new frame on stack
mOpenFrames.push(frame);
}
// now store the information for the new element
String elemName = getName(localName, qualifiedName);
mCurrentFrameName = elemName;
mCurrentFrameAttrs = attributes;
}
/**
* Characters.
*
* @param ch
* the ch
* @param start
* the start
* @param length
* the length
* @see org.xml.sax.ContentHandler#characters(char[],int,int)
*/
@Override
public void characters(char[] ch, int start, int length) {
mCharContentBuffer.append(ch, start, length);
}
/**
* End element.
*
* @param namespaceURI
* the namespace URI
* @param localName
* the local name
* @param qualifiedName
* the qualified name
* @see org.xml.sax.ContentHandler#endElement(String,String,String)
*/
@Override
public void endElement(String namespaceURI, String localName, String qualifiedName) {
// if we're ending a leaf frame (which we know because mCurrentFrame is
// non-null), we must create the appropriate FrameLeaf object and add
// it to the top frame on the stack.
if (mCurrentFrameName != null) {
// the getLeafContent method just returns the contents of the
// mCharContentBuffer, but exists so subclasses can override for
// specialized behavior (such as supressing certain content).
String leafContent = getLeafContent(mCurrentFrameName, mCurrentFrameAttrs,
mCharContentBuffer);
// add leaf to parent frame
AFrame parent = (AFrame) mOpenFrames.peek();
org.apache.vinci.transport.Attributes vinciAttrs = parent.aadd(mCurrentFrameName,
leafContent);
// set attributes
if (mCurrentFrameAttrs != null) {
for (int i = 0; i < mCurrentFrameAttrs.getLength(); i++) {
String attrName = getName(mCurrentFrameAttrs.getLocalName(i),
mCurrentFrameAttrs.getQName(i));
vinciAttrs.fadd(attrName, mCurrentFrameAttrs.getValue(i));
}
}
mCurrentFrameName = null;
mCurrentFrameAttrs = null;
mCharContentBuffer = new StringBuffer();
} else {
// ending a non-leaf frame; pop the stack
mOpenFrames.pop();
}
}
/**
* Gets the content to be included in a FrameLeaf. This method just returns the contents of the
* provided StringBuffer, but subclasses can override to provide specialized content.
*
* @param aFrameName
* name of the FrameLeaf
* @param aAttributes
* attributes of FrameLeaf
* @param aContentBuf
* StringBuffer containing the character data obtained from the SAX parser
*
* @return the data to be included in the Vinci FrameLeaf
*/
protected String getLeafContent(String aFrameName, Attributes aAttributes,
StringBuffer aContentBuf) {
return aContentBuf.toString();
}
/**
* If the first String parameter is nonempty, return it, else return the second string parameter.
*
* @param s1
* The string to be tested.
* @param s2
* The alternate String.
* @return s1 if it isn't empty, else s2.
*/
protected String getName(String s1, String s2) {
if (s1 == null || "".equals(s1))
return s2;
else
return s1;
}
}
| |
package org.testng;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.AnnotationTypeEnum;
import org.testng.internal.ClassHelper;
import org.testng.internal.Utils;
import org.testng.internal.version.VersionInfo;
import org.testng.log4testng.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* TestNG/RemoteTestNG command line arguments parser.
*
* @author Cedric Beust
* @author <a href = "mailto:the_mindstorm@evolva.ro">Alexandru Popescu</a>
*/
public final class TestNGCommandLineArgs {
/** This class's log4testng Logger. */
private static final Logger LOGGER = Logger.getLogger(TestNGCommandLineArgs.class);
public static final String SHOW_TESTNG_STACK_FRAMES = "testng.show.stack.frames";
public static final String TEST_CLASSPATH = "testng.test.classpath";
// These next two are used by the Eclipse plug-in
public static final String PORT_COMMAND_OPT = "-port";
public static final String HOST_COMMAND_OPT = "-host";
/** The logging level option. */
public static final String LOG = "-log";
/** @deprecated replaced by DEFAULT_ANNOTATIONS_COMMAND_OPT. */
public static final String TARGET_COMMAND_OPT = "-target";
/** The default annotations option (useful in TestNG 15 only). */
public static final String ANNOTATIONS_COMMAND_OPT = "-annotations";
/** The test report output directory option. */
public static final String OUTDIR_COMMAND_OPT = "-d";
public static final String EXCLUDED_GROUPS_COMMAND_OPT = "-excludegroups";
public static final String GROUPS_COMMAND_OPT = "-groups";
public static final String JUNIT_DEF_OPT = "-junit";
public static final String LISTENER_COMMAND_OPT = "-listener";
public static final String MASTER_OPT = "-master";
public static final String OBJECT_FACTORY_COMMAND_OPT = "-objectfactory";
/**
* Used to pass a reporter configuration in the form
* <code>-reporter <reporter_name_or_class>:option=value[,option=value]</code>
*/
public static final String REPORTER = "-reporter";
/**
* Used as map key for the complete list of report listeners provided with the above argument
*/
public static final String REPORTERS_LIST = "-reporterslist";
public static final String PARALLEL_MODE = "-parallel";
public static final String SKIP_FAILED_INVOCATION_COUNT_OPT = "-skipfailedinvocationcounts";
public static final String SLAVE_OPT = "-slave";
/** The source directory option (when using JavaDoc type annotations). */
public static final String SRC_COMMAND_OPT = "-sourcedir";
public static final String SUITE_NAME_OPT = "-suitename";
/** The list of test classes option. */
public static final String TESTCLASS_COMMAND_OPT = "-testclass";
public static final String TESTJAR_COMMAND_OPT = "-testjar";
public static final String TEST_NAME_OPT = "-testname";
public static final String TESTRUNNER_FACTORY_COMMAND_OPT = "-testrunfactory";
public static final String THREAD_COUNT = "-threadcount";
public static final String DATA_PROVIDER_THREAD_COUNT = "-dataproviderthreadcount";
public static final String USE_DEFAULT_LISTENERS = "-usedefaultlisteners";
public static final String SUITE_DEF_OPT = "testng.suite.definitions";
/**
* When given a file name to form a class name, the file name is parsed and divided
* into segments. For example, "c:/java/classes/com/foo/A.class" would be divided
* into 6 segments {"C:" "java", "classes", "com", "foo", "A"}. The first segment
* actually making up the class name is [3]. This value is saved in m_lastGoodRootIndex
* so that when we parse the next file name, we will try 3 right away. If 3 fails we
* will take the long approach. This is just a optimization cache value.
*/
private static int m_lastGoodRootIndex = -1;
/**
* Hide the constructor for utility class.
*/
private TestNGCommandLineArgs() {
// Hide constructor for utility class
}
/**
* Parses the command line options and returns a map from option string to parsed values.
* For example, if argv contains {..., "-sourcedir", "src/main", "-target", ...} then
* the map would contain an entry in which the key would be the "-sourcedir" String and
* the value would be the "src/main" String.
*
* @param originalArgv the command line options.
* @return the parsed parameters as a map from option string to parsed values.
*/
public static Map parseCommandLine(final String[] originalArgv) {
for (int i = 0; i < originalArgv.length; ++i) {
LOGGER.debug("originalArgv[" + i + "] = \"" + originalArgv[i] + "\"");
}
// TODO CQ In this method, is this OK to simply ignore invalid parameters?
LOGGER.debug("TestNG version: \"" + (VersionInfo.IS_JDK14 ? "14" : "15") + "\"");
Map<String, Object> arguments = Maps.newHashMap();
String[] argv = expandArgv(originalArgv);
for (int i = 0; i < argv.length; i++) {
if (OUTDIR_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(OUTDIR_COMMAND_OPT, argv[i + 1].trim());
}
else {
LOGGER.error("WARNING: missing output directory after -d. ignored");
}
i++;
}
else if (GROUPS_COMMAND_OPT.equalsIgnoreCase(argv[i])
|| EXCLUDED_GROUPS_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
String option = null;
if (argv[i + 1].startsWith("\"")) {
if (argv[i + 1].endsWith("\"")) {
option = argv[i + 1].substring(1, argv[i + 1].length() - 1);
}
else {
LOGGER.error("WARNING: groups option is not well quoted:" + argv[i + 1]);
option = argv[i + 1].substring(1);
}
}
else {
option = argv[i + 1];
}
String opt = GROUPS_COMMAND_OPT.equalsIgnoreCase(argv[i])
? GROUPS_COMMAND_OPT : EXCLUDED_GROUPS_COMMAND_OPT;
arguments.put(opt, option);
}
else {
LOGGER.error("WARNING: missing groups parameter after -groups. ignored");
}
i++;
}
else if (LOG.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(LOG, Integer.valueOf(argv[i + 1].trim()));
}
else {
LOGGER.error("WARNING: missing log level after -log. ignored");
}
i++;
}
else if (JUNIT_DEF_OPT.equalsIgnoreCase(argv[i])) {
arguments.put(JUNIT_DEF_OPT, Boolean.TRUE);
}
else if (TARGET_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(ANNOTATIONS_COMMAND_OPT, AnnotationTypeEnum.valueOf(argv[i + 1]));
LOGGER.warn("The usage of " + TARGET_COMMAND_OPT + " has been deprecated. Please use " + ANNOTATIONS_COMMAND_OPT + " instead.");
++i;
}
}
else if (ANNOTATIONS_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(ANNOTATIONS_COMMAND_OPT, AnnotationTypeEnum.valueOf(argv[i + 1]));
++i;
}
}
else if (TESTRUNNER_FACTORY_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(TESTRUNNER_FACTORY_COMMAND_OPT, fileToClass(argv[++i]));
}
else {
LOGGER.error("WARNING: missing ITestRunnerFactory class or file argument after "
+ TESTRUNNER_FACTORY_COMMAND_OPT);
}
}
else if (OBJECT_FACTORY_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
Class<?> cls = fileToClass(argv[++i]);
arguments.put(OBJECT_FACTORY_COMMAND_OPT, cls);
}
else {
LOGGER.error("WARNING: missing IObjectFactory class/file list argument after "
+ OBJECT_FACTORY_COMMAND_OPT);
}
}
else if (LISTENER_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
String strClass = argv[++i];
String sep = ";";
if (strClass.indexOf(",") >= 0) {
sep = ",";
}
String[] strs = Utils.split(strClass, sep);
List<Class<?>> classes = Lists.newArrayList();
for (String cls : strs) {
classes.add(fileToClass(cls));
}
arguments.put(LISTENER_COMMAND_OPT, classes);
}
else {
LOGGER.error("WARNING: missing ITestListener class/file list argument after "
+ LISTENER_COMMAND_OPT);
}
}
else if (TESTCLASS_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
while ((i + 1) < argv.length) {
String nextArg = argv[i + 1].trim();
if (!nextArg.toLowerCase().endsWith(".xml") && !nextArg.startsWith("-")) {
// Assume it's a class name
List<Class<?>> l = (List<Class<?>>) arguments.get(TESTCLASS_COMMAND_OPT);
if (null == l) {
l = Lists.newArrayList();
arguments.put(TESTCLASS_COMMAND_OPT, l);
}
Class<?> cls = fileToClass(nextArg);
if (null != cls) {
l.add(cls);
}
i++;
} // if
else {
break;
}
}
}
else {
TestNG.exitWithError("-testclass must be followed by a classname");
}
}
else if (TESTJAR_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(TESTJAR_COMMAND_OPT, argv[i + 1].trim());
}
else {
TestNG.exitWithError("-testjar must be followed by a valid jar");
}
i++;
}
else if (SRC_COMMAND_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(SRC_COMMAND_OPT, argv[i + 1].trim());
}
else {
TestNG.exitWithError(SRC_COMMAND_OPT + " must be followed by a directory path");
}
i++;
}
else if (HOST_COMMAND_OPT.equals(argv[i])) {
String hostAddress = "127.0.0.1";
if ((i + 1) < argv.length) {
hostAddress = argv[i + 1].trim();
i++;
}
else {
LOGGER.warn("WARNING: "
+ HOST_COMMAND_OPT
+ " option should be followed by the host address. "
+ "Using default localhost.");
}
arguments.put(HOST_COMMAND_OPT, hostAddress);
}
else if (PORT_COMMAND_OPT.equals(argv[i])) {
String portNumber = null;
if ((i + 1) < argv.length) {
portNumber = argv[i + 1].trim();
}
else {
TestNG.exitWithError(
PORT_COMMAND_OPT + " option should be followed by a valid port number.");
}
arguments.put(PORT_COMMAND_OPT, portNumber);
i++;
}
else if (SLAVE_OPT.equals(argv[i])) {
String propertiesFile = null;
if ((i + 1) < argv.length) {
propertiesFile = argv[i + 1].trim();
}
else {
TestNG.exitWithError(SLAVE_OPT + " option should be followed by a valid file path.");
}
arguments.put(SLAVE_OPT, propertiesFile);
i++;
}
else if (MASTER_OPT.equals(argv[i])) {
String propertiesFile = null;
if ((i + 1) < argv.length) {
propertiesFile = argv[i + 1].trim();
}
else {
TestNG.exitWithError(MASTER_OPT + " option should be followed by a valid file path.");
}
arguments.put(MASTER_OPT, propertiesFile);
i++;
}
else if (PARALLEL_MODE.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(PARALLEL_MODE, argv[i + 1]);
i++;
}
}
else if (THREAD_COUNT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(THREAD_COUNT, argv[i + 1]);
i++;
}
}
else if (DATA_PROVIDER_THREAD_COUNT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(DATA_PROVIDER_THREAD_COUNT, argv[i + 1]);
i++;
}
}
else if (USE_DEFAULT_LISTENERS.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(USE_DEFAULT_LISTENERS, argv[i + 1]);
i++;
}
}
else if (SUITE_NAME_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(SUITE_NAME_OPT, trim(argv[i + 1]));
i++;
}
}
else if (TEST_NAME_OPT.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
arguments.put(TEST_NAME_OPT, trim(argv[i + 1]));
i++;
}
}
else if (REPORTER.equalsIgnoreCase(argv[i])) {
if ((i + 1) < argv.length) {
ReporterConfig reporterConfig = ReporterConfig.deserialize(trim(argv[i + 1]));
if (arguments.get(REPORTERS_LIST) == null) {
arguments.put(REPORTERS_LIST, Lists.newArrayList());
}
((List<ReporterConfig>)arguments.get(REPORTERS_LIST)).add(reporterConfig);
i++;
}
}
else if (SKIP_FAILED_INVOCATION_COUNT_OPT.equalsIgnoreCase(argv[i])) {
arguments.put(SKIP_FAILED_INVOCATION_COUNT_OPT, Boolean.TRUE);
}
//
// Unknown option
//
else if (argv[i].startsWith("-")) {
TestNG.exitWithError("Unknown option: " + argv[i]);
}
//
// The XML files
//
// Read parameters just once, to get all xml files
else if( arguments.get(SUITE_DEF_OPT) == null ){
List<String> suiteDefs = Lists.newArrayList();
// Iterates over all declared XML file params
for (int k = i; k < argv.length; k++) {
String file = argv[k].trim();
if (file.toLowerCase().endsWith(".xml")) {
suiteDefs.add(file);
}
}
arguments.put(SUITE_DEF_OPT, suiteDefs);
}
}
for (Map.Entry entry : arguments.entrySet()) {
LOGGER.debug("parseCommandLine argument: \""
+ entry.getKey() + "\" = \"" + entry.getValue() + "\"");
}
return arguments;
}
/**
* @param string
* @return
*/
private static String trim(String string) {
String trimSpaces=string.trim();
if (trimSpaces.startsWith("\"")) {
if (trimSpaces.endsWith("\"")) {
return trimSpaces.substring(1, trimSpaces.length() - 1);
} else {
return trimSpaces.substring(1);
}
} else {
return trimSpaces;
}
}
/**
* Expand the command line parameters to take @ parameters into account.
* When @ is encountered, the content of the file that follows is inserted
* in the command line
* @param originalArgv the original command line parameters
* @return the new and enriched command line parameters
*/
private static String[] expandArgv(String[] originalArgv) {
List<String> vResult = Lists.newArrayList();
for (String arg : originalArgv) {
if (arg.startsWith("@")) {
String fileName = arg.substring(1);
vResult.addAll(readFile(fileName));
}
else {
vResult.add(arg);
}
}
return vResult.toArray(new String[vResult.size()]);
}
// /**
// * Break a line of parameters into individual parameters as the command line parsing
// * would do. The line is assumed to contain only un-escaped double quotes. For example
// * the following Java string:
// * " a \"command\"\"line\" \"with quotes\" a command line\" with quotes \"here there"
// * would yield the following 7 tokens:
// * a,commandline,with quotes,a,command,line with quotes here,there
// * @param line the command line parameter to be parsed
// * @return the list of individual command line tokens
// */
// private static List<String> parseArgs(String line) {
// LOGGER.debug("parseArgs line: \"" + line + "\"");
// final String SPACE = " ";
// final String DOUBLE_QUOTE = "\"";
//
// // If line contains no double quotes, the space character is the only
// // separator. Easy to do return quickly (logic is also easier to follow)
// if (line.indexOf(DOUBLE_QUOTE) == -1) {
// List<String> results = Arrays.asList(line.split(SPACE));
// for (String result : results) {
// LOGGER.debug("parseArgs result: \"" + result + "\"");
// }
// return results;
// }
//
// // TODO There must be an easier way to do this with a regular expression.
//
// StringTokenizer st = new StringTokenizer(line, SPACE + DOUBLE_QUOTE, true);
// List<String> results = Lists.newArrayList();
//
// /*
// * isInDoubleQuote toggles from false to true when we reach a double
// * quoted string and toggles back to false when we exit. We need to
// * know if we are in a double quoted string to treat blanks as normal
// * characters. Out of quotes blanks separate arguments.
// *
// * The following example shows these toggle points:
// *
// * " a \"command\"\"line\" \"with quotes\" a command line\" with quotes \"here there"
// * T F T F T F T F
// *
// * If the double quotes are not evenly matched, an exception is thrown.
// */
// boolean isInDoubleQuote = false;
//
// /*
// * isInArg toggles from false to true when we enter a command line argument
// * and toggles back to false when we exit. The logic is that we toggle to
// * true at the first non-whitespace character met. We toggle back to false
// * at first whitespace character not in double quotes or at end of line.
// *
// * The following example shows these toggle points:
// *
// * " a \"command\"\"line\" \"with quotes\" a command line\" with quotes \"here there"
// * TF T F T F TFT FT F
// */
// boolean isInArg = false;
//
// /* arg is a string buffer to create the argument by concatenating all tokens
// * that compose it.
// *
// * The following example shows the token returned by the parser and the
// * (spaces, double quotes, others) and resultant argument:
// *
// * Input (argument):
// * "line\" with quotes \"here"
// *
// * Tokens (9):
// * line,", ,with, ,quote, ,",here
// */
// StringBuffer arg = new StringBuffer();
//
// while (st.hasMoreTokens()) {
// String token = st.nextToken();
//
// if (token.equals(SPACE)) {
// if (isInArg) {
// if (isInDoubleQuote) {
// // Spaces within double quotes are treated as normal spaces
// arg.append(SPACE);
// }
// else {
// // First spaces outside double quotes marks the end of the argument.
// isInArg = false;
// results.add(arg.toString());
// arg = new StringBuffer();
// }
// }
// }
// else if (token.equals(DOUBLE_QUOTE)) {
// // If we encounter a double quote, we may be entering a new argument
// // (isInArg is false) or continuing the current argument (isInArg is true).
// isInArg = true;
// isInDoubleQuote = !isInDoubleQuote;
// }
// else {
// // We we encounter a new token, we may be entering a new argument
// // (isInArg is false) or continuing the current argument (isInArg is true).
// isInArg = true;
// arg.append(token);
// }
// }
//
// // In some (most) cases we exit this parsing because there are no tokens left
// // but we have not encountered a token to indicate that the last argument has
// // completely been read. For example, if the command line ends with a whitespace
// // the isInArg will toggle to false and the argument will be completely read.
// if (isInArg) {
// // End of last argument
// results.add(arg.toString());
// }
//
// // If we exit the parsing of the command line with an uneven number of double
// // quotes, throw an exception.
// if (isInDoubleQuote) {
// throw new IllegalArgumentException("Unbalanced double quotes: \"" + line + "\"");
// }
//
// for (String result : results) {
// LOGGER.debug("parseArgs result: \"" + result + "\"");
// }
//
// return results;
// }
/**
* Reads the file specified by filename and returns the file content as a string.
* End of lines are replaced by a space
*
* @param fileName the command line filename
* @return the file content as a string.
*/
public static List<String> readFile(String fileName) {
List<String> result = Lists.newArrayList();
try {
BufferedReader bufRead = new BufferedReader(new FileReader(fileName));
String line;
// Read through file one line at time. Print line # and line
while ((line = bufRead.readLine()) != null) {
result.add(line);
}
bufRead.close();
}
catch (IOException e) {
LOGGER.error("IO exception reading command line file", e);
}
return result;
}
/**
* Returns the Class object corresponding to the given name. The name may be
* of the following form:
* <ul>
* <li>A class name: "org.testng.TestNG"</li>
* <li>A class file name: "/testng/src/org/testng/TestNG.class"</li>
* <li>A class source name: "d:\testng\src\org\testng\TestNG.java"</li>
* </ul>
*
* @param file
* the class name.
* @return the class corresponding to the name specified.
*/
private static Class<?> fileToClass(String file) {
Class<?> result = null;
if(!file.endsWith(".class") && !file.endsWith(".java")) {
// Doesn't end in .java or .class, assume it's a class name
result = ClassHelper.forName(file);
if (null == result) {
throw new TestNGException("Cannot load class from file: " + file);
}
return result;
}
int classIndex = file.lastIndexOf(".class");
if (-1 == classIndex) {
classIndex = file.lastIndexOf(".java");
//
// if(-1 == classIndex) {
// result = ClassHelper.forName(file);
//
// if (null == result) {
// throw new TestNGException("Cannot load class from file: " + file);
// }
//
// return result;
// }
//
}
// Transforms the file name into a class name.
// Remove the ".class" or ".java" extension.
String shortFileName = file.substring(0, classIndex);
// Split file name into segments. For example "c:/java/classes/com/foo/A"
// becomes {"c:", "java", "classes", "com", "foo", "A"}
String[] segments = shortFileName.split("[/\\\\]", -1);
//
// Check if the last good root index works for this one. For example, if the previous
// name was "c:/java/classes/com/foo/A.class" then m_lastGoodRootIndex is 3 and we
// try to make a class name ignoring the first m_lastGoodRootIndex segments (3). This
// will succeed rapidly if the path is the same as the one from the previous name.
//
if (-1 != m_lastGoodRootIndex) {
// TODO use a SringBuffer here
String className = segments[m_lastGoodRootIndex];
for (int i = m_lastGoodRootIndex + 1; i < segments.length; i++) {
className += "." + segments[i];
}
result = ClassHelper.forName(className);
if (null != result) {
return result;
}
}
//
// We haven't found a good root yet, start by resolving the class from the end segment
// and work our way up. For example, if we start with "c:/java/classes/com/foo/A"
// we'll start by resolving "A", then "foo.A", then "com.foo.A" until something
// resolves. When it does, we remember the path we are at as "lastGoodRoodIndex".
//
// TODO CQ use a StringBuffer here
String className = null;
for (int i = segments.length - 1; i >= 0; i--) {
if (null == className) {
className = segments[i];
}
else {
className = segments[i] + "." + className;
}
result = ClassHelper.forName(className);
if (null != result) {
m_lastGoodRootIndex = i;
break;
}
}
if (null == result) {
throw new TestNGException("Cannot load class from file: " + file);
}
return result;
}
// private static void ppp(Object msg) {
// System.out.println("[CMD]: " + msg);
// }
/**
* Prints the usage message to System.out. This message describes all the command line
* options.
*/
public static void usage() {
System.out.println("Usage:");
System.out.println("[" + OUTDIR_COMMAND_OPT + " output-directory]");
System.out.println("\t\tdefault output directory to : " + TestNG.DEFAULT_OUTPUTDIR);
System.out.println("[" + TESTCLASS_COMMAND_OPT
+ " list of .class files or list of class names]");
System.out.println("[" + SRC_COMMAND_OPT + " a source directory]");
if (VersionInfo.IS_JDK14) {
System.out.println("[" + ANNOTATIONS_COMMAND_OPT + " " + AnnotationTypeEnum.JAVADOC.getName() + "]");
System.out.println("\t\tSpecifies the default annotation type to be used in suites when none is explicitly specified.");
System.out.println("\t\tThis version of TestNG (14) only supports " + AnnotationTypeEnum.JAVADOC.getName() + " annotation type.");
System.out.println("\t\tFor interface compatibility reasons, we allow this value to be explicitly set to " +
AnnotationTypeEnum.JAVADOC.getName() + "\" ");
}
else {
System.out.println("[" + ANNOTATIONS_COMMAND_OPT + " " + AnnotationTypeEnum.JAVADOC.getName() + " or "
+ AnnotationTypeEnum.JDK.getName() + "]");
System.out.println("\t\tSpecifies the default annotation type to be used in suites when none is explicitly");
System.out.println("\t\tspecified. This version of TestNG (15) supports both \""
+ AnnotationTypeEnum.JAVADOC.getName() + "\" and \"" + AnnotationTypeEnum.JDK.getName() + "\" annotation types.");
}
System.out.println("[" + GROUPS_COMMAND_OPT + " comma-separated list of group names to be run]");
System.out.println("\t\tworks only with " + TESTCLASS_COMMAND_OPT);
System.out.println("[" + EXCLUDED_GROUPS_COMMAND_OPT
+ " comma-separated list of group names to be excluded]");
System.out.println("\t\tworks only with " + TESTCLASS_COMMAND_OPT);
System.out.println("[" + TESTRUNNER_FACTORY_COMMAND_OPT
+ " list of .class files or list of class names implementing "
+ ITestRunnerFactory.class.getName()
+ "]");
System.out.println("[" + LISTENER_COMMAND_OPT
+ " list of .class files or list of class names implementing "
+ ITestListener.class.getName()
+ " and/or "
+ ISuiteListener.class.getName()
+ "]");
System.out.println("[" + PARALLEL_MODE
+ " methods|tests]");
System.out.println("\t\trun tests in parallel using the specified mode");
System.out.println("[" + THREAD_COUNT
+ " number of threads to use when running tests in parallel]");
System.out.println("[" + SUITE_NAME_OPT + " name]");
System.out.println("\t\tDefault name of test suite, if not specified in suite definition file or source code");
System.out.println("[" + TEST_NAME_OPT + " Name]");
System.out.println("\t\tDefault name of test, if not specified in suite definition file or source code");
System.out.println("[" + REPORTER + " Extended configuration for custom report listener]");
System.out.println("[suite definition files*]");
System.out.println("");
System.out.println("For details, please consult the documentation at http://testng.org.");
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.vector.expressions;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.hive.common.type.DataTypePhysicalVariation;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator;
import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluatorFactory;
import org.apache.hadoop.hive.ql.exec.FunctionInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorExtractRow;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomBatchSource;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource;
import org.apache.hadoop.hive.ql.exec.vector.VectorizationContext;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx;
import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.GenerationSpec;
import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression;
import org.apache.hadoop.hive.ql.exec.vector.udf.VectorUDFAdaptor;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFDateAdd;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFDateDiff;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFDateSub;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPGreaterThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPLessThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqualOrGreaterThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqualOrLessThan;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNotEqual;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
import org.apache.hadoop.io.BooleanWritable;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
public class TestVectorFilterCompare {
public TestVectorFilterCompare() {
// Arithmetic operations rely on getting conf from SessionState, need to initialize here.
SessionState ss = new SessionState(new HiveConf());
ss.getConf().setVar(HiveConf.ConfVars.HIVE_COMPAT, "latest");
SessionState.setCurrentSessionState(ss);
}
@Test
public void testIntegers() throws Exception {
Random random = new Random(7743);
doIntegerTests(random);
}
@Test
public void testIntegerFloating() throws Exception {
Random random = new Random(7743);
doIntegerFloatingTests(random);
}
@Test
public void testFloating() throws Exception {
Random random = new Random(7743);
doFloatingTests(random);
}
@Test
public void testDecimal() throws Exception {
Random random = new Random(7743);
doDecimalTests(random, /* tryDecimal64 */ false);
}
@Test
public void testDecimal64() throws Exception {
Random random = new Random(7743);
doDecimalTests(random, /* tryDecimal64 */ true);
}
@Test
public void testTimestamp() throws Exception {
Random random = new Random(7743);
doTests(random, TypeInfoFactory.timestampTypeInfo, TypeInfoFactory.timestampTypeInfo);
doTests(random, TypeInfoFactory.timestampTypeInfo, TypeInfoFactory.longTypeInfo);
doTests(random, TypeInfoFactory.timestampTypeInfo, TypeInfoFactory.doubleTypeInfo);
doTests(random, TypeInfoFactory.longTypeInfo, TypeInfoFactory.timestampTypeInfo);
doTests(random, TypeInfoFactory.doubleTypeInfo, TypeInfoFactory.timestampTypeInfo);
}
@Test
public void testDate() throws Exception {
Random random = new Random(7743);
doTests(random, TypeInfoFactory.dateTypeInfo, TypeInfoFactory.dateTypeInfo);
}
@Test
public void testInterval() throws Exception {
Random random = new Random(7743);
doTests(random, TypeInfoFactory.intervalYearMonthTypeInfo, TypeInfoFactory.intervalYearMonthTypeInfo);
doTests(random, TypeInfoFactory.intervalDayTimeTypeInfo, TypeInfoFactory.intervalDayTimeTypeInfo);
}
@Test
public void testStringFamily() throws Exception {
Random random = new Random(7743);
doTests(random, TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo);
doTests(random, new CharTypeInfo(10), new CharTypeInfo(10));
doTests(random, new VarcharTypeInfo(10), new VarcharTypeInfo(10));
}
public enum FilterCompareTestMode {
ROW_MODE,
ADAPTOR,
FILTER_VECTOR_EXPRESSION,
COMPARE_VECTOR_EXPRESSION;
static final int count = values().length;
}
public enum ColumnScalarMode {
COLUMN_COLUMN,
COLUMN_SCALAR,
SCALAR_COLUMN;
static final int count = values().length;
}
private static TypeInfo[] integerTypeInfos = new TypeInfo[] {
TypeInfoFactory.byteTypeInfo,
TypeInfoFactory.shortTypeInfo,
TypeInfoFactory.intTypeInfo,
TypeInfoFactory.longTypeInfo
};
// We have test failures with FLOAT. Ignoring this issue for now.
private static TypeInfo[] floatingTypeInfos = new TypeInfo[] {
// TypeInfoFactory.floatTypeInfo,
TypeInfoFactory.doubleTypeInfo
};
private void doIntegerTests(Random random)
throws Exception {
for (TypeInfo typeInfo : integerTypeInfos) {
doTests(random, typeInfo, typeInfo);
}
}
private void doIntegerFloatingTests(Random random)
throws Exception {
for (TypeInfo typeInfo1 : integerTypeInfos) {
for (TypeInfo typeInfo2 : floatingTypeInfos) {
doTests(random, typeInfo1, typeInfo2);
}
}
for (TypeInfo typeInfo1 : floatingTypeInfos) {
for (TypeInfo typeInfo2 : integerTypeInfos) {
doTests(random, typeInfo1, typeInfo2);
}
}
}
private void doFloatingTests(Random random)
throws Exception {
for (TypeInfo typeInfo1 : floatingTypeInfos) {
for (TypeInfo typeInfo2 : floatingTypeInfos) {
doTests(random, typeInfo1, typeInfo2);
}
}
}
private static TypeInfo[] decimalTypeInfos = new TypeInfo[] {
new DecimalTypeInfo(38, 18),
new DecimalTypeInfo(25, 2),
new DecimalTypeInfo(19, 4),
new DecimalTypeInfo(18, 10),
new DecimalTypeInfo(17, 3),
new DecimalTypeInfo(12, 2),
new DecimalTypeInfo(7, 1)
};
private void doDecimalTests(Random random, boolean tryDecimal64)
throws Exception {
for (TypeInfo typeInfo : decimalTypeInfos) {
doTests(random, typeInfo, typeInfo, tryDecimal64);
}
}
private TypeInfo getOutputTypeInfo(GenericUDF genericUdfClone,
List<ObjectInspector> objectInspectorList)
throws HiveException {
ObjectInspector[] array =
objectInspectorList.toArray(new ObjectInspector[objectInspectorList.size()]);
ObjectInspector outputObjectInspector = genericUdfClone.initialize(array);
return TypeInfoUtils.getTypeInfoFromObjectInspector(outputObjectInspector);
}
public enum Comparison {
EQUALS,
LESS_THAN,
LESS_THAN_EQUAL,
GREATER_THAN,
GREATER_THAN_EQUAL,
NOT_EQUALS;
}
private TypeInfo getDecimalScalarTypeInfo(Object scalarObject) {
HiveDecimal dec = (HiveDecimal) scalarObject;
int precision = dec.precision();
int scale = dec.scale();
return new DecimalTypeInfo(precision, scale);
}
private boolean checkDecimal64(boolean tryDecimal64, TypeInfo typeInfo) {
if (!tryDecimal64 || !(typeInfo instanceof DecimalTypeInfo)) {
return false;
}
DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
boolean result = HiveDecimalWritable.isPrecisionDecimal64(decimalTypeInfo.getPrecision());
return result;
}
private void doTests(Random random, TypeInfo typeInfo1, TypeInfo typeInfo2, boolean tryDecimal64)
throws Exception {
for (ColumnScalarMode columnScalarMode : ColumnScalarMode.values()) {
doTestsWithDiffColumnScalar(
random, typeInfo1, typeInfo2, columnScalarMode, tryDecimal64);
}
}
private void doTests(Random random, TypeInfo typeInfo1, TypeInfo typeInfo2)
throws Exception {
for (ColumnScalarMode columnScalarMode : ColumnScalarMode.values()) {
doTestsWithDiffColumnScalar(
random, typeInfo1, typeInfo2, columnScalarMode);
}
}
private void doTestsWithDiffColumnScalar(Random random, TypeInfo typeInfo1, TypeInfo typeInfo2,
ColumnScalarMode columnScalarMode)
throws Exception {
doTestsWithDiffColumnScalar(random, typeInfo1, typeInfo2, columnScalarMode, false);
}
private void doTestsWithDiffColumnScalar(Random random, TypeInfo typeInfo1, TypeInfo typeInfo2,
ColumnScalarMode columnScalarMode, boolean tryDecimal64)
throws Exception {
for (Comparison comparison : Comparison.values()) {
doTestsWithDiffColumnScalar(
random, typeInfo1, typeInfo2, columnScalarMode, comparison, tryDecimal64);
}
}
private void doTestsWithDiffColumnScalar(Random random, TypeInfo typeInfo1, TypeInfo typeInfo2,
ColumnScalarMode columnScalarMode, Comparison comparison, boolean tryDecimal64)
throws Exception {
String typeName1 = typeInfo1.getTypeName();
PrimitiveCategory primitiveCategory1 =
((PrimitiveTypeInfo) typeInfo1).getPrimitiveCategory();
String typeName2 = typeInfo2.getTypeName();
PrimitiveCategory primitiveCategory2 =
((PrimitiveTypeInfo) typeInfo2).getPrimitiveCategory();
List<GenerationSpec> generationSpecList = new ArrayList<GenerationSpec>();
List<DataTypePhysicalVariation> explicitDataTypePhysicalVariationList =
new ArrayList<DataTypePhysicalVariation>();
List<String> columns = new ArrayList<String>();
int columnNum = 1;
ExprNodeDesc col1Expr;
Object scalar1Object = null;
final boolean decimal64Enable1 = checkDecimal64(tryDecimal64, typeInfo1);
if (columnScalarMode == ColumnScalarMode.COLUMN_COLUMN ||
columnScalarMode == ColumnScalarMode.COLUMN_SCALAR) {
generationSpecList.add(
GenerationSpec.createSameType(typeInfo1));
explicitDataTypePhysicalVariationList.add(
decimal64Enable1 ?
DataTypePhysicalVariation.DECIMAL_64 :
DataTypePhysicalVariation.NONE);
String columnName = "col" + (columnNum++);
col1Expr = new ExprNodeColumnDesc(typeInfo1, columnName, "table", false);
columns.add(columnName);
} else {
scalar1Object =
VectorRandomRowSource.randomPrimitiveObject(
random, (PrimitiveTypeInfo) typeInfo1);
// Adjust the decimal type to the scalar's type...
if (typeInfo1 instanceof DecimalTypeInfo) {
typeInfo1 = getDecimalScalarTypeInfo(scalar1Object);
}
col1Expr = new ExprNodeConstantDesc(typeInfo1, scalar1Object);
}
ExprNodeDesc col2Expr;
Object scalar2Object = null;
final boolean decimal64Enable2 = checkDecimal64(tryDecimal64, typeInfo2);
if (columnScalarMode == ColumnScalarMode.COLUMN_COLUMN ||
columnScalarMode == ColumnScalarMode.SCALAR_COLUMN) {
generationSpecList.add(
GenerationSpec.createSameType(typeInfo2));
explicitDataTypePhysicalVariationList.add(
decimal64Enable2 ?
DataTypePhysicalVariation.DECIMAL_64 :
DataTypePhysicalVariation.NONE);
String columnName = "col" + (columnNum++);
col2Expr = new ExprNodeColumnDesc(typeInfo2, columnName, "table", false);
columns.add(columnName);
} else {
scalar2Object =
VectorRandomRowSource.randomPrimitiveObject(
random, (PrimitiveTypeInfo) typeInfo2);
// Adjust the decimal type to the scalar's type...
if (typeInfo2 instanceof DecimalTypeInfo) {
typeInfo2 = getDecimalScalarTypeInfo(scalar2Object);
}
col2Expr = new ExprNodeConstantDesc(typeInfo2, scalar2Object);
}
List<ObjectInspector> objectInspectorList = new ArrayList<ObjectInspector>();
objectInspectorList.add(VectorRandomRowSource.getObjectInspector(typeInfo1));
objectInspectorList.add(VectorRandomRowSource.getObjectInspector(typeInfo2));
List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>();
children.add(col1Expr);
children.add(col2Expr);
//----------------------------------------------------------------------------------------------
String[] columnNames = columns.toArray(new String[0]);
VectorRandomRowSource rowSource = new VectorRandomRowSource();
rowSource.initGenerationSpecSchema(
random, generationSpecList, /* maxComplexDepth */ 0,
/* allowNull */ true, /* isUnicodeOk */ true,
explicitDataTypePhysicalVariationList);
Object[][] randomRows = rowSource.randomRows(100000);
VectorRandomBatchSource batchSource =
VectorRandomBatchSource.createInterestingBatches(
random,
rowSource,
randomRows,
null);
GenericUDF genericUdf;
switch (comparison) {
case EQUALS:
genericUdf = new GenericUDFOPEqual();
break;
case LESS_THAN:
genericUdf = new GenericUDFOPLessThan();
break;
case LESS_THAN_EQUAL:
genericUdf = new GenericUDFOPEqualOrLessThan();
break;
case GREATER_THAN:
genericUdf = new GenericUDFOPGreaterThan();
break;
case GREATER_THAN_EQUAL:
genericUdf = new GenericUDFOPEqualOrGreaterThan();
break;
case NOT_EQUALS:
genericUdf = new GenericUDFOPNotEqual();
break;
default:
throw new RuntimeException("Unexpected arithmetic " + comparison);
}
ObjectInspector[] objectInspectors =
objectInspectorList.toArray(new ObjectInspector[objectInspectorList.size()]);
ObjectInspector outputObjectInspector = null;
try {
outputObjectInspector = genericUdf.initialize(objectInspectors);
} catch (Exception e) {
Assert.fail(e.toString());
}
TypeInfo outputTypeInfo = TypeInfoUtils.getTypeInfoFromObjectInspector(outputObjectInspector);
ExprNodeGenericFuncDesc exprDesc =
new ExprNodeGenericFuncDesc(outputTypeInfo, genericUdf, children);
final int rowCount = randomRows.length;
Object[][] resultObjectsArray = new Object[FilterCompareTestMode.count][];
for (int i = 0; i < FilterCompareTestMode.count; i++) {
Object[] resultObjects = new Object[rowCount];
resultObjectsArray[i] = resultObjects;
FilterCompareTestMode filterCompareTestMode = FilterCompareTestMode.values()[i];
switch (filterCompareTestMode) {
case ROW_MODE:
doRowFilterCompareTest(
typeInfo1,
typeInfo2,
columns,
children,
exprDesc,
comparison,
randomRows,
columnScalarMode,
rowSource.rowStructObjectInspector(),
outputTypeInfo,
resultObjects);
break;
case ADAPTOR:
case FILTER_VECTOR_EXPRESSION:
case COMPARE_VECTOR_EXPRESSION:
doVectorFilterCompareTest(
typeInfo1,
typeInfo2,
columns,
columnNames,
rowSource.typeInfos(),
rowSource.dataTypePhysicalVariations(),
children,
exprDesc,
comparison,
filterCompareTestMode,
columnScalarMode,
batchSource,
exprDesc.getWritableObjectInspector(),
outputTypeInfo,
resultObjects);
break;
default:
throw new RuntimeException("Unexpected IF statement test mode " + filterCompareTestMode);
}
}
for (int i = 0; i < rowCount; i++) {
// Row-mode is the expected value.
Object expectedResult = resultObjectsArray[0][i];
for (int v = 1; v < FilterCompareTestMode.count; v++) {
FilterCompareTestMode filterCompareTestMode = FilterCompareTestMode.values()[v];
Object vectorResult = resultObjectsArray[v][i];
if (filterCompareTestMode == FilterCompareTestMode.FILTER_VECTOR_EXPRESSION &&
expectedResult == null &&
vectorResult != null) {
// This is OK.
boolean vectorBoolean = ((BooleanWritable) vectorResult).get();
if (vectorBoolean) {
Assert.fail(
"Row " + i +
" typeName1 " + typeName1 +
" typeName2 " + typeName2 +
" outputTypeName " + outputTypeInfo.getTypeName() +
" " + comparison +
" " + filterCompareTestMode +
" " + columnScalarMode +
" result is NOT NULL and true" +
" does not match row-mode expected result is NULL which means false here" +
(columnScalarMode == ColumnScalarMode.SCALAR_COLUMN ?
" scalar1 " + scalar1Object.toString() : "") +
" row values " + Arrays.toString(randomRows[i]) +
(columnScalarMode == ColumnScalarMode.COLUMN_SCALAR ?
" scalar2 " + scalar2Object.toString() : ""));
}
} else if (expectedResult == null || vectorResult == null) {
if (expectedResult != null || vectorResult != null) {
Assert.fail(
"Row " + i +
" typeName1 " + typeName1 +
" typeName2 " + typeName2 +
" outputTypeName " + outputTypeInfo.getTypeName() +
" " + comparison +
" " + filterCompareTestMode +
" " + columnScalarMode +
" result is NULL " + (vectorResult == null) +
" does not match row-mode expected result is NULL " + (expectedResult == null) +
(columnScalarMode == ColumnScalarMode.SCALAR_COLUMN ?
" scalar1 " + scalar1Object.toString() : "") +
" row values " + Arrays.toString(randomRows[i]) +
(columnScalarMode == ColumnScalarMode.COLUMN_SCALAR ?
" scalar2 " + scalar2Object.toString() : ""));
}
} else {
if (!expectedResult.equals(vectorResult)) {
Assert.fail(
"Row " + i +
" typeName1 " + typeName1 +
" typeName2 " + typeName2 +
" outputTypeName " + outputTypeInfo.getTypeName() +
" " + comparison +
" " + filterCompareTestMode +
" " + columnScalarMode +
" result " + vectorResult.toString() +
" (" + vectorResult.getClass().getSimpleName() + ")" +
" does not match row-mode expected result " + expectedResult.toString() +
" (" + expectedResult.getClass().getSimpleName() + ")" +
(columnScalarMode == ColumnScalarMode.SCALAR_COLUMN ?
" scalar1 " + scalar1Object.toString() : "") +
" row values " + Arrays.toString(randomRows[i]) +
(columnScalarMode == ColumnScalarMode.COLUMN_SCALAR ?
" scalar2 " + scalar2Object.toString() : ""));
}
}
}
}
}
private void doRowFilterCompareTest(TypeInfo typeInfo1,
TypeInfo typeInfo2,
List<String> columns, List<ExprNodeDesc> children,
ExprNodeGenericFuncDesc exprDesc,
Comparison comparison,
Object[][] randomRows, ColumnScalarMode columnScalarMode,
ObjectInspector rowInspector,
TypeInfo outputTypeInfo, Object[] resultObjects) throws Exception {
/*
System.out.println(
"*DEBUG* typeInfo " + typeInfo1.toString() +
" typeInfo2 " + typeInfo2 +
" filterCompareTestMode ROW_MODE" +
" columnScalarMode " + columnScalarMode +
" exprDesc " + exprDesc.toString());
*/
HiveConf hiveConf = new HiveConf();
ExprNodeEvaluator evaluator =
ExprNodeEvaluatorFactory.get(exprDesc, hiveConf);
evaluator.initialize(rowInspector);
ObjectInspector objectInspector =
TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(
outputTypeInfo);
final int rowCount = randomRows.length;
for (int i = 0; i < rowCount; i++) {
Object[] row = randomRows[i];
Object result = evaluator.evaluate(row);
Object copyResult = null;
try {
copyResult =
ObjectInspectorUtils.copyToStandardObject(
result, objectInspector, ObjectInspectorCopyOption.WRITABLE);
} catch (Exception e) {
Assert.fail(e.toString());
}
resultObjects[i] = copyResult;
}
}
private void extractResultObjects(VectorizedRowBatch batch, int rowIndex,
VectorExtractRow resultVectorExtractRow, Object[] scrqtchRow,
ObjectInspector objectInspector, Object[] resultObjects) {
boolean selectedInUse = batch.selectedInUse;
int[] selected = batch.selected;
for (int logicalIndex = 0; logicalIndex < batch.size; logicalIndex++) {
final int batchIndex = (selectedInUse ? selected[logicalIndex] : logicalIndex);
resultVectorExtractRow.extractRow(batch, batchIndex, scrqtchRow);
Object copyResult =
ObjectInspectorUtils.copyToStandardObject(
scrqtchRow[0], objectInspector, ObjectInspectorCopyOption.WRITABLE);
resultObjects[rowIndex++] = copyResult;
}
}
private void doVectorFilterCompareTest(TypeInfo typeInfo1,
TypeInfo typeInfo2,
List<String> columns,
String[] columnNames,
TypeInfo[] typeInfos, DataTypePhysicalVariation[] dataTypePhysicalVariations,
List<ExprNodeDesc> children,
ExprNodeGenericFuncDesc exprDesc,
Comparison comparison,
FilterCompareTestMode filterCompareTestMode, ColumnScalarMode columnScalarMode,
VectorRandomBatchSource batchSource,
ObjectInspector objectInspector,
TypeInfo outputTypeInfo, Object[] resultObjects)
throws Exception {
HiveConf hiveConf = new HiveConf();
if (filterCompareTestMode == FilterCompareTestMode.ADAPTOR) {
hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_TEST_VECTOR_ADAPTOR_OVERRIDE, true);
// Don't use DECIMAL_64 with the VectorUDFAdaptor.
dataTypePhysicalVariations = null;
}
VectorizationContext vectorizationContext =
new VectorizationContext(
"name",
columns,
Arrays.asList(typeInfos),
dataTypePhysicalVariations == null ? null : Arrays.asList(dataTypePhysicalVariations),
hiveConf);
final VectorExpressionDescriptor.Mode mode;
switch (filterCompareTestMode) {
case ADAPTOR:
case COMPARE_VECTOR_EXPRESSION:
mode = VectorExpressionDescriptor.Mode.PROJECTION;
break;
case FILTER_VECTOR_EXPRESSION:
mode = VectorExpressionDescriptor.Mode.FILTER;
break;
default:
throw new RuntimeException("Unexpected filter compare mode " + filterCompareTestMode);
}
VectorExpression vectorExpression =
vectorizationContext.getVectorExpression(
exprDesc, mode);
vectorExpression.transientInit();
if (filterCompareTestMode == FilterCompareTestMode.COMPARE_VECTOR_EXPRESSION &&
vectorExpression instanceof VectorUDFAdaptor) {
System.out.println(
"*NO NATIVE VECTOR EXPRESSION* typeInfo1 " + typeInfo1.toString() +
" typeInfo2 " + typeInfo2.toString() +
" " + comparison + " " +
" filterCompareTestMode " + filterCompareTestMode +
" columnScalarMode " + columnScalarMode +
" vectorExpression " + vectorExpression.toString());
}
String[] outputScratchTypeNames= vectorizationContext.getScratchColumnTypeNames();
DataTypePhysicalVariation[] outputDataTypePhysicalVariations =
vectorizationContext.getScratchDataTypePhysicalVariations();
VectorizedRowBatchCtx batchContext =
new VectorizedRowBatchCtx(
columnNames,
typeInfos,
dataTypePhysicalVariations,
/* dataColumnNums */ null,
/* partitionColumnCount */ 0,
/* virtualColumnCount */ 0,
/* neededVirtualColumns */ null,
outputScratchTypeNames,
outputDataTypePhysicalVariations);
VectorizedRowBatch batch = batchContext.createVectorizedRowBatch();
VectorExtractRow resultVectorExtractRow = new VectorExtractRow();
final int outputColumnNum = vectorExpression.getOutputColumnNum();
resultVectorExtractRow.init(
new TypeInfo[] { outputTypeInfo }, new int[] { outputColumnNum });
Object[] scrqtchRow = new Object[1];
// System.out.println("*VECTOR EXPRESSION* " + vectorExpression.getClass().getSimpleName());
/*
System.out.println(
"*DEBUG* typeInfo1 " + typeInfo1.toString() +
" typeInfo2 " + typeInfo2.toString() +
" " + comparison + " " +
" filterCompareTestMode " + filterCompareTestMode +
" columnScalarMode " + columnScalarMode +
" vectorExpression " + vectorExpression.toString());
*/
final boolean isFilter = (mode == VectorExpressionDescriptor.Mode.FILTER);
boolean copySelectedInUse = false;
int[] copySelected = new int[VectorizedRowBatch.DEFAULT_SIZE];
batchSource.resetBatchIteration();
int rowIndex = 0;
while (true) {
if (!batchSource.fillNextBatch(batch)) {
break;
}
final int originalBatchSize = batch.size;
if (isFilter) {
copySelectedInUse = batch.selectedInUse;
if (batch.selectedInUse) {
System.arraycopy(batch.selected, 0, copySelected, 0, originalBatchSize);
}
}
// In filter mode, the batch size can be made smaller.
vectorExpression.evaluate(batch);
if (!isFilter) {
extractResultObjects(batch, rowIndex, resultVectorExtractRow, scrqtchRow,
objectInspector, resultObjects);
} else {
final int currentBatchSize = batch.size;
if (copySelectedInUse && batch.selectedInUse) {
int selectIndex = 0;
for (int i = 0; i < originalBatchSize; i++) {
final int originalBatchIndex = copySelected[i];
final boolean booleanResult;
if (selectIndex < currentBatchSize && batch.selected[selectIndex] == originalBatchIndex) {
booleanResult = true;
selectIndex++;
} else {
booleanResult = false;
}
resultObjects[rowIndex + i] = new BooleanWritable(booleanResult);
}
} else if (batch.selectedInUse) {
int selectIndex = 0;
for (int i = 0; i < originalBatchSize; i++) {
final boolean booleanResult;
if (selectIndex < currentBatchSize && batch.selected[selectIndex] == i) {
booleanResult = true;
selectIndex++;
} else {
booleanResult = false;
}
resultObjects[rowIndex + i] = new BooleanWritable(booleanResult);
}
} else if (currentBatchSize == 0) {
// Whole batch got zapped.
for (int i = 0; i < originalBatchSize; i++) {
resultObjects[rowIndex + i] = new BooleanWritable(false);
}
} else {
// Every row kept.
for (int i = 0; i < originalBatchSize; i++) {
resultObjects[rowIndex + i] = new BooleanWritable(true);
}
}
}
rowIndex += originalBatchSize;
}
}
}
| |
/*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oic.simulator.serviceprovider.view;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.oic.simulator.SimulatorException;
import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
import oic.simulator.serviceprovider.manager.ResourceManager;
import oic.simulator.serviceprovider.manager.UiListenerHandler;
import oic.simulator.serviceprovider.model.MetaProperty;
import oic.simulator.serviceprovider.model.Resource;
import oic.simulator.serviceprovider.model.SingleResource;
import oic.simulator.serviceprovider.utils.Constants;
import oic.simulator.serviceprovider.utils.Utility;
import oic.simulator.serviceprovider.view.dialogs.UpdateResourceInterfaceDialog;
/**
* This class manages and shows the meta properties view in the perspective.
*/
public class MetaPropertiesView extends ViewPart {
public static final String VIEW_ID = "oic.simulator.serviceprovider.view.metaproperties";
private TableViewer tableViewer;
private final String[] columnHeaders = { "Property", "Value" };
private final Integer[] columnWidth = { 150, 150 };
private ISelectionChangedListener resourceSelectionChangedListener;
private ResourceManager resourceManagerRef;
private Set<String> updatedIfSet;
private List<MetaProperty> properties;
private boolean enable_edit;
private Button editBtn;
private Button cancelBtn;
private Map<String, String> ifTypes;
public MetaPropertiesView() {
resourceManagerRef = Activator.getDefault().getResourceManager();
resourceSelectionChangedListener = new ISelectionChangedListener() {
@Override
public void onResourceSelectionChange(final Resource resource) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (null != tableViewer) {
properties = getData(resource);
updateViewer(properties);
}
updateEditControls(resource);
}
});
}
};
}
@Override
public void createPartControl(final Composite parent) {
parent.setLayout(new GridLayout(2, false));
tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
createColumns(tableViewer);
// Make lines and header visible
final Table table = tableViewer.getTable();
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.horizontalSpan = 2;
table.setLayoutData(gd);
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer.setContentProvider(new PropertycontentProvider());
editBtn = new Button(parent, SWT.PUSH);
editBtn.setText("Edit");
gd = new GridData();
gd.widthHint = 50;
editBtn.setLayoutData(gd);
editBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (editBtn.getText().equals("Edit")) {
cancelBtn.setEnabled(true);
editBtn.setText("Save");
setEnableEdit(true);
Resource resource = resourceManagerRef
.getCurrentResourceInSelection();
if (null != resource) {
updatedIfSet = resource.getResourceInterfaces();
}
} else {
Resource resourceInSelection = resourceManagerRef
.getCurrentResourceInSelection();
if (null != resourceInSelection) {
// Null Check
boolean result = resourceManagerRef
.isPropertyValueInvalid(resourceInSelection,
properties, Constants.RESOURCE_URI);
if (result) {
MessageDialog.openError(parent.getShell(),
"Invalid Resource URI.",
Constants.INVALID_URI_MESSAGE);
return;
}
result = resourceManagerRef.isPropertyValueInvalid(
resourceInSelection, properties,
Constants.RESOURCE_NAME);
if (result) {
MessageDialog.openError(parent.getShell(),
"Invalid Input",
"Resource Name is invalid.");
return;
}
result = resourceManagerRef.isPropertyValueInvalid(
resourceInSelection, properties,
Constants.RESOURCE_TYPE);
if (result) {
MessageDialog.openError(parent.getShell(),
"Invalid Resource Type.",
Constants.INVALID_RESOURCE_TYPE_MESSAGE);
return;
}
boolean update = false;
boolean uriChange = false;
boolean typeChange = false;
boolean nameChange = false;
boolean interfaceChange = false;
if (resourceManagerRef.isPropValueChanged(
resourceInSelection, properties,
Constants.RESOURCE_NAME)) {
update = true;
nameChange = true;
}
if (resourceManagerRef.isPropValueChanged(
resourceInSelection, properties,
Constants.RESOURCE_URI)) {
// Check whether the new URI is unique.
if (!resourceManagerRef.isUriUnique(properties)) {
MessageDialog.openError(parent.getShell(),
"Resource URI in use",
"Resource URI is in use. Please try a different URI.");
return;
}
update = true;
uriChange = true;
}
if (resourceManagerRef.isPropValueChanged(
resourceInSelection, properties,
Constants.RESOURCE_TYPE)) {
update = true;
typeChange = true;
}
// Checking whether any changes made in resource
// interfaces by
// comparing the current interface set and updated
// interface set.
Set<String> curIfSet = resourceInSelection
.getResourceInterfaces();
if (null != curIfSet && null != updatedIfSet) {
if (curIfSet.size() != updatedIfSet.size()) {
update = true;
interfaceChange = true;
} else {
Iterator<String> itr = updatedIfSet.iterator();
while (itr.hasNext()) {
if (!curIfSet.contains(itr.next())) {
update = true;
interfaceChange = true;
break;
}
}
}
}
if (update) {
if (uriChange || typeChange || interfaceChange) {
if (resourceManagerRef
.isResourceStarted(resourceInSelection)) {
update = MessageDialog.openQuestion(
parent.getShell(),
"Save Details",
"Resource will be restarted to take the changes."
+ " Do you want to continue?");
if (!update) {
return;
}
}
}
try {
if (uriChange || nameChange || typeChange)
result = Activator
.getDefault()
.getResourceManager()
.updateResourceProperties(
resourceManagerRef
.getCurrentResourceInSelection(),
properties, uriChange,
nameChange, typeChange);
if (interfaceChange)
result = Activator
.getDefault()
.getResourceManager()
.updateResourceInterfaces(
resourceInSelection,
updatedIfSet);
} catch (SimulatorException ex) {
result = false;
}
if (!result) {
MessageDialog.openInformation(
parent.getShell(), "Operation status",
"Failed to update the resource properties.");
// Reset the old property values.
properties = getData(resourceManagerRef
.getCurrentResourceInSelection());
updateViewer(properties);
}
}
}
cancelBtn.setEnabled(false);
editBtn.setText("Edit");
setEnableEdit(false);
}
}
});
cancelBtn = new Button(parent, SWT.PUSH);
cancelBtn.setText("Cancel");
cancelBtn.setEnabled(false);
gd = new GridData();
gd.widthHint = 70;
cancelBtn.setLayoutData(gd);
cancelBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Resource res = resourceManagerRef
.getCurrentResourceInSelection();
if (null != res) {
properties = getData(res);
}
updateViewer(properties);
cancelBtn.setEnabled(false);
editBtn.setText("Edit");
setEnableEdit(false);
if (null != updatedIfSet)
updatedIfSet.clear();
}
});
// Get the supported interfaces.
Map<String, String> ifTypesSupported = Utility
.getResourceInterfaces(SingleResource.class);
if (null != ifTypesSupported && !ifTypesSupported.isEmpty()) {
ifTypes = new HashMap<String, String>();
String key;
for (Map.Entry<String, String> entry : ifTypesSupported.entrySet()) {
key = entry.getValue() + " (" + entry.getKey() + ")";
ifTypes.put(key, entry.getKey());
}
}
addManagerListeners();
// Check whether there is any resource selected already
Resource resource = resourceManagerRef.getCurrentResourceInSelection();
properties = getData(resource);
if (null != properties) {
updateViewer(properties);
}
updateEditControls(resource);
}
private void updateEditControls(Object obj) {
if (!editBtn.isDisposed() && !cancelBtn.isDisposed()) {
if (editBtn.getText().equals("Save")) {
editBtn.setText("Edit");
setEnableEdit(false);
}
if (null == obj) {
editBtn.setEnabled(false);
} else {
editBtn.setEnabled(true);
}
cancelBtn.setEnabled(false);
}
}
private List<MetaProperty> getData(Resource resource) {
if (null != resource) {
List<MetaProperty> metaPropertyList = resourceManagerRef
.getMetaProperties(resource);
return metaPropertyList;
} else {
return null;
}
}
private void updateViewer(List<MetaProperty> metaPropertyList) {
if (null != tableViewer) {
Table tbl = tableViewer.getTable();
if (tbl.isDisposed()) {
return;
}
if (null != metaPropertyList) {
tableViewer.setInput(metaPropertyList.toArray());
tbl.setLinesVisible(true);
} else {
tbl.removeAll();
tbl.setLinesVisible(false);
}
}
}
public void createColumns(final TableViewer tableViewer) {
TableViewerColumn propName = new TableViewerColumn(tableViewer,
SWT.NONE);
propName.getColumn().setWidth(columnWidth[0]);
propName.getColumn().setText(columnHeaders[0]);
propName.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
MetaProperty prop = (MetaProperty) cell.getElement();
cell.setText(prop.getPropName());
super.update(cell);
}
});
TableViewerColumn propValue = new TableViewerColumn(tableViewer,
SWT.NONE);
propValue.getColumn().setWidth(columnWidth[1]);
propValue.getColumn().setText(columnHeaders[1]);
propValue.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
MetaProperty prop = (MetaProperty) cell.getElement();
cell.setText(prop.getPropValue());
super.update(cell);
}
});
propValue.setEditingSupport(new PropValueEditor(tableViewer));
}
private void addManagerListeners() {
UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
resourceSelectionChangedListener);
}
class PropertycontentProvider implements IStructuredContentProvider {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
}
@Override
public Object[] getElements(Object element) {
return (Object[]) element;
}
}
@Override
public void dispose() {
// Unregister the listener
if (null != resourceSelectionChangedListener) {
UiListenerHandler.getInstance()
.removeResourceSelectionChangedUIListener(
resourceSelectionChangedListener);
}
super.dispose();
}
class PropValueEditor extends EditingSupport {
private final TableViewer viewer;
public PropValueEditor(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected CellEditor getCellEditor(final Object element) {
if (!getEnableEdit()) {
return null;
}
String propName = ((MetaProperty) element).getPropName();
CellEditor editor = new TextCellEditor(viewer.getTable());
if (null != propName && propName.equals(Constants.INTERFACE_TYPES)) {
editor.setStyle(SWT.READ_ONLY);
final Text txt = (Text) editor.getControl();
txt.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
if (null == updatedIfSet) {
return;
}
// Form the result set of interfaces with check-box that
// will be shown in the dialog for editing.
Map<String, String> curResInterfaces = new HashMap<String, String>();
for (Map.Entry<String, String> entry : ifTypes
.entrySet()) {
if (updatedIfSet.contains(entry.getValue())) {
curResInterfaces.put(entry.getKey(),
entry.getValue());
}
}
// Show the dialog for editing the resource interfaces.
UpdateResourceInterfaceDialog ad = new UpdateResourceInterfaceDialog(
Display.getDefault().getActiveShell(),
curResInterfaces, ifTypes);
if (ad.open() == Window.OK) {
// Update the local copy of the current resource
// interfaces to keep the state for save operation.
updatedIfSet.clear();
StringBuilder newPropValue = new StringBuilder();
for (Map.Entry<String, String> entry : curResInterfaces
.entrySet()) {
if (!newPropValue.toString().isEmpty()) {
newPropValue.append(", ");
}
String value = ifTypes.get(entry.getKey());
newPropValue.append(value);
updatedIfSet.add(value);
}
// Update the model
MetaProperty prop = (MetaProperty) element;
prop.setPropValue(newPropValue.toString());
// Update the viewer in a separate UI thread.
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.refresh(element, true);
}
});
}
}
});
}
return editor;
}
@Override
protected Object getValue(Object element) {
return ((MetaProperty) element).getPropValue();
}
@Override
protected void setValue(Object element, Object value) {
MetaProperty prop = (MetaProperty) element;
if (prop.getPropName().equals(Constants.INTERFACE_TYPES)) {
return;
}
prop.setPropValue(String.valueOf(value));
viewer.update(element, null);
}
}
private synchronized Boolean getEnableEdit() {
return enable_edit;
}
private synchronized void setEnableEdit(boolean value) {
enable_edit = value;
}
@Override
public void setFocus() {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.taskmanager;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.InetAddress;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.util.InstantiationUtil;
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for the TaskManagerLocation, which identifies the location and connection
* information of a TaskManager.
*/
public class TaskManagerLocationTest {
@Test
public void testEqualsHashAndCompareTo() {
try {
ResourceID resourceID1 = new ResourceID("a");
ResourceID resourceID2 = new ResourceID("b");
ResourceID resourceID3 = new ResourceID("c");
// we mock the addresses to save the times of the reverse name lookups
InetAddress address1 = mock(InetAddress.class);
when(address1.getCanonicalHostName()).thenReturn("localhost");
when(address1.getHostName()).thenReturn("localhost");
when(address1.getHostAddress()).thenReturn("127.0.0.1");
when(address1.getAddress()).thenReturn(new byte[] {127, 0, 0, 1} );
InetAddress address2 = mock(InetAddress.class);
when(address2.getCanonicalHostName()).thenReturn("testhost1");
when(address2.getHostName()).thenReturn("testhost1");
when(address2.getHostAddress()).thenReturn("0.0.0.0");
when(address2.getAddress()).thenReturn(new byte[] {0, 0, 0, 0} );
InetAddress address3 = mock(InetAddress.class);
when(address3.getCanonicalHostName()).thenReturn("testhost2");
when(address3.getHostName()).thenReturn("testhost2");
when(address3.getHostAddress()).thenReturn("192.168.0.1");
when(address3.getAddress()).thenReturn(new byte[] {(byte) 192, (byte) 168, 0, 1} );
// one == four != two != three
TaskManagerLocation one = new TaskManagerLocation(resourceID1, address1, 19871);
TaskManagerLocation two = new TaskManagerLocation(resourceID2, address2, 19871);
TaskManagerLocation three = new TaskManagerLocation(resourceID3, address3, 10871);
TaskManagerLocation four = new TaskManagerLocation(resourceID1, address1, 19871);
assertTrue(one.equals(four));
assertTrue(!one.equals(two));
assertTrue(!one.equals(three));
assertTrue(!two.equals(three));
assertTrue(!three.equals(four));
assertTrue(one.compareTo(four) == 0);
assertTrue(four.compareTo(one) == 0);
assertTrue(one.compareTo(two) != 0);
assertTrue(one.compareTo(three) != 0);
assertTrue(two.compareTo(three) != 0);
assertTrue(three.compareTo(four) != 0);
{
int val = one.compareTo(two);
assertTrue(two.compareTo(one) == -val);
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testSerialization() {
try {
// without resolved hostname
{
TaskManagerLocation original = new TaskManagerLocation(
ResourceID.generate(), InetAddress.getByName("1.2.3.4"), 8888);
TaskManagerLocation serCopy = InstantiationUtil.clone(original);
assertEquals(original, serCopy);
}
// with resolved hostname
{
TaskManagerLocation original = new TaskManagerLocation(
ResourceID.generate(), InetAddress.getByName("127.0.0.1"), 19871);
original.getFQDNHostname();
TaskManagerLocation serCopy = InstantiationUtil.clone(original);
assertEquals(original, serCopy);
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testGetFQDNHostname() {
try {
TaskManagerLocation info1 = new TaskManagerLocation(ResourceID.generate(), InetAddress.getByName("127.0.0.1"), 19871);
assertNotNull(info1.getFQDNHostname());
TaskManagerLocation info2 = new TaskManagerLocation(ResourceID.generate(), InetAddress.getByName("1.2.3.4"), 8888);
assertNotNull(info2.getFQDNHostname());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testGetHostname0() {
try {
InetAddress address = mock(InetAddress.class);
when(address.getCanonicalHostName()).thenReturn("worker2.cluster.mycompany.com");
when(address.getHostName()).thenReturn("worker2.cluster.mycompany.com");
when(address.getHostAddress()).thenReturn("127.0.0.1");
final TaskManagerLocation info = new TaskManagerLocation(ResourceID.generate(), address, 19871);
Assert.assertEquals("worker2", info.getHostname());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testGetHostname1() {
try {
InetAddress address = mock(InetAddress.class);
when(address.getCanonicalHostName()).thenReturn("worker10");
when(address.getHostName()).thenReturn("worker10");
when(address.getHostAddress()).thenReturn("127.0.0.1");
TaskManagerLocation info = new TaskManagerLocation(ResourceID.generate(), address, 19871);
Assert.assertEquals("worker10", info.getHostname());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testGetHostname2() {
try {
final String addressString = "192.168.254.254";
// we mock the addresses to save the times of the reverse name lookups
InetAddress address = mock(InetAddress.class);
when(address.getCanonicalHostName()).thenReturn("192.168.254.254");
when(address.getHostName()).thenReturn("192.168.254.254");
when(address.getHostAddress()).thenReturn("192.168.254.254");
when(address.getAddress()).thenReturn(new byte[] {(byte) 192, (byte) 168, (byte) 254, (byte) 254} );
TaskManagerLocation info = new TaskManagerLocation(ResourceID.generate(), address, 54152);
assertNotNull(info.getFQDNHostname());
assertTrue(info.getFQDNHostname().equals(addressString));
assertNotNull(info.getHostname());
assertTrue(info.getHostname().equals(addressString));
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.http4;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import org.apache.camel.CamelContext;
import org.apache.camel.ComponentVerifier;
import org.apache.camel.Endpoint;
import org.apache.camel.Producer;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.VerifiableComponent;
import org.apache.camel.http.common.HttpBinding;
import org.apache.camel.http.common.HttpCommonComponent;
import org.apache.camel.http.common.HttpHelper;
import org.apache.camel.http.common.HttpRestHeaderFilterStrategy;
import org.apache.camel.http.common.UrlRewrite;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestProducerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Defines the <a href="http://camel.apache.org/http4.html">HTTP4
* Component</a>
*
* @version
*/
@Metadata(label = "verifiers", enums = "parameters,connectivity")
public class HttpComponent extends HttpCommonComponent implements RestProducerFactory, VerifiableComponent {
private static final Logger LOG = LoggerFactory.getLogger(HttpComponent.class);
@Metadata(label = "advanced", description = "To use the custom HttpClientConfigurer to perform configuration of the HttpClient that will be used.")
protected HttpClientConfigurer httpClientConfigurer;
@Metadata(label = "advanced", description = "To use a custom and shared HttpClientConnectionManager to manage connections."
+ " If this has been configured then this is always used for all endpoints created by this component.")
protected HttpClientConnectionManager clientConnectionManager;
@Metadata(label = "advanced", description = "To use a custom org.apache.http.protocol.HttpContext when executing requests.")
protected HttpContext httpContext;
@Metadata(label = "security", description = "To configure security using SSLContextParameters."
+ " Important: Only one instance of org.apache.camel.util.jsse.SSLContextParameters is supported per HttpComponent."
+ " If you need to use 2 or more different instances, you need to define a new HttpComponent per instance you need.")
protected SSLContextParameters sslContextParameters;
@Metadata(label = "security", description = "To use a custom X509HostnameVerifier such as DefaultHostnameVerifier or NoopHostnameVerifier.")
protected HostnameVerifier x509HostnameVerifier = new DefaultHostnameVerifier();
@Metadata(label = "producer", description = "To use a custom org.apache.http.client.CookieStore."
+ " By default the org.apache.http.impl.client.BasicCookieStore is used which is an in-memory only cookie store."
+ " Notice if bridgeEndpoint=true then the cookie store is forced to be a noop cookie store as cookie"
+ " shouldn't be stored as we are just bridging (eg acting as a proxy).")
protected CookieStore cookieStore;
// options to the default created http connection manager
@Metadata(label = "advanced", defaultValue = "200", description = "The maximum number of connections.")
protected int maxTotalConnections = 200;
@Metadata(label = "advanced", defaultValue = "20", description = "The maximum number of connections per route.")
protected int connectionsPerRoute = 20;
// It's MILLISECONDS, the default value is always keep alive
@Metadata(label = "advanced", description = "The time for connection to live, the time unit is millisecond, the default value is always keep alive.")
protected long connectionTimeToLive = -1;
public HttpComponent() {
super(HttpEndpoint.class);
}
public HttpComponent(Class<? extends HttpEndpoint> endpointClass) {
super(endpointClass);
}
/**
* Creates the HttpClientConfigurer based on the given parameters
*
* @param parameters the map of parameters
* @param secure whether the endpoint is secure (eg https4)
* @return the configurer
* @throws Exception is thrown if error creating configurer
*/
protected HttpClientConfigurer createHttpClientConfigurer(Map<String, Object> parameters, boolean secure) throws Exception {
// prefer to use endpoint configured over component configured
HttpClientConfigurer configurer = resolveAndRemoveReferenceParameter(parameters, "httpClientConfigurer", HttpClientConfigurer.class);
if (configurer == null) {
// fallback to component configured
configurer = getHttpClientConfigurer();
}
configurer = configureBasicAuthentication(parameters, configurer);
configurer = configureHttpProxy(parameters, configurer, secure);
return configurer;
}
private HttpClientConfigurer configureBasicAuthentication(Map<String, Object> parameters, HttpClientConfigurer configurer) {
String authUsername = getParameter(parameters, "authUsername", String.class);
String authPassword = getParameter(parameters, "authPassword", String.class);
if (authUsername != null && authPassword != null) {
String authDomain = getParameter(parameters, "authDomain", String.class);
String authHost = getParameter(parameters, "authHost", String.class);
return CompositeHttpConfigurer.combineConfigurers(configurer, new BasicAuthenticationHttpClientConfigurer(authUsername, authPassword, authDomain, authHost));
}
return configurer;
}
private HttpClientConfigurer configureHttpProxy(Map<String, Object> parameters, HttpClientConfigurer configurer, boolean secure) throws Exception {
String proxyAuthScheme = getParameter(parameters, "proxyAuthScheme", String.class);
if (proxyAuthScheme == null) {
// fallback and use either http or https depending on secure
proxyAuthScheme = secure ? "https" : "http";
}
String proxyAuthHost = getParameter(parameters, "proxyAuthHost", String.class);
Integer proxyAuthPort = getParameter(parameters, "proxyAuthPort", Integer.class);
if (proxyAuthHost != null && proxyAuthPort != null) {
String proxyAuthUsername = getParameter(parameters, "proxyAuthUsername", String.class);
String proxyAuthPassword = getParameter(parameters, "proxyAuthPassword", String.class);
String proxyAuthDomain = getParameter(parameters, "proxyAuthDomain", String.class);
String proxyAuthNtHost = getParameter(parameters, "proxyAuthNtHost", String.class);
if (proxyAuthUsername != null && proxyAuthPassword != null) {
return CompositeHttpConfigurer.combineConfigurers(
configurer, new ProxyHttpClientConfigurer(proxyAuthHost, proxyAuthPort, proxyAuthScheme, proxyAuthUsername, proxyAuthPassword, proxyAuthDomain, proxyAuthNtHost));
} else {
return CompositeHttpConfigurer.combineConfigurers(configurer, new ProxyHttpClientConfigurer(proxyAuthHost, proxyAuthPort, proxyAuthScheme));
}
}
return configurer;
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
Map<String, Object> httpClientParameters = new HashMap<String, Object>(parameters);
final Map<String, Object> httpClientOptions = new HashMap<>();
final HttpClientBuilder clientBuilder = createHttpClientBuilder(uri, parameters, httpClientOptions);
HttpBinding httpBinding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
HttpContext httpContext = resolveAndRemoveReferenceParameter(parameters, "httpContext", HttpContext.class);
SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParameters", SSLContextParameters.class);
if (sslContextParameters == null) {
sslContextParameters = getSslContextParameters();
}
String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
boolean secure = HttpHelper.isSecureConnection(uri) || sslContextParameters != null;
// need to set scheme on address uri depending on if its secure or not
String addressUri = (secure ? "https://" : "http://") + remaining;
addressUri = UnsafeUriCharactersEncoder.encodeHttpURI(addressUri);
URI uriHttpUriAddress = new URI(addressUri);
// validate http uri that end-user did not duplicate the http part that can be a common error
int pos = uri.indexOf("//");
if (pos != -1) {
String part = uri.substring(pos + 2);
if (part.startsWith("http:") || part.startsWith("https:")) {
throw new ResolveEndpointFailedException(uri,
"The uri part is not configured correctly. You have duplicated the http(s) protocol.");
}
}
// create the configurer to use for this endpoint
HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, secure);
URI endpointUri = URISupport.createRemainingURI(uriHttpUriAddress, httpClientParameters);
// the endpoint uri should use the component name as scheme, so we need to re-create it once more
String scheme = ObjectHelper.before(uri, "://");
endpointUri = URISupport.createRemainingURI(
new URI(scheme,
endpointUri.getUserInfo(),
endpointUri.getHost(),
endpointUri.getPort(),
endpointUri.getPath(),
endpointUri.getQuery(),
endpointUri.getFragment()),
httpClientParameters);
// create the endpoint and set the http uri to be null
String endpointUriString = endpointUri.toString();
LOG.debug("Creating endpoint uri {}", endpointUriString);
final HttpClientConnectionManager localConnectionManager = createConnectionManager(parameters, sslContextParameters);
HttpEndpoint endpoint = new HttpEndpoint(endpointUriString, this, clientBuilder, localConnectionManager, configurer);
// configure the endpoint with the common configuration from the component
if (getHttpConfiguration() != null) {
Map<String, Object> properties = new HashMap<>();
IntrospectionSupport.getProperties(getHttpConfiguration(), properties, null);
setProperties(endpoint, properties);
}
if (urlRewrite != null) {
// let CamelContext deal with the lifecycle of the url rewrite
// this ensures its being shutdown when Camel shutdown etc.
getCamelContext().addService(urlRewrite);
endpoint.setUrlRewrite(urlRewrite);
}
// configure the endpoint
setProperties(endpoint, parameters);
// determine the portnumber (special case: default portnumber)
//int port = getPort(uriHttpUriAddress);
// we can not change the port of an URI, we must create a new one with an explicit port value
URI httpUri = URISupport.createRemainingURI(
new URI(uriHttpUriAddress.getScheme(),
uriHttpUriAddress.getUserInfo(),
uriHttpUriAddress.getHost(),
uriHttpUriAddress.getPort(),
uriHttpUriAddress.getPath(),
uriHttpUriAddress.getQuery(),
uriHttpUriAddress.getFragment()),
parameters);
endpoint.setHttpUri(httpUri);
if (headerFilterStrategy != null) {
endpoint.setHeaderFilterStrategy(headerFilterStrategy);
} else {
setEndpointHeaderFilterStrategy(endpoint);
}
endpoint.setBinding(getHttpBinding());
if (httpBinding != null) {
endpoint.setBinding(httpBinding);
}
if (httpMethodRestrict != null) {
endpoint.setHttpMethodRestrict(httpMethodRestrict);
}
endpoint.setHttpContext(getHttpContext());
if (httpContext != null) {
endpoint.setHttpContext(httpContext);
}
if (endpoint.getCookieStore() == null) {
endpoint.setCookieStore(getCookieStore());
}
endpoint.setHttpClientOptions(httpClientOptions);
return endpoint;
}
protected HttpClientConnectionManager createConnectionManager(final Map<String, Object> parameters,
final SSLContextParameters sslContextParameters) throws GeneralSecurityException, IOException {
if (clientConnectionManager != null) {
return clientConnectionManager;
}
final HostnameVerifier resolvedHostnameVerifier = resolveAndRemoveReferenceParameter(parameters, "x509HostnameVerifier", HostnameVerifier.class);
final HostnameVerifier hostnameVerifier = Optional.ofNullable(resolvedHostnameVerifier).orElse(x509HostnameVerifier);
// need to check the parameters of maxTotalConnections and connectionsPerRoute
final int maxTotalConnections = getAndRemoveParameter(parameters, "maxTotalConnections", int.class, 0);
final int connectionsPerRoute = getAndRemoveParameter(parameters, "connectionsPerRoute", int.class, 0);
final Registry<ConnectionSocketFactory> connectionRegistry = createConnectionRegistry(hostnameVerifier, sslContextParameters);
return createConnectionManager(connectionRegistry, maxTotalConnections, connectionsPerRoute);
}
protected HttpClientBuilder createHttpClientBuilder(final String uri, final Map<String, Object> parameters,
final Map<String, Object> httpClientOptions) throws Exception {
// http client can be configured from URI options
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// allow the builder pattern
httpClientOptions.putAll(IntrospectionSupport.extractProperties(parameters, "httpClient."));
IntrospectionSupport.setProperties(clientBuilder, httpClientOptions);
// set the Request configure this way and allow the builder pattern
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
IntrospectionSupport.setProperties(requestConfigBuilder, httpClientOptions);
clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
// validate that we could resolve all httpClient. parameters as this component is lenient
validateParameters(uri, httpClientOptions, null);
return clientBuilder;
}
protected Registry<ConnectionSocketFactory> createConnectionRegistry(HostnameVerifier x509HostnameVerifier, SSLContextParameters sslContextParams)
throws GeneralSecurityException, IOException {
// create the default connection registry to use
RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create();
builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
builder.register("http4", PlainConnectionSocketFactory.getSocketFactory());
if (sslContextParams != null) {
builder.register("https", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier));
builder.register("https4", new SSLConnectionSocketFactory(sslContextParams.createSSLContext(getCamelContext()), x509HostnameVerifier));
} else {
builder.register("https4", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier));
builder.register("https", new SSLConnectionSocketFactory(SSLContexts.createDefault(), x509HostnameVerifier));
}
return builder.build();
}
protected HttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry) {
return createConnectionManager(registry, 0, 0);
}
protected HttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, int maxTotalConnections, int connectionsPerRoute) {
// setup the connection live time
PoolingHttpClientConnectionManager answer =
new PoolingHttpClientConnectionManager(registry, null, null, null, getConnectionTimeToLive(), TimeUnit.MILLISECONDS);
int localMaxTotalConnections = maxTotalConnections;
if (localMaxTotalConnections == 0) {
localMaxTotalConnections = getMaxTotalConnections();
}
if (localMaxTotalConnections > 0) {
answer.setMaxTotal(localMaxTotalConnections);
}
int localConnectionsPerRoute = connectionsPerRoute;
if (localConnectionsPerRoute == 0) {
localConnectionsPerRoute = getConnectionsPerRoute();
}
if (localConnectionsPerRoute > 0) {
answer.setDefaultMaxPerRoute(localConnectionsPerRoute);
}
LOG.info("Created ClientConnectionManager " + answer);
return answer;
}
@Override
protected boolean useIntrospectionOnEndpoint() {
return false;
}
@Override
public Producer createProducer(CamelContext camelContext, String host,
String verb, String basePath, String uriTemplate, String queryParameters,
String consumes, String produces, Map<String, Object> parameters) throws Exception {
// avoid leading slash
basePath = FileUtil.stripLeadingSeparator(basePath);
uriTemplate = FileUtil.stripLeadingSeparator(uriTemplate);
// replace http with http4 in the host part
host = host.replace("http", "http4");
// get the endpoint
String url = host;
if (!ObjectHelper.isEmpty(basePath)) {
url += "/" + basePath;
}
if (!ObjectHelper.isEmpty(uriTemplate)) {
url += "/" + uriTemplate;
}
HttpEndpoint endpoint = camelContext.getEndpoint(url, HttpEndpoint.class);
if (parameters != null && !parameters.isEmpty()) {
setProperties(camelContext, endpoint, parameters);
}
String path = uriTemplate != null ? uriTemplate : basePath;
endpoint.setHeaderFilterStrategy(new HttpRestHeaderFilterStrategy(path, queryParameters));
// the endpoint must be started before creating the producer
ServiceHelper.startService(endpoint);
return endpoint.createProducer();
}
public HttpClientConfigurer getHttpClientConfigurer() {
return httpClientConfigurer;
}
/**
* To use the custom HttpClientConfigurer to perform configuration of the HttpClient that will be used.
*/
public void setHttpClientConfigurer(HttpClientConfigurer httpClientConfigurer) {
this.httpClientConfigurer = httpClientConfigurer;
}
public HttpClientConnectionManager getClientConnectionManager() {
return clientConnectionManager;
}
/**
* To use a custom and shared HttpClientConnectionManager to manage connections.
* If this has been configured then this is always used for all endpoints created by this component.
*/
public void setClientConnectionManager(HttpClientConnectionManager clientConnectionManager) {
this.clientConnectionManager = clientConnectionManager;
}
public HttpContext getHttpContext() {
return httpContext;
}
/**
* To use a custom org.apache.http.protocol.HttpContext when executing requests.
*/
public void setHttpContext(HttpContext httpContext) {
this.httpContext = httpContext;
}
public SSLContextParameters getSslContextParameters() {
return sslContextParameters;
}
/**
* To configure security using SSLContextParameters.
* Important: Only one instance of org.apache.camel.util.jsse.SSLContextParameters is supported per HttpComponent.
* If you need to use 2 or more different instances, you need to define a new HttpComponent per instance you need.
*/
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
public HostnameVerifier getX509HostnameVerifier() {
return x509HostnameVerifier;
}
/**
* To use a custom X509HostnameVerifier such as {@link DefaultHostnameVerifier}
* or {@link org.apache.http.conn.ssl.NoopHostnameVerifier}.
*/
public void setX509HostnameVerifier(HostnameVerifier x509HostnameVerifier) {
this.x509HostnameVerifier = x509HostnameVerifier;
}
public int getMaxTotalConnections() {
return maxTotalConnections;
}
/**
* The maximum number of connections.
*/
public void setMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
}
public int getConnectionsPerRoute() {
return connectionsPerRoute;
}
/**
* The maximum number of connections per route.
*/
public void setConnectionsPerRoute(int connectionsPerRoute) {
this.connectionsPerRoute = connectionsPerRoute;
}
public long getConnectionTimeToLive() {
return connectionTimeToLive;
}
/**
* The time for connection to live, the time unit is millisecond, the default value is always keep alive.
*/
public void setConnectionTimeToLive(long connectionTimeToLive) {
this.connectionTimeToLive = connectionTimeToLive;
}
public CookieStore getCookieStore() {
return cookieStore;
}
/**
* To use a custom org.apache.http.client.CookieStore.
* By default the org.apache.http.impl.client.BasicCookieStore is used which is an in-memory only cookie store.
* Notice if bridgeEndpoint=true then the cookie store is forced to be a noop cookie store as cookie
* shouldn't be stored as we are just bridging (eg acting as a proxy).
*/
public void setCookieStore(CookieStore cookieStore) {
this.cookieStore = cookieStore;
}
@Override
public void doStart() throws Exception {
super.doStart();
}
@Override
public void doStop() throws Exception {
// shutdown connection manager
if (clientConnectionManager != null) {
LOG.info("Shutting down ClientConnectionManager: " + clientConnectionManager);
clientConnectionManager.shutdown();
clientConnectionManager = null;
}
super.doStop();
}
/**
* TODO: document
*/
public ComponentVerifier getVerifier() {
return new HttpComponentVerifier(this);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.parser.roaster;
import java.lang.annotation.Annotation;
import java.util.List;
import org.jboss.forge.roaster.model.JavaType;
import org.jboss.forge.roaster.model.Type;
import org.jboss.forge.roaster.model.TypeVariable;
import org.jboss.forge.roaster.model.Visibility;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.JavaDocSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.jboss.forge.roaster.model.source.ParameterSource;
import org.jboss.forge.roaster.model.source.TypeVariableSource;
/**
* In use when we have discovered a RouteBuilder being as anonymous inner class
*/
public class AnonymousMethodSource implements MethodSource<JavaClassSource> {
// this implementation should only implement the needed logic to support the parser
private final JavaClassSource origin;
private final Object internal;
public AnonymousMethodSource(JavaClassSource origin, Object internal) {
this.origin = origin;
this.internal = internal;
}
@Override
public MethodSource<JavaClassSource> setDefault(boolean b) {
return null;
}
@Override
public MethodSource<JavaClassSource> setSynchronized(boolean b) {
return null;
}
@Override
public MethodSource<JavaClassSource> setNative(boolean b) {
return null;
}
@Override
public MethodSource<JavaClassSource> setReturnType(Class<?> aClass) {
return null;
}
@Override
public MethodSource<JavaClassSource> setReturnType(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> setReturnType(JavaType<?> javaType) {
return null;
}
@Override
public MethodSource<JavaClassSource> setReturnTypeVoid() {
return null;
}
@Override
public MethodSource<JavaClassSource> setBody(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> setConstructor(boolean b) {
return null;
}
@Override
public MethodSource<JavaClassSource> setParameters(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> addThrows(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> addThrows(Class<? extends Exception> aClass) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeThrows(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeThrows(Class<? extends Exception> aClass) {
return null;
}
@Override
public boolean isSynchronized() {
return false;
}
@Override
public boolean isNative() {
return false;
}
@Override
public String getBody() {
return null;
}
@Override
public boolean isConstructor() {
return false;
}
@Override
public Type<JavaClassSource> getReturnType() {
return null;
}
@Override
public boolean isReturnTypeVoid() {
return false;
}
@Override
public List<ParameterSource<JavaClassSource>> getParameters() {
return null;
}
@Override
public String toSignature() {
return null;
}
@Override
public List<String> getThrownExceptions() {
return null;
}
@Override
public boolean isDefault() {
return false;
}
@Override
public ParameterSource<JavaClassSource> addParameter(Class<?> aClass, String s) {
return null;
}
@Override
public ParameterSource<JavaClassSource> addParameter(String s, String s1) {
return null;
}
@Override
public ParameterSource<JavaClassSource> addParameter(JavaType<?> javaType, String s) {
return null;
}
@Override
public void removeAllAnnotations() {
}
@Override
public MethodSource<JavaClassSource> removeParameter(ParameterSource<JavaClassSource> parameterSource) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeParameter(Class<?> aClass, String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeParameter(String s, String s1) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeParameter(JavaType<?> javaType, String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> setAbstract(boolean b) {
return null;
}
@Override
public List<AnnotationSource<JavaClassSource>> getAnnotations() {
return null;
}
@Override
public boolean hasAnnotation(Class<? extends Annotation> aClass) {
return false;
}
@Override
public boolean hasAnnotation(String s) {
return false;
}
@Override
public AnnotationSource<JavaClassSource> getAnnotation(Class<? extends Annotation> aClass) {
return null;
}
@Override
public AnnotationSource<JavaClassSource> getAnnotation(String s) {
return null;
}
@Override
public AnnotationSource<JavaClassSource> addAnnotation() {
return null;
}
@Override
public AnnotationSource<JavaClassSource> addAnnotation(Class<? extends Annotation> aClass) {
return null;
}
@Override
public AnnotationSource<JavaClassSource> addAnnotation(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeAnnotation(org.jboss.forge.roaster.model.Annotation<JavaClassSource> annotation) {
return null;
}
@Override
public List<TypeVariableSource<JavaClassSource>> getTypeVariables() {
return null;
}
@Override
public TypeVariableSource<JavaClassSource> getTypeVariable(String s) {
return null;
}
@Override
public TypeVariableSource<JavaClassSource> addTypeVariable() {
return null;
}
@Override
public TypeVariableSource<JavaClassSource> addTypeVariable(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeTypeVariable(String s) {
return null;
}
@Override
public MethodSource<JavaClassSource> removeTypeVariable(TypeVariable<?> typeVariable) {
return null;
}
@Override
public boolean hasJavaDoc() {
return false;
}
@Override
public boolean isAbstract() {
return false;
}
@Override
public MethodSource<JavaClassSource> setFinal(boolean b) {
return null;
}
@Override
public boolean isFinal() {
return false;
}
@Override
public Object getInternal() {
return internal;
}
@Override
public JavaDocSource<MethodSource<JavaClassSource>> getJavaDoc() {
return null;
}
@Override
public MethodSource<JavaClassSource> removeJavaDoc() {
return null;
}
@Override
public MethodSource<JavaClassSource> setName(String s) {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public JavaClassSource getOrigin() {
return origin;
}
@Override
public MethodSource<JavaClassSource> setStatic(boolean b) {
return null;
}
@Override
public boolean isStatic() {
return false;
}
@Override
public MethodSource<JavaClassSource> setPackagePrivate() {
return null;
}
@Override
public MethodSource<JavaClassSource> setPublic() {
return null;
}
@Override
public MethodSource<JavaClassSource> setPrivate() {
return null;
}
@Override
public MethodSource<JavaClassSource> setProtected() {
return null;
}
@Override
public MethodSource<JavaClassSource> setVisibility(Visibility visibility) {
return null;
}
@Override
public boolean isPackagePrivate() {
return false;
}
@Override
public boolean isPublic() {
return false;
}
@Override
public boolean isPrivate() {
return false;
}
@Override
public boolean isProtected() {
return false;
}
@Override
public Visibility getVisibility() {
return null;
}
@Override
public int getColumnNumber() {
return 0;
}
@Override
public int getStartPosition() {
return 0;
}
@Override
public int getEndPosition() {
return 0;
}
@Override
public int getLineNumber() {
return 0;
}
@Override
public boolean hasTypeVariable(String arg0) {
return false;
}
@Override
public MethodSource<JavaClassSource> setReturnType(Type<?> arg0) {
return null;
}
}
| |
package org.jzy3d.chart;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jzy3d.chart.controllers.ChartCameraController;
import org.jzy3d.colors.Color;
import org.jzy3d.maths.Coord3d;
import org.jzy3d.maths.Scale;
import org.jzy3d.plot3d.primitives.AbstractDrawable;
import org.jzy3d.plot3d.primitives.axes.layout.IAxeLayout;
import org.jzy3d.plot3d.rendering.canvas.CanvasAWT;
import org.jzy3d.plot3d.rendering.canvas.CanvasSwing;
import org.jzy3d.plot3d.rendering.canvas.ICanvas;
import org.jzy3d.plot3d.rendering.canvas.OffscreenCanvas;
import org.jzy3d.plot3d.rendering.canvas.Quality;
import org.jzy3d.plot3d.rendering.scene.Scene;
import org.jzy3d.plot3d.rendering.view.Renderer2d;
import org.jzy3d.plot3d.rendering.view.View;
import org.jzy3d.plot3d.rendering.view.modes.ViewPositionMode;
/** {@link Chart} is a convenient object that gather all components required to render
* a 3d scene for plotting.
*
* The chart {@link Quality} enable the following functionalities:
*
*
*
*
* @author Martin Pernollet
*
*/
public class Chart{
public Chart(){
this(Quality.Intermediate, "awt");
}
public Chart(Quality quality){
this(quality, "awt");
}
public Chart(String chartType){
this(Quality.Intermediate, chartType);
}
public Chart(Quality quality, String chartType){
// Set up controllers
controllers = new ArrayList<ChartCameraController>(1);
// Set up the scene and 3d canvas
scene = initializeScene( quality.isAlphaActivated() );
canvas = initializeCanvas(scene, quality, chartType);
// Set up the view
view = (ChartView)canvas.getView();
view.setBackgroundColor(Color.WHITE);
}
protected ICanvas initializeCanvas(Scene scene, Quality quality, String chartType){
if("awt".compareTo(chartType)==0)
return new CanvasAWT(scene, quality);
else if("swing".compareTo(chartType)==0)
return new CanvasSwing(scene, quality);
else if(chartType.startsWith("offscreen")){
Pattern pattern = Pattern.compile("offscreen,(\\d+),(\\d+)");
Matcher matcher = pattern.matcher(chartType);
if(matcher.matches()){
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
return new OffscreenCanvas(scene, quality, width, height);
}
else
return new OffscreenCanvas(scene, quality);
}
else
throw new RuntimeException("unknown chart type:" + chartType);
}
/**
* Provides a concrete scene. This method shoud be overriden to inject a custom scene,
* which may rely on several views, and could enhance manipulation of scene graph.
*/
protected ChartScene initializeScene(boolean graphsort){
return new ChartScene(graphsort);
}
public void clear(){
scene.clear();
view.shoot();
}
public void dispose(){
clearControllerList();
canvas.dispose();
scene.dispose(); // view is disposed by scene
canvas = null;
scene = null;
}
public void render(){
view.shoot();
}
public BufferedImage screenshot(){
return canvas.screenshot();
}
public void updateProjectionsAndRender(){
getView().shoot();
getView().project();
render();
}
/**************************************************************/
/** Add a {@link ChartCameraController} to this {@link Chart}.
* Warning: the {@link Chart} is not the owner of the controller. Disposing
* the chart thus just unregisters the controllers, but does not handle
* stopping and disposing controllers.
*/
public void addController(ChartCameraController controller){
controller.addTarget(this);
controllers.add(controller);
}
public void removeController(ChartCameraController controller){
controller.removeTarget(this);
controllers.remove(controller);
}
protected void clearControllerList(){
for(ChartCameraController controller: controllers)
controller.removeTarget(this);
controllers.clear();
}
public void addDrawable(AbstractDrawable drawable){
getScene().getGraph().add(drawable);
}
public void addDrawable(AbstractDrawable drawable, boolean updateViews){
getScene().getGraph().add(drawable, updateViews);
}
public void addDrawable(List<? extends AbstractDrawable> drawables, boolean updateViews){
getScene().getGraph().add(drawables, updateViews);
}
public void addDrawable(List<? extends AbstractDrawable> drawables){
getScene().getGraph().add(drawables);
}
public void removeDrawable(AbstractDrawable drawable){
getScene().getGraph().remove(drawable);
}
public void removeDrawable(AbstractDrawable drawable, boolean updateViews){
getScene().getGraph().remove(drawable, updateViews);
}
public void addRenderer(Renderer2d renderer2d){
view.addRenderer2d(renderer2d);
}
public void removeRenderer(Renderer2d renderer2d){
view.removeRenderer2d(renderer2d);
}
public ChartView getView(){
return view;
}
public ChartScene getScene(){
return scene;
}
public ICanvas getCanvas(){
return canvas;
}
public IAxeLayout getAxeLayout(){
return getView().getAxe().getLayout();
}
public void setAxeDisplayed(boolean status){
view.setAxeBoxDisplayed(status);
view.shoot();
}
/**************************************************************************************/
public void setViewPoint(Coord3d viewPoint){
view.setViewPoint(viewPoint);
view.shoot();
}
public Coord3d getViewPoint(){
return view.getViewPoint();
}
/******************************************************************/
public void setViewMode(ViewPositionMode mode){
// Store current view mode and view point in memory
ViewPositionMode previous = view.getViewMode();
if(previous==ViewPositionMode.FREE)
previousViewPointFree = view.getViewPoint();
else if(previous==ViewPositionMode.TOP)
previousViewPointTop = view.getViewPoint();
else if(previous==ViewPositionMode.PROFILE)
previousViewPointProfile = view.getViewPoint();
// Set new view mode and former view point
view.setViewPositionMode(mode);
if(mode==ViewPositionMode.FREE)
view.setViewPoint( previousViewPointFree==null ? View.DEFAULT_VIEW.clone() : previousViewPointFree );
else if(mode==ViewPositionMode.TOP)
view.setViewPoint( previousViewPointTop==null ? View.DEFAULT_VIEW.clone() : previousViewPointTop );
else if(mode==ViewPositionMode.PROFILE)
view.setViewPoint( previousViewPointProfile==null ? View.DEFAULT_VIEW.clone() : previousViewPointProfile );
view.shoot();
}
public ViewPositionMode getViewMode(){
return view.getViewMode();
}
/******************************************************************/
public void setScale(org.jzy3d.maths.Scale scale, boolean notify){
view.setScale(scale, notify);
}
public void setScale(Scale scale){
setScale(scale, true);
}
public Scale getScale() {
return new Scale(view.getBounds().getZmin(), view.getBounds().getZmax());
}
public float flip(float y){
return canvas.getRendererHeight() - y;
}
/******************************************************************/
protected ChartScene scene;
protected ChartView view;
protected ICanvas canvas;
protected Coord3d previousViewPointFree;
protected Coord3d previousViewPointTop;
protected Coord3d previousViewPointProfile;
protected ArrayList<ChartCameraController> controllers;
}
| |
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote.merkletree;
import build.bazel.remote.execution.v2.Digest;
import build.bazel.remote.execution.v2.Directory;
import build.bazel.remote.execution.v2.DirectoryNode;
import build.bazel.remote.execution.v2.FileNode;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.MetadataProvider;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.SilentCloseable;
import com.google.devtools.build.lib.remote.util.DigestUtil;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
/** A merkle tree representation as defined by the remote execution api. */
public class MerkleTree {
/** A path or contents */
public static class PathOrBytes {
private final Path path;
private final ByteString bytes;
public PathOrBytes(Path path) {
this.path = Preconditions.checkNotNull(path, "path");
this.bytes = null;
}
public PathOrBytes(ByteString bytes) {
this.bytes = Preconditions.checkNotNull(bytes, "bytes");
this.path = null;
}
@Nullable
public Path getPath() {
return path;
}
@Nullable
public ByteString getBytes() {
return bytes;
}
}
private final Map<Digest, Directory> digestDirectoryMap;
private final Map<Digest, PathOrBytes> digestFileMap;
private final Digest rootDigest;
private final long inputFiles;
private final long inputBytes;
private MerkleTree(
Map<Digest, Directory> digestDirectoryMap,
Map<Digest, PathOrBytes> digestFileMap,
Digest rootDigest,
long inputFiles,
long inputBytes) {
this.digestDirectoryMap = digestDirectoryMap;
this.digestFileMap = digestFileMap;
this.rootDigest = rootDigest;
this.inputFiles = inputFiles;
this.inputBytes = inputBytes;
}
/** Returns the digest of the merkle tree's root. */
public Digest getRootDigest() {
return rootDigest;
}
/** Returns the number of files represented by this merkle tree */
public long getInputFiles() {
return inputFiles;
}
/** Returns the sum of file sizes plus protobuf sizes used to represent this merkle tree */
public long getInputBytes() {
return inputBytes;
}
@Nullable
public Directory getDirectoryByDigest(Digest digest) {
return digestDirectoryMap.get(digest);
}
@Nullable
public PathOrBytes getFileByDigest(Digest digest) {
return digestFileMap.get(digest);
}
/**
* Returns the hashes of all nodes and leafs of the merkle tree. That is, the hashes of the {@link
* Directory} protobufs and {@link ActionInput} files.
*/
public Iterable<Digest> getAllDigests() {
return Iterables.concat(digestDirectoryMap.keySet(), digestFileMap.keySet());
}
/**
* Constructs a merkle tree from a lexicographically sorted map of inputs (files).
*
* @param inputs a map of path to input. The map is required to be sorted lexicographically by
* paths. Inputs of type tree artifacts are not supported and are expected to have been
* expanded before.
* @param metadataProvider provides metadata for all {@link ActionInput}s in {@code inputs}, as
* well as any {@link ActionInput}s being discovered via directory expansion.
* @param execRoot all paths in {@code inputs} need to be relative to this {@code execRoot}.
* @param digestUtil a hashing utility
*/
public static MerkleTree build(
SortedMap<PathFragment, ActionInput> inputs,
MetadataProvider metadataProvider,
Path execRoot,
DigestUtil digestUtil)
throws IOException {
try (SilentCloseable c = Profiler.instance().profile("MerkleTree.build(ActionInput)")) {
DirectoryTree tree =
DirectoryTreeBuilder.fromActionInputs(inputs, metadataProvider, execRoot, digestUtil);
return build(tree, digestUtil);
}
}
/**
* Constructs a merkle tree from a lexicographically sorted map of files.
*
* @param inputFiles a map of path to files. The map is required to be sorted lexicographically by
* paths.
* @param digestUtil a hashing utility
*/
public static MerkleTree build(SortedMap<PathFragment, Path> inputFiles, DigestUtil digestUtil)
throws IOException {
try (SilentCloseable c = Profiler.instance().profile("MerkleTree.build(Path)")) {
DirectoryTree tree = DirectoryTreeBuilder.fromPaths(inputFiles, digestUtil);
return build(tree, digestUtil);
}
}
private static MerkleTree build(DirectoryTree tree, DigestUtil digestUtil) {
Preconditions.checkNotNull(tree);
if (tree.isEmpty()) {
return new MerkleTree(
ImmutableMap.of(), ImmutableMap.of(), digestUtil.compute(new byte[0]), 0, 0);
}
Map<Digest, Directory> digestDirectoryMap =
Maps.newHashMapWithExpectedSize(tree.numDirectories());
Map<Digest, PathOrBytes> digestPathMap = Maps.newHashMapWithExpectedSize(tree.numFiles());
Map<PathFragment, Digest> m = new HashMap<>();
AtomicLong inputBytes = new AtomicLong(0);
tree.visit(
(dirname, files, dirs) -> {
Directory.Builder b = Directory.newBuilder();
for (DirectoryTree.FileNode file : files) {
b.addFiles(buildProto(file));
digestPathMap.put(file.getDigest(), toPathOrBytes(file));
inputBytes.addAndGet(file.getDigest().getSizeBytes());
}
for (DirectoryTree.DirectoryNode dir : dirs) {
PathFragment subDirname = dirname.getRelative(dir.getPathSegment());
Digest protoDirDigest =
Preconditions.checkNotNull(m.remove(subDirname), "protoDirDigest was null");
b.addDirectories(buildProto(dir, protoDirDigest));
inputBytes.addAndGet(protoDirDigest.getSizeBytes());
}
Directory protoDir = b.build();
Digest protoDirDigest = digestUtil.compute(protoDir);
digestDirectoryMap.put(protoDirDigest, protoDir);
m.put(dirname, protoDirDigest);
});
Digest rootDigest = m.get(PathFragment.EMPTY_FRAGMENT);
inputBytes.addAndGet(rootDigest.getSizeBytes());
return new MerkleTree(
digestDirectoryMap, digestPathMap, rootDigest, tree.numFiles(), inputBytes.get());
}
private static FileNode buildProto(DirectoryTree.FileNode file) {
return FileNode.newBuilder()
.setName(file.getPathSegment())
.setDigest(file.getDigest())
.setIsExecutable(true)
.build();
}
private static DirectoryNode buildProto(DirectoryTree.DirectoryNode dir, Digest protoDirDigest) {
return DirectoryNode.newBuilder()
.setName(dir.getPathSegment())
.setDigest(protoDirDigest)
.build();
}
private static PathOrBytes toPathOrBytes(DirectoryTree.FileNode file) {
return file.getPath() != null
? new PathOrBytes(file.getPath())
: new PathOrBytes(file.getBytes());
}
}
| |
package com.nordnetab.chcp.main.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Nikolay Demyankov on 21.07.15.
* <p/>
* Helper class to work with file system.
*/
public class FilesUtility {
/**
* Delete object at the given location.
* If it is a folder - it will be deleted recursively will all content.
*
* @param pathToFileOrDirectory absolute path to the file/directory.
*/
public static void delete(String pathToFileOrDirectory) {
delete(new File(pathToFileOrDirectory));
}
/**
* Delete file object.
* If it is a folder - it will be deleted recursively will all content.
*
* @param fileOrDirectory file/directory to delete
*/
public static void delete(File fileOrDirectory) {
if (!fileOrDirectory.exists()) {
return;
}
if (fileOrDirectory.isDirectory()) {
File[] filesList = fileOrDirectory.listFiles();
for (File child : filesList) {
delete(child);
}
}
final File to = new File(fileOrDirectory.getAbsolutePath() + System.currentTimeMillis());
fileOrDirectory.renameTo(to);
to.delete();
//fileOrDirectory.delete();
}
/**
* Check if folder exists at the given path.
* If not - it will be created with with all subdirectories.
*
* @param dirPath absolute path to the directory
*/
public static void ensureDirectoryExists(String dirPath) {
ensureDirectoryExists(new File(dirPath));
}
/**
* Check if folder exists.
* If not - it will be created with with all subdirectories.
*
* @param dir file object
*/
public static void ensureDirectoryExists(File dir) {
if (dir != null && (!dir.exists() || !dir.isDirectory())) {
dir.mkdirs();
}
}
/**
* Copy object from one place to another.
* Can be used to copy file to file, or folder to folder.
*
* @param src absolute path to source object
* @param dst absolute path to destination object
* @throws IOException
*/
public static void copy(String src, String dst) throws IOException {
copy(new File(src), new File(dst));
}
/**
* Copy file object from one place to another.
* Can be used to copy file to file, or folder to folder.
*
* @param src source file
* @param dst destination file
* @throws IOException
*/
public static void copy(File src, File dst) throws IOException {
if (src.isDirectory()) {
ensureDirectoryExists(dst);
String[] filesList = src.list();
for (String file : filesList) {
File srcFile = new File(src, file);
File destFile = new File(dst, file);
copy(srcFile, destFile);
}
} else {
copyFile(src, dst);
}
}
private static void copyFile(File fromFile, File toFile) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(fromFile));
OutputStream out = new BufferedOutputStream(new FileOutputStream(toFile));
// Transfer bytes from in to out
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Read data as string from the provided file.
*
* @param filePath absolute path to the file
* @return data from file
* @throws IOException
*/
public static String readFromFile(String filePath) throws IOException {
return readFromFile(new File(filePath));
}
/**
* Read data as string from the provided file.
*
* @param file file to read from
* @return data from file
* @throws IOException
*/
public static String readFromFile(File file) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder content = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line).append("\n");
}
bufferedReader.close();
return content.toString().trim();
}
/**
* Save string into the file
*
* @param content data to store
* @param filePath absolute path to file
* @throws IOException
*/
public static void writeToFile(String content, String filePath) throws IOException {
writeToFile(content, new File(filePath));
}
/**
* Save string into the file
*
* @param content data to store
* @param dstFile where to save
* @throws IOException
*/
public static void writeToFile(String content, File dstFile) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(dstFile, false));
bufferedWriter.write(content);
bufferedWriter.close();
}
/**
* Calculate MD5 hash of the file at the given path
*
* @param filePath absolute path to the file
* @return calculated hash
* @throws Exception
* @see MD5
*/
public static String calculateFileHash(String filePath) throws Exception {
return calculateFileHash(new File(filePath));
}
/**
* Calculate MD5 hash of the file
*
* @param file file whose hash we need
* @return calculated hash
* @throws Exception
* @see MD5
*/
public static String calculateFileHash(File file) throws Exception {
MD5 md5 = new MD5();
InputStream in = new BufferedInputStream(new FileInputStream(file));
int len;
byte[] buff = new byte[8192];
while ((len = in.read(buff)) > 0) {
md5.write(buff, len);
}
return md5.calculateHash();
}
}
| |
package org.apereo.cas.authentication;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.credential.HttpBasedServiceCredential;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.metadata.BasicCredentialMetaData;
import org.apereo.cas.authentication.principal.DefaultPrincipalElectionStrategy;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceAccessStrategy;
import org.apereo.cas.services.RegisteredServiceAuthenticationPolicy;
import org.apereo.cas.util.CollectionUtils;
import lombok.experimental.UtilityClass;
import lombok.val;
import org.apereo.services.persondir.support.StubPersonAttributeDao;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mockito.Mockito.*;
/**
* @author Scott Battaglia
* @since 3.0.0.2
*/
@UtilityClass
public class CoreAuthenticationTestUtils {
public static final String CONST_USERNAME = "test";
public static final String CONST_TEST_URL = "https://google.com";
public static final String CONST_GOOD_URL = "https://github.com/";
private static final String CONST_PASSWORD = "test1";
public static UsernamePasswordCredential getCredentialsWithSameUsernameAndPassword() {
return getCredentialsWithSameUsernameAndPassword(CONST_USERNAME);
}
public static UsernamePasswordCredential getCredentialsWithSameUsernameAndPassword(final String username) {
return getCredentialsWithDifferentUsernameAndPassword(username, username);
}
public static UsernamePasswordCredential getCredentialsWithDifferentUsernameAndPassword() {
return getCredentialsWithDifferentUsernameAndPassword(CONST_USERNAME, CONST_PASSWORD);
}
public static UsernamePasswordCredential getCredentialsWithDifferentUsernameAndPassword(final String username, final String password) {
val usernamePasswordCredentials = new UsernamePasswordCredential();
usernamePasswordCredentials.setUsername(username);
usernamePasswordCredentials.setPassword(password);
return usernamePasswordCredentials;
}
public static HttpBasedServiceCredential getHttpBasedServiceCredentials() {
return getHttpBasedServiceCredentials(CONST_GOOD_URL);
}
public static HttpBasedServiceCredential getHttpBasedServiceCredentials(final String url) {
try {
return new HttpBasedServiceCredential(new URL(url), getRegisteredService(url));
} catch (final MalformedURLException e) {
throw new IllegalArgumentException();
}
}
public static Service getService(final String id) {
val svc = mock(Service.class);
lenient().when(svc.getId()).thenReturn(id);
return svc;
}
public static Service getService() {
return getService(CONST_TEST_URL);
}
public static WebApplicationService getWebApplicationService() {
return getWebApplicationService("https://github.com/apereo/cas");
}
public static WebApplicationService getWebApplicationService(final String id) {
val svc = mock(WebApplicationService.class);
when(svc.getId()).thenReturn(id);
when(svc.getOriginalUrl()).thenReturn(id);
when(svc.getSource()).thenReturn(CasProtocolConstants.PARAMETER_SERVICE);
return svc;
}
public static StubPersonAttributeDao getAttributeRepository() {
val attributes = new HashMap<String, List<Object>>();
attributes.put("uid", CollectionUtils.wrap(CONST_USERNAME));
attributes.put("cn", CollectionUtils.wrap(CONST_USERNAME.toUpperCase()));
attributes.put("givenName", CollectionUtils.wrap(CONST_USERNAME));
attributes.put("mail", CollectionUtils.wrap(CONST_USERNAME + "@example.org"));
attributes.put("memberOf", CollectionUtils.wrapList("system", "admin", "cas", "staff"));
return new StubPersonAttributeDao(attributes);
}
public static Map getAttributes() {
return getAttributeRepository().getBackingMap();
}
public static Principal getPrincipal() {
return getPrincipal(CONST_USERNAME);
}
public static Principal getPrincipal(final Map<String, List<Object>> attributes) {
return getPrincipal(CONST_USERNAME, attributes);
}
public static Principal getPrincipal(final String name) {
val backingMap = getAttributeRepository().getBackingMap();
return getPrincipal(name, backingMap);
}
public static Principal getPrincipal(final String name, final Map<String, List<Object>> attributes) {
return PrincipalFactoryUtils.newPrincipalFactory().createPrincipal(name, attributes);
}
public static Authentication getAuthentication() {
return getAuthentication(CONST_USERNAME);
}
public static Authentication getAuthentication(final String name) {
return getAuthentication(getPrincipal(name));
}
public static Authentication getAuthentication(final String name, final Map<String, List<Object>> attributes) {
return getAuthentication(getPrincipal(name), attributes, null);
}
public static Authentication getAuthentication(final String name, final ZonedDateTime authnDate) {
return getAuthentication(getPrincipal(name), new HashMap<>(0), authnDate);
}
public static Authentication getAuthentication(final Principal principal) {
return getAuthentication(principal, new HashMap<>(0));
}
public static Authentication getAuthentication(final Principal principal, final Map<String, List<Object>> attributes) {
return getAuthentication(principal, attributes, null);
}
public static Authentication getAuthentication(final Map<String, List<Object>> authnAttributes) {
return getAuthentication(getPrincipal(CONST_USERNAME), authnAttributes, null);
}
public static Authentication getAuthentication(final Principal principal, final Map<String, List<Object>> attributes, final ZonedDateTime authnDate) {
val handler = new SimpleTestUsernamePasswordAuthenticationHandler();
val meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
return new DefaultAuthenticationBuilder(principal)
.addCredential(meta)
.setAuthenticationDate(authnDate)
.addSuccess(handler.getName(), new DefaultAuthenticationHandlerExecutionResult(handler, meta))
.setAttributes(attributes)
.build();
}
public static RegisteredService getRegisteredService() {
return getRegisteredService(CONST_TEST_URL);
}
public static RegisteredService getRegisteredService(final String url) {
val service = mock(RegisteredService.class);
when(service.getServiceId()).thenReturn(url);
when(service.getName()).thenReturn("service name");
when(service.getId()).thenReturn(Long.MAX_VALUE);
when(service.getDescription()).thenReturn("service description");
val access = mock(RegisteredServiceAccessStrategy.class);
when(access.isServiceAccessAllowed()).thenReturn(true);
when(service.getAccessStrategy()).thenReturn(access);
val authnPolicy = mock(RegisteredServiceAuthenticationPolicy.class);
when(authnPolicy.getRequiredAuthenticationHandlers()).thenReturn(Set.of());
when(service.getAuthenticationPolicy()).thenReturn(authnPolicy);
return service;
}
public static AuthenticationResult getAuthenticationResult(final AuthenticationSystemSupport support, final Service service)
throws AuthenticationException {
return getAuthenticationResult(support, service, getCredentialsWithSameUsernameAndPassword());
}
public static AuthenticationResult getAuthenticationResult(final AuthenticationSystemSupport support) throws AuthenticationException {
return getAuthenticationResult(support, getWebApplicationService(), getCredentialsWithSameUsernameAndPassword());
}
public static AuthenticationResult getAuthenticationResult(final AuthenticationSystemSupport support, final Credential... credentials)
throws AuthenticationException {
return getAuthenticationResult(support, getWebApplicationService(), credentials);
}
public static AuthenticationResult getAuthenticationResult(final AuthenticationSystemSupport support, final Service service,
final Credential... credentials) throws AuthenticationException {
return support.finalizeAuthenticationTransaction(service, credentials);
}
public static AuthenticationResult getAuthenticationResult() throws AuthenticationException {
return getAuthenticationResult(getWebApplicationService(), getAuthentication());
}
public static AuthenticationResult getAuthenticationResult(final Service service) {
return getAuthenticationResult(service, getAuthentication());
}
public static AuthenticationResult getAuthenticationResult(final Authentication authentication) throws AuthenticationException {
return getAuthenticationResult(getWebApplicationService(), authentication);
}
public static AuthenticationResult getAuthenticationResult(final Service service, final Authentication authentication) throws AuthenticationException {
val result = mock(AuthenticationResult.class);
when(result.getAuthentication()).thenReturn(authentication);
when(result.getService()).thenReturn(service);
return result;
}
public static AuthenticationBuilder getAuthenticationBuilder() {
return getAuthenticationBuilder(getPrincipal());
}
public static AuthenticationBuilder getAuthenticationBuilder(final Principal principal) {
val meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
val handler = new SimpleTestUsernamePasswordAuthenticationHandler();
return new DefaultAuthenticationBuilder(principal)
.addCredential(meta)
.addSuccess(handler.getName(), new DefaultAuthenticationHandlerExecutionResult(handler, meta));
}
public static AuthenticationBuilder getAuthenticationBuilder(final Principal principal,
final Map<Credential, ? extends AuthenticationHandler> handlers,
final Map<String, List<Object>> attributes) {
val builder = new DefaultAuthenticationBuilder(principal).setAttributes(attributes);
handlers.forEach((credential, handler) -> {
builder.addSuccess(handler.getName(), new DefaultAuthenticationHandlerExecutionResult(handler, new BasicCredentialMetaData(credential)));
builder.addCredential(new BasicCredentialMetaData(credential));
});
return builder;
}
public static AuthenticationSystemSupport getAuthenticationSystemSupport() {
val authSupport = mock(AuthenticationSystemSupport.class);
when(authSupport.getPrincipalElectionStrategy()).thenReturn(new DefaultPrincipalElectionStrategy());
return authSupport;
}
}
| |
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.util.pattern;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.PathContainer;
import org.springframework.web.util.pattern.PatternParseException.PatternMessage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
/**
* Exercise the {@link PathPatternParser}.
*
* @author Andy Clement
* @author Sam Brannen
*/
public class PathPatternParserTests {
private PathPattern pathPattern;
@Test
public void basicPatterns() {
checkStructure("/");
checkStructure("/foo");
checkStructure("foo");
checkStructure("foo/");
checkStructure("/foo/");
checkStructure("");
}
@Test
public void singleCharWildcardPatterns() {
pathPattern = checkStructure("?");
assertPathElements(pathPattern, SingleCharWildcardedPathElement.class);
checkStructure("/?/");
checkStructure("/?abc?/");
}
@Test
public void multiwildcardPattern() {
pathPattern = checkStructure("/**");
assertPathElements(pathPattern, WildcardTheRestPathElement.class);
// this is not double wildcard, it's / then **acb (an odd, unnecessary use of double *)
pathPattern = checkStructure("/**acb");
assertPathElements(pathPattern, SeparatorPathElement.class, RegexPathElement.class);
}
@Test
public void toStringTests() {
assertThat(checkStructure("/{*foobar}").toChainString()).isEqualTo("CaptureTheRest(/{*foobar})");
assertThat(checkStructure("{foobar}").toChainString()).isEqualTo("CaptureVariable({foobar})");
assertThat(checkStructure("abc").toChainString()).isEqualTo("Literal(abc)");
assertThat(checkStructure("{a}_*_{b}").toChainString()).isEqualTo("Regex({a}_*_{b})");
assertThat(checkStructure("/").toChainString()).isEqualTo("Separator(/)");
assertThat(checkStructure("?a?b?c").toChainString()).isEqualTo("SingleCharWildcarded(?a?b?c)");
assertThat(checkStructure("*").toChainString()).isEqualTo("Wildcard(*)");
assertThat(checkStructure("/**").toChainString()).isEqualTo("WildcardTheRest(/**)");
}
@Test
public void captureTheRestPatterns() {
pathPattern = parse("{*foobar}");
assertThat(pathPattern.computePatternString()).isEqualTo("/{*foobar}");
assertPathElements(pathPattern, CaptureTheRestPathElement.class);
pathPattern = checkStructure("/{*foobar}");
assertPathElements(pathPattern, CaptureTheRestPathElement.class);
checkError("/{*foobar}/", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
checkError("/{*foobar}abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
checkError("/{*f%obar}", 4, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR);
checkError("/{*foobar}abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
checkError("/{f*oobar}", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR);
checkError("/{*foobar}/abc", 10, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
checkError("/{*foobar:.*}/abc", 9, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR);
checkError("/{abc}{*foobar}", 1, PatternMessage.CAPTURE_ALL_IS_STANDALONE_CONSTRUCT);
checkError("/{abc}{*foobar}{foo}", 15, PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
}
@Test
public void equalsAndHashcode() {
PathPatternParser caseInsensitiveParser = new PathPatternParser();
caseInsensitiveParser.setCaseSensitive(false);
PathPatternParser caseSensitiveParser = new PathPatternParser();
PathPattern pp1 = caseInsensitiveParser.parse("/abc");
PathPattern pp2 = caseInsensitiveParser.parse("/abc");
PathPattern pp3 = caseInsensitiveParser.parse("/def");
assertThat(pp2).isEqualTo(pp1);
assertThat(pp2.hashCode()).isEqualTo(pp1.hashCode());
assertThat(pp3).isNotEqualTo(pp1);
pp1 = caseInsensitiveParser.parse("/abc");
pp2 = caseSensitiveParser.parse("/abc");
assertThat(pp1.equals(pp2)).isFalse();
assertThat(pp2.hashCode()).isNotEqualTo(pp1.hashCode());
}
@Test
public void regexPathElementPatterns() {
checkError("/{var:[^/]*}", 8, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("/{var:abc", 8, PatternMessage.MISSING_CLOSE_CAPTURE);
// Do not check the expected position due a change in RegEx parsing in JDK 13.
// See https://github.com/spring-projects/spring-framework/issues/23669
checkError("/{var:a{{1,2}}}", PatternMessage.REGEX_PATTERN_SYNTAX_EXCEPTION);
pathPattern = checkStructure("/{var:\\\\}");
PathElement next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
assertMatches(pathPattern, "/\\");
pathPattern = checkStructure("/{var:\\/}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
assertNoMatch(pathPattern, "/aaa");
pathPattern = checkStructure("/{var:a{1,2}}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
pathPattern = checkStructure("/{var:[^\\/]*}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
PathPattern.PathMatchInfo result = matchAndExtract(pathPattern, "/foo");
assertThat(result.getUriVariables().get("var")).isEqualTo("foo");
pathPattern = checkStructure("/{var:\\[*}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
result = matchAndExtract(pathPattern, "/[[[");
assertThat(result.getUriVariables().get("var")).isEqualTo("[[[");
pathPattern = checkStructure("/{var:[\\{]*}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
result = matchAndExtract(pathPattern, "/{{{");
assertThat(result.getUriVariables().get("var")).isEqualTo("{{{");
pathPattern = checkStructure("/{var:[\\}]*}");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
result = matchAndExtract(pathPattern, "/}}}");
assertThat(result.getUriVariables().get("var")).isEqualTo("}}}");
pathPattern = checkStructure("*");
assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName());
checkStructure("/*");
checkStructure("/*/");
checkStructure("*/");
checkStructure("/*/");
pathPattern = checkStructure("/*a*/");
next = pathPattern.getHeadSection().next;
assertThat(next.getClass().getName()).isEqualTo(RegexPathElement.class.getName());
pathPattern = checkStructure("*/");
assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName());
checkError("{foo}_{foo}", 0, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "foo");
checkError("/{bar}/{bar}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar");
checkError("/{bar}/{bar}_{foo}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar");
pathPattern = checkStructure("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar");
assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName());
}
@Test
public void completeCapturingPatterns() {
pathPattern = checkStructure("{foo}");
assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName());
checkStructure("/{foo}");
checkStructure("/{f}/");
checkStructure("/{foo}/{bar}/{wibble}");
checkStructure("/{mobile-number}"); // gh-23101
}
@Test
public void noEncoding() {
// Check no encoding of expressions or constraints
PathPattern pp = parse("/{var:f o}");
assertThat(pp.toChainString()).isEqualTo("Separator(/) CaptureVariable({var:f o})");
pp = parse("/{var:f o}_");
assertThat(pp.toChainString()).isEqualTo("Separator(/) Regex({var:f o}_)");
pp = parse("{foo:f o}_ _{bar:b\\|o}");
assertThat(pp.toChainString()).isEqualTo("Regex({foo:f o}_ _{bar:b\\|o})");
}
@Test
public void completeCaptureWithConstraints() {
pathPattern = checkStructure("{foo:...}");
assertPathElements(pathPattern, CaptureVariablePathElement.class);
pathPattern = checkStructure("{foo:[0-9]*}");
assertPathElements(pathPattern, CaptureVariablePathElement.class);
checkError("{foo:}", 5, PatternMessage.MISSING_REGEX_CONSTRAINT);
}
@Test
public void partialCapturingPatterns() {
pathPattern = checkStructure("{foo}abc");
assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName());
checkStructure("abc{foo}");
checkStructure("/abc{foo}");
checkStructure("{foo}def/");
checkStructure("/abc{foo}def/");
checkStructure("{foo}abc{bar}");
checkStructure("{foo}abc{bar}/");
checkStructure("/{foo}abc{bar}/");
}
@Test
public void illegalCapturePatterns() {
checkError("{abc/", 4, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("{abc:}/", 5, PatternMessage.MISSING_REGEX_CONSTRAINT);
checkError("{", 1, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("{abc", 4, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("{/}", 1, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("/{", 2, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("}", 0, PatternMessage.MISSING_OPEN_CAPTURE);
checkError("/}", 1, PatternMessage.MISSING_OPEN_CAPTURE);
checkError("def}", 3, PatternMessage.MISSING_OPEN_CAPTURE);
checkError("/{/}", 2, PatternMessage.MISSING_CLOSE_CAPTURE);
checkError("/{{/}", 2, PatternMessage.ILLEGAL_NESTED_CAPTURE);
checkError("/{abc{/}", 5, PatternMessage.ILLEGAL_NESTED_CAPTURE);
checkError("/{0abc}/abc", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR);
checkError("/{a?bc}/abc", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR);
checkError("/{abc}_{abc}", 1, PatternMessage.ILLEGAL_DOUBLE_CAPTURE);
checkError("/foobar/{abc}_{abc}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE);
checkError("/foobar/{abc:..}_{abc:..}", 8, PatternMessage.ILLEGAL_DOUBLE_CAPTURE);
PathPattern pp = parse("/{abc:foo(bar)}");
assertThatIllegalArgumentException().isThrownBy(() ->
pp.matchAndExtract(toPSC("/foo")))
.withMessage("No capture groups allowed in the constraint regex: foo(bar)");
assertThatIllegalArgumentException().isThrownBy(() ->
pp.matchAndExtract(toPSC("/foobar")))
.withMessage("No capture groups allowed in the constraint regex: foo(bar)");
}
@Test
public void badPatterns() {
// checkError("/{foo}{bar}/",6,PatternMessage.CANNOT_HAVE_ADJACENT_CAPTURES);
checkError("/{?}/", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "?");
checkError("/{a?b}/", 3, PatternMessage.ILLEGAL_CHARACTER_IN_CAPTURE_DESCRIPTOR, "?");
checkError("/{%%$}", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "%");
checkError("/{ }", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, " ");
checkError("/{%:[0-9]*}", 2, PatternMessage.ILLEGAL_CHARACTER_AT_START_OF_CAPTURE_DESCRIPTOR, "%");
}
@Test
public void patternPropertyGetCaptureCountTests() {
// Test all basic section types
assertThat(parse("{foo}").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("foo").getCapturedVariableCount()).isEqualTo(0);
assertThat(parse("{*foobar}").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("/{*foobar}").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("/**").getCapturedVariableCount()).isEqualTo(0);
assertThat(parse("{abc}asdf").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("{abc}_*").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("{abc}_{def}").getCapturedVariableCount()).isEqualTo(2);
assertThat(parse("/").getCapturedVariableCount()).isEqualTo(0);
assertThat(parse("a?b").getCapturedVariableCount()).isEqualTo(0);
assertThat(parse("*").getCapturedVariableCount()).isEqualTo(0);
// Test on full templates
assertThat(parse("/foo/bar").getCapturedVariableCount()).isEqualTo(0);
assertThat(parse("/{foo}").getCapturedVariableCount()).isEqualTo(1);
assertThat(parse("/{foo}/{bar}").getCapturedVariableCount()).isEqualTo(2);
assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getCapturedVariableCount()).isEqualTo(4);
}
@Test
public void patternPropertyGetWildcardCountTests() {
// Test all basic section types
assertThat(parse("{foo}").getScore()).isEqualTo(computeScore(1, 0));
assertThat(parse("foo").getScore()).isEqualTo(computeScore(0, 0));
assertThat(parse("{*foobar}").getScore()).isEqualTo(computeScore(0, 0));
// assertEquals(1,parse("/**").getScore());
assertThat(parse("{abc}asdf").getScore()).isEqualTo(computeScore(1, 0));
assertThat(parse("{abc}_*").getScore()).isEqualTo(computeScore(1, 1));
assertThat(parse("{abc}_{def}").getScore()).isEqualTo(computeScore(2, 0));
assertThat(parse("/").getScore()).isEqualTo(computeScore(0, 0));
// currently deliberate
assertThat(parse("a?b").getScore()).isEqualTo(computeScore(0, 0));
assertThat(parse("*").getScore()).isEqualTo(computeScore(0, 1));
// Test on full templates
assertThat(parse("/foo/bar").getScore()).isEqualTo(computeScore(0, 0));
assertThat(parse("/{foo}").getScore()).isEqualTo(computeScore(1, 0));
assertThat(parse("/{foo}/{bar}").getScore()).isEqualTo(computeScore(2, 0));
assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 0));
assertThat(parse("/{foo}/*/*_*/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 3));
}
@Test
public void multipleSeparatorPatterns() {
pathPattern = checkStructure("///aaa");
assertThat(pathPattern.getNormalizedLength()).isEqualTo(6);
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, LiteralPathElement.class);
pathPattern = checkStructure("///aaa////aaa/b");
assertThat(pathPattern.getNormalizedLength()).isEqualTo(15);
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class,
LiteralPathElement.class, SeparatorPathElement.class, LiteralPathElement.class);
pathPattern = checkStructure("/////**");
assertThat(pathPattern.getNormalizedLength()).isEqualTo(5);
assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class,
SeparatorPathElement.class, SeparatorPathElement.class, WildcardTheRestPathElement.class);
}
@Test
public void patternPropertyGetLengthTests() {
// Test all basic section types
assertThat(parse("{foo}").getNormalizedLength()).isEqualTo(1);
assertThat(parse("foo").getNormalizedLength()).isEqualTo(3);
assertThat(parse("{*foobar}").getNormalizedLength()).isEqualTo(1);
assertThat(parse("/{*foobar}").getNormalizedLength()).isEqualTo(1);
assertThat(parse("/**").getNormalizedLength()).isEqualTo(1);
assertThat(parse("{abc}asdf").getNormalizedLength()).isEqualTo(5);
assertThat(parse("{abc}_*").getNormalizedLength()).isEqualTo(3);
assertThat(parse("{abc}_{def}").getNormalizedLength()).isEqualTo(3);
assertThat(parse("/").getNormalizedLength()).isEqualTo(1);
assertThat(parse("a?b").getNormalizedLength()).isEqualTo(3);
assertThat(parse("*").getNormalizedLength()).isEqualTo(1);
// Test on full templates
assertThat(parse("/foo/bar").getNormalizedLength()).isEqualTo(8);
assertThat(parse("/{foo}").getNormalizedLength()).isEqualTo(2);
assertThat(parse("/{foo}/{bar}").getNormalizedLength()).isEqualTo(4);
assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getNormalizedLength()).isEqualTo(16);
}
@Test
public void compareTests() {
PathPattern p1, p2, p3;
// Based purely on number of captures
p1 = parse("{a}");
p2 = parse("{a}/{b}");
p3 = parse("{a}/{b}/{c}");
// Based on number of captures
assertThat(p1.compareTo(p2)).isEqualTo(-1);
List<PathPattern> patterns = new ArrayList<>();
patterns.add(p2);
patterns.add(p3);
patterns.add(p1);
Collections.sort(patterns);
assertThat(patterns.get(0)).isEqualTo(p1);
// Based purely on length
p1 = parse("/a/b/c");
p2 = parse("/a/boo/c/doo");
p3 = parse("/asdjflaksjdfjasdf");
assertThat(p1.compareTo(p2)).isEqualTo(1);
patterns = new ArrayList<>();
patterns.add(p2);
patterns.add(p3);
patterns.add(p1);
Collections.sort(patterns);
assertThat(patterns.get(0)).isEqualTo(p3);
// Based purely on 'wildness'
p1 = parse("/*");
p2 = parse("/*/*");
p3 = parse("/*/*/*_*");
assertThat(p1.compareTo(p2)).isEqualTo(-1);
patterns = new ArrayList<>();
patterns.add(p2);
patterns.add(p3);
patterns.add(p1);
Collections.sort(patterns);
assertThat(patterns.get(0)).isEqualTo(p1);
// Based purely on catchAll
p1 = parse("{*foobar}");
p2 = parse("{*goo}");
assertThat(p1.compareTo(p2) != 0).isTrue();
p1 = parse("/{*foobar}");
p2 = parse("/abc/{*ww}");
assertThat(p1.compareTo(p2)).isEqualTo(+1);
assertThat(p2.compareTo(p1)).isEqualTo(-1);
p3 = parse("/this/that/theother");
assertThat(p1.isCatchAll()).isTrue();
assertThat(p2.isCatchAll()).isTrue();
assertThat(p3.isCatchAll()).isFalse();
patterns = new ArrayList<>();
patterns.add(p2);
patterns.add(p3);
patterns.add(p1);
Collections.sort(patterns);
assertThat(patterns.get(0)).isEqualTo(p3);
assertThat(patterns.get(1)).isEqualTo(p2);
}
@Test
public void captureTheRestWithinPatternNotSupported() {
PathPatternParser parser = new PathPatternParser();
assertThatThrownBy(() -> parser.parse("/resources/**/details"))
.isInstanceOf(PatternParseException.class)
.extracting("messageType").isEqualTo(PatternMessage.NO_MORE_DATA_EXPECTED_AFTER_CAPTURE_THE_REST);
}
@Test
public void separatorTests() {
PathPatternParser parser = new PathPatternParser();
parser.setPathOptions(PathContainer.Options.create('.', false));
String rawPattern = "first.second.{last}";
PathPattern pattern = parser.parse(rawPattern);
assertThat(pattern.computePatternString()).isEqualTo(rawPattern);
}
private PathPattern parse(String pattern) {
PathPatternParser patternParser = new PathPatternParser();
return patternParser.parse(pattern);
}
/**
* Verify the pattern string computed for a parsed pattern matches the original pattern text
*/
private PathPattern checkStructure(String pattern) {
PathPattern pp = parse(pattern);
assertThat(pp.computePatternString()).isEqualTo(pattern);
return pp;
}
/**
* Delegates to {@link #checkError(String, int, PatternMessage, String...)},
* passing {@code -1} as the {@code expectedPos}.
* @since 5.2
*/
private void checkError(String pattern, PatternMessage expectedMessage, String... expectedInserts) {
checkError(pattern, -1, expectedMessage, expectedInserts);
}
/**
* @param expectedPos the expected position, or {@code -1} if the position should not be checked
*/
private void checkError(String pattern, int expectedPos, PatternMessage expectedMessage,
String... expectedInserts) {
assertThatExceptionOfType(PatternParseException.class)
.isThrownBy(() -> pathPattern = parse(pattern))
.satisfies(ex -> {
if (expectedPos >= 0) {
assertThat(ex.getPosition()).as(ex.toDetailedString()).isEqualTo(expectedPos);
}
assertThat(ex.getMessageType()).as(ex.toDetailedString()).isEqualTo(expectedMessage);
if (expectedInserts.length != 0) {
assertThat(ex.getInserts()).isEqualTo(expectedInserts);
}
});
}
@SafeVarargs
private final void assertPathElements(PathPattern p, Class<? extends PathElement>... sectionClasses) {
PathElement head = p.getHeadSection();
for (Class<? extends PathElement> sectionClass : sectionClasses) {
if (head == null) {
fail("Ran out of data in parsed pattern. Pattern is: " + p.toChainString());
}
assertThat(head.getClass().getSimpleName()).as("Not expected section type. Pattern is: " + p.toChainString()).isEqualTo(sectionClass.getSimpleName());
head = head.next;
}
}
// Mirrors the score computation logic in PathPattern
private int computeScore(int capturedVariableCount, int wildcardCount) {
return capturedVariableCount + wildcardCount * 100;
}
private void assertMatches(PathPattern pp, String path) {
assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isTrue();
}
private void assertNoMatch(PathPattern pp, String path) {
assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isFalse();
}
private PathPattern.PathMatchInfo matchAndExtract(PathPattern pp, String path) {
return pp.matchAndExtract(PathPatternTests.toPathContainer(path));
}
private PathContainer toPSC(String path) {
return PathPatternTests.toPathContainer(path);
}
}
| |
/**********************************************************************
Copyright (c) 2005 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.jpox.samples.identity.application;
import java.io.Serializable;
import java.util.StringTokenizer;
import javax.jdo.InstanceCallbacks;
import org.datanucleus.tests.TestObject;
/**
* Class with identity using fields of types int, String, Double.
* @version $Revision: 1.1 $
*/
public class ComposedMixedIDBase extends TestObject implements InstanceCallbacks
{
private int code; // PK
private String composed; // PK
private Double doubleObjField; // PK
private String name;
private String description;
public String getComposed()
{
return composed;
}
public void setComposed(String composed)
{
this.composed = composed;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Double getDoubleObjField()
{
return doubleObjField;
}
public void setDoubleObjField(Double double1)
{
doubleObjField = double1;
}
public void jdoPostLoad()
{
}
public void jdoPreStore()
{
}
public void jdoPreClear()
{
}
public void jdoPreDelete()
{
}
public void fillRandom()
{
code = r.nextInt(50000);
composed = "LONG COMPOSED KEY random number: " + String.valueOf(r.nextInt() * 1000);
doubleObjField = new Double(r.nextInt(10000));
fillUpdateRandom();
}
public void fillUpdateRandom()
{
name = String.valueOf(r.nextDouble() * 1000);
description = "Description " + this.getClass().toString() + " random: " + String.valueOf(r.nextDouble() * 1000);
}
public boolean compareTo(Object obj)
{
if (obj == this)
return true;
if (!(obj instanceof ComposedMixedIDBase))
return false;
ComposedMixedIDBase other = (ComposedMixedIDBase)obj;
return code == other.code
&& name.equals(other.name)
&& composed.equals(other.composed)
&& description.equals(other.description)
&& doubleObjField.compareTo(other.doubleObjField)==0;
}
public String toString()
{
StringBuffer s = new StringBuffer(super.toString());
s.append(" code = ").append(code);
s.append('\n');
s.append(" name = ").append(name);
s.append('\n');
s.append(" composed = ").append(composed);
s.append('\n');
s.append(" description = ").append(description);
s.append('\n');
s.append(" doubleObjField = ").append(doubleObjField);
s.append('\n');
return s.toString();
}
public static class Key implements Serializable
{
public int code;
public String composed;
public Double doubleObjField;
public Key ()
{
}
public Key (String str)
{
StringTokenizer toke = new StringTokenizer (str, "::");
str = toke.nextToken ();
this.code = Integer.parseInt (str);
str = toke.nextToken ();
this.composed = str;
str = toke.nextToken ();
this.doubleObjField = new Double(Double.parseDouble(str));
}
public boolean equals (Object obj)
{
if (obj == this)
{
return true;
}
if (!(obj instanceof Key))
{
return false;
}
Key c = (Key)obj;
return code == c.code
&& composed.equals(c.composed)
&& doubleObjField.compareTo(c.doubleObjField)==0;
}
public int hashCode()
{
return this.code ^ this.composed.hashCode() ^ doubleObjField.hashCode();
}
public String toString()
{
return String.valueOf (this.code) + "::" + String.valueOf (this.composed) + "::" + String.valueOf (this.doubleObjField.doubleValue());
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.core.query;
import java.util.*;
import com.glaf.core.query.DataQuery;
public class ServerEntityQuery extends DataQuery {
private static final long serialVersionUID = 1L;
protected List<Long> serverEntityIds;
protected Collection<String> appActorIds;
protected Long nodeId;
protected List<Long> nodeIds;
protected String titleLike;
protected String code;
protected String host;
protected String hostLike;
protected String type;
protected List<String> types;
protected String active;
protected String detectionFlag;
protected String initFlag;
protected String verify;
protected Date createTimeGreaterThanOrEqual;
protected Date createTimeLessThanOrEqual;
public ServerEntityQuery() {
}
public ServerEntityQuery active(String active) {
if (active == null) {
throw new RuntimeException("active is null");
}
this.active = active;
return this;
}
public ServerEntityQuery code(String code) {
if (code == null) {
throw new RuntimeException("code is null");
}
this.code = code;
return this;
}
public ServerEntityQuery detectionFlag(String detectionFlag) {
if (detectionFlag == null) {
throw new RuntimeException("detectionFlag is null");
}
this.detectionFlag = detectionFlag;
return this;
}
public String getActive() {
return active;
}
public Collection<String> getAppActorIds() {
return appActorIds;
}
public String getCode() {
return code;
}
public Date getCreateTimeGreaterThanOrEqual() {
return createTimeGreaterThanOrEqual;
}
public Date getCreateTimeLessThanOrEqual() {
return createTimeLessThanOrEqual;
}
public String getDetectionFlag() {
return detectionFlag;
}
public String getHost() {
return host;
}
public String getHostLike() {
if (hostLike != null && hostLike.trim().length() > 0) {
if (!hostLike.startsWith("%")) {
hostLike = "%" + hostLike;
}
if (!hostLike.endsWith("%")) {
hostLike = hostLike + "%";
}
}
return hostLike;
}
public String getInitFlag() {
return initFlag;
}
public Long getNodeId() {
return nodeId;
}
public List<Long> getNodeIds() {
return nodeIds;
}
public String getOrderBy() {
if (sortColumn != null) {
String a_x = " asc ";
if (sortOrder != null) {
a_x = sortOrder;
}
if ("nodeId".equals(sortColumn)) {
orderBy = "E.NODEID_" + a_x;
}
if ("host".equals(sortColumn)) {
orderBy = "E.HOST_" + a_x;
}
if ("port".equals(sortColumn)) {
orderBy = "E.PORT_" + a_x;
}
if ("user".equals(sortColumn)) {
orderBy = "E.USER_" + a_x;
}
if ("password".equals(sortColumn)) {
orderBy = "E.PASSWORD_" + a_x;
}
if ("path".equals(sortColumn)) {
orderBy = "E.PATH_" + a_x;
}
if ("type".equals(sortColumn)) {
orderBy = "E.TYPE_" + a_x;
}
if ("connectionString".equals(sortColumn)) {
orderBy = "E.CONNECTIONSTRING_" + a_x;
}
if ("active".equals(sortColumn)) {
orderBy = "E.ACTIVE_" + a_x;
}
}
return orderBy;
}
public List<Long> getServerEntityIds() {
return serverEntityIds;
}
public String getTitleLike() {
if (titleLike != null && titleLike.trim().length() > 0) {
if (!titleLike.startsWith("%")) {
titleLike = "%" + titleLike;
}
if (!titleLike.endsWith("%")) {
titleLike = titleLike + "%";
}
}
return titleLike;
}
public String getType() {
return type;
}
public List<String> getTypes() {
return types;
}
public String getVerify() {
return verify;
}
public ServerEntityQuery host(String host) {
if (host == null) {
throw new RuntimeException("host is null");
}
this.host = host;
return this;
}
public ServerEntityQuery hostLike(String hostLike) {
if (hostLike == null) {
throw new RuntimeException("host is null");
}
this.hostLike = hostLike;
return this;
}
public ServerEntityQuery initFlag(String initFlag) {
if (initFlag == null) {
throw new RuntimeException("initFlag is null");
}
this.initFlag = initFlag;
return this;
}
@Override
public void initQueryColumns() {
super.initQueryColumns();
addColumn("id", "ID_");
addColumn("nodeId", "NODEID_");
addColumn("host", "HOST_");
addColumn("port", "PORT_");
addColumn("user", "USER_");
addColumn("password", "PASSWORD_");
addColumn("path", "PATH_");
addColumn("type", "TYPE_");
addColumn("connectionString", "CONNECTIONSTRING_");
addColumn("active", "ACTIVE_");
}
public ServerEntityQuery nodeId(Long nodeId) {
if (nodeId == null) {
throw new RuntimeException("nodeId is null");
}
this.nodeId = nodeId;
return this;
}
public ServerEntityQuery nodeIds(List<Long> nodeIds) {
if (nodeIds == null) {
throw new RuntimeException("nodeIds is empty ");
}
this.nodeIds = nodeIds;
return this;
}
public void setActive(String active) {
this.active = active;
}
public void setAppActorIds(Collection<String> appActorIds) {
this.appActorIds = appActorIds;
}
public void setCode(String code) {
this.code = code;
}
public void setCreateTimeGreaterThanOrEqual(Date createTimeGreaterThanOrEqual) {
this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual;
}
public void setCreateTimeLessThanOrEqual(Date createTimeLessThanOrEqual) {
this.createTimeLessThanOrEqual = createTimeLessThanOrEqual;
}
public void setDetectionFlag(String detectionFlag) {
this.detectionFlag = detectionFlag;
}
public void setHost(String host) {
this.host = host;
}
public void setHostLike(String hostLike) {
this.hostLike = hostLike;
}
public void setInitFlag(String initFlag) {
this.initFlag = initFlag;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public void setNodeIds(List<Long> nodeIds) {
this.nodeIds = nodeIds;
}
public void setServerEntityIds(List<Long> serverEntityIds) {
this.serverEntityIds = serverEntityIds;
}
public void setTitleLike(String titleLike) {
this.titleLike = titleLike;
}
public void setType(String type) {
this.type = type;
}
public void setTypes(List<String> types) {
this.types = types;
}
public void setVerify(String verify) {
this.verify = verify;
}
public ServerEntityQuery type(String type) {
if (type == null) {
throw new RuntimeException("type is null");
}
this.type = type;
return this;
}
public ServerEntityQuery types(List<String> types) {
if (types == null) {
throw new RuntimeException("types is empty ");
}
this.types = types;
return this;
}
public ServerEntityQuery verify(String verify) {
if (verify == null) {
throw new RuntimeException("verify is null");
}
this.verify = verify;
return this;
}
}
| |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.dmrclient;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
public class AddressTest extends Address {
@Test
public void testGetAddressParts() {
Address addr = Address.parse("/");
Assert.assertEquals(0, addr.toAddressParts().length);
addr = Address.parse("/one=two");
Assert.assertEquals(2, addr.toAddressParts().length);
Assert.assertEquals("one", addr.toAddressParts()[0]);
Assert.assertEquals("two", addr.toAddressParts()[1]);
addr = Address.parse("/one=two/three=four");
Assert.assertEquals(4, addr.toAddressParts().length);
Assert.assertEquals("one", addr.toAddressParts()[0]);
Assert.assertEquals("two", addr.toAddressParts()[1]);
Assert.assertEquals("three", addr.toAddressParts()[2]);
Assert.assertEquals("four", addr.toAddressParts()[3]);
}
@Test
public void testAddAddress() {
Address addrA = Address.parse("/one=two");
Address addrB = Address.parse("/three=four");
Address addrAB = addrA.add(addrB);
Assert.assertEquals("/one=two/three=four", addrAB.toAddressPathString());
addrA = Address.parse("/one=two/three=four");
addrB = Address.parse("/five=six/seven=eight");
addrAB = addrA.add(addrB);
Assert.assertEquals("/one=two/three=four/five=six/seven=eight", addrAB.toAddressPathString());
addrA = Address.parse("/one=two/three=four");
addrB = Address.root();
addrAB = addrA.add(addrB);
Assert.assertEquals("/one=two/three=four", addrAB.toAddressPathString());
addrA = Address.root();
addrB = Address.parse("/one=two/three=four");
addrAB = addrA.add(addrB);
Assert.assertEquals("/one=two/three=four", addrAB.toAddressPathString());
}
@Test
public void testAddressFromModelNode() {
ModelNode node;
Assert.assertEquals("/", Address.fromModelNode(new ModelNode()).toAddressPathString());
StringBuilder addrStr = new StringBuilder();
addrStr.append("[");
addrStr.append("(\"deployment\" => \"my-app.ear\"),\n");
addrStr.append("(\"subdeployment\" => \"my-webapp.war\"),\n");
addrStr.append("(\"subsystem\" => \"undertow\")");
addrStr.append("]");
node = ModelNode.fromString(addrStr.toString());
Assert.assertEquals("/deployment=my-app.ear/subdeployment=my-webapp.war/subsystem=undertow",
Address.fromModelNode(node).toAddressPathString());
String addrWrapper = String.format("{ \"one\" => \"1\", \"address\" => %s, \"two\" => \"2\" }", addrStr);
node = ModelNode.fromString(addrWrapper.toString());
Assert.assertEquals("/deployment=my-app.ear/subdeployment=my-webapp.war/subsystem=undertow",
Address.fromModelNodeWrapper(node, "address").toAddressPathString());
try {
Address.fromModelNode(new ModelNode("not-an-address"));
Assert.fail("Should not have been able to use a non-address ModelNode");
} catch (IllegalArgumentException expected) {
}
}
@Test
public void testRootAddress() {
Address addr = Address.root();
assert addr != null;
assert addr.equals(Address.root());
assert addr.getAddressNode().toString().equals("undefined");
assert addr.toString().equals("/");
Address addr2 = Address.root().add("one", "two");
assert addr2 != null;
assert !addr2.equals(addr);
assert addr2.getAddressNode().asList().get(0).get("one").asString().equals("two");
assert addr2.toString().equals("/one=two");
}
@Test
public void testAddress() {
Address addr = Address.root().add("one", "two", "three", "four");
assert addr != null;
assert addr.getAddressNode().asList().get(0).get("one").asString().equals("two");
assert addr.getAddressNode().asList().get(1).get("three").asString().equals("four");
}
@Test
public void testClone() throws CloneNotSupportedException {
Address addr = Address.root().add("one", "two", "three", "four", "five", "six");
Address addr2 = addr.clone();
assert addr2 != null;
assert addr2 != addr; // clone worked, duplicated it, didn't just return the same ref
assert addr2.equals(addr);
assert addr2.hashCode() == addr.hashCode();
}
@Test
public void testParse() {
Address addr = Address.parse("/parent=foo");
assert addr.getAddressNode().asList().size() == 1;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("foo");
addr = Address.parse("/parent=foo/child=bar");
assert addr.getAddressNode().asList().size() == 2;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("foo");
assert addr.getAddressNode().asList().get(1).get("child").asString().equals("bar");
addr = Address.parse("/parent=foo/child=bar/"); // trailing / shouldn't matter
assert addr.getAddressNode().asList().size() == 2;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("foo");
assert addr.getAddressNode().asList().get(1).get("child").asString().equals("bar");
addr = Address.parse("parent=foo/child=bar"); // missing leading / shouldn't matter
assert addr.getAddressNode().asList().size() == 2;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("foo");
assert addr.getAddressNode().asList().get(1).get("child").asString().equals("bar");
addr = Address.parse("/a-b-c=x-y-z/a_b_c=x_y_z"); // special chars in names
assert addr.getAddressNode().asList().size() == 2;
assert addr.getAddressNode().asList().get(0).get("a-b-c").asString().equals("x-y-z");
assert addr.getAddressNode().asList().get(1).get("a_b_c").asString().equals("x_y_z");
addr = Address.parse("/parent"); // partial address
assert addr.getAddressNode().asList().size() == 1;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("");
addr = Address.parse("/parent="); // partial address
assert addr.getAddressNode().asList().size() == 1;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("");
addr = Address.parse("/parent=/child="); // partial addresses (is this even valid DMR?)
assert addr.getAddressNode().asList().size() == 2;
assert addr.getAddressNode().asList().get(0).get("parent").asString().equals("");
assert addr.getAddressNode().asList().get(1).get("child").asString().equals("");
}
@Test
public void testIncompleteAddress() {
try {
Address.root().add("one");
assert false : "The address is unbalanced and should not have been constructed";
} catch (IllegalArgumentException expected) {
}
try {
new Address("one");
assert false : "The address is unbalanced and should not have been constructed";
} catch (IllegalArgumentException expected) {
}
try {
Address.root().add("one", "two", "three");
assert false : "The address is unbalanced and should not have been constructed";
} catch (IllegalArgumentException expected) {
}
try {
new Address("one", "two", "three");
assert false : "The address is unbalanced and should not have been constructed";
} catch (IllegalArgumentException expected) {
}
}
@Test
public void testToAddressPathString() {
Address addr = Address.root();
assert addr.toAddressPathString().equals("/") : addr.toAddressPathString();
addr = Address.root().add("one", "two");
assert addr.toAddressPathString().equals("/one=two") : addr.toAddressPathString();
addr = Address.root().add("one", "two", "three", "four");
assert addr.toAddressPathString().equals("/one=two/three=four") : addr.toAddressPathString();
addr = Address.root().add("one", "two", "three", "four", "5", "6");
assert addr.toAddressPathString().equals("/one=two/three=four/5=6") : addr.toAddressPathString();
}
}
| |
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.localsearch.decider.forager;
import java.util.Random;
import org.junit.Test;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.config.localsearch.decider.forager.LocalSearchPickEarlyType;
import org.optaplanner.core.impl.heuristic.move.DummyMove;
import org.optaplanner.core.impl.localsearch.decider.forager.finalist.HighestScoreFinalistPodium;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchMoveScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope;
import org.optaplanner.core.impl.score.buildin.simple.SimpleScoreDefinition;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.solver.scope.DefaultSolverScope;
import org.optaplanner.core.impl.testdata.domain.TestdataSolution;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class AcceptedForagerTest {
@Test
public void pickMoveMaxScoreAccepted() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.NEVER, Integer.MAX_VALUE, true);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-20), true);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-1), false);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-20), false);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-2), true);
LocalSearchMoveScope e = createMoveScope(stepScope, SimpleScore.valueOf(-300), true);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertFalse(forager.isQuitEarly());
forager.addMove(e);
assertFalse(forager.isQuitEarly());
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
// Post conditions
assertSame(d, pickedScope);
forager.phaseEnded(phaseScope);
}
@Test
public void pickMoveMaxScoreUnaccepted() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.NEVER, Integer.MAX_VALUE, true);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-20), false);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-1), false);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-20), false);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-2), false);
LocalSearchMoveScope e = createMoveScope(stepScope, SimpleScore.valueOf(-300), false);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertFalse(forager.isQuitEarly());
forager.addMove(e);
assertFalse(forager.isQuitEarly());
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
// Post conditions
assertSame(b, pickedScope);
forager.phaseEnded(phaseScope);
}
@Test
public void pickMoveFirstBestScoreImproving() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.FIRST_BEST_SCORE_IMPROVING, Integer.MAX_VALUE, true);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-1), false);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-20), true);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-300), true);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertTrue(forager.isQuitEarly());
// Post conditions
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
assertSame(d, pickedScope);
forager.phaseEnded(phaseScope);
}
@Test
public void pickMoveFirstLastStepScoreImproving() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.FIRST_LAST_STEP_SCORE_IMPROVING, Integer.MAX_VALUE, true);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-1), false);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-300), true);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-4000), true);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-20), true);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertTrue(forager.isQuitEarly());
// Post conditions
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
assertSame(d, pickedScope);
forager.phaseEnded(phaseScope);
}
@Test
public void pickMoveAcceptedBreakTieRandomly() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.NEVER, 4, true);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-20), false);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-20), true);
LocalSearchMoveScope e = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertFalse(forager.isQuitEarly());
forager.addMove(e);
assertTrue(forager.isQuitEarly());
// Post conditions
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
assertSame(c, pickedScope);
forager.phaseEnded(phaseScope);
}
@Test
public void pickMoveAcceptedBreakTieFirst() {
// Setup
Forager forager = new AcceptedForager(new HighestScoreFinalistPodium(),
LocalSearchPickEarlyType.NEVER, 4, false);
LocalSearchPhaseScope phaseScope = createPhaseScope();
forager.phaseStarted(phaseScope);
LocalSearchStepScope stepScope = new LocalSearchStepScope(phaseScope);
forager.stepStarted(stepScope);
// Pre conditions
LocalSearchMoveScope a = createMoveScope(stepScope, SimpleScore.valueOf(-20), false);
LocalSearchMoveScope b = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
LocalSearchMoveScope c = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
LocalSearchMoveScope d = createMoveScope(stepScope, SimpleScore.valueOf(-20), true);
LocalSearchMoveScope e = createMoveScope(stepScope, SimpleScore.valueOf(-1), true);
// Do stuff
forager.addMove(a);
assertFalse(forager.isQuitEarly());
forager.addMove(b);
assertFalse(forager.isQuitEarly());
forager.addMove(c);
assertFalse(forager.isQuitEarly());
forager.addMove(d);
assertFalse(forager.isQuitEarly());
forager.addMove(e);
assertTrue(forager.isQuitEarly());
// Post conditions
LocalSearchMoveScope pickedScope = forager.pickMove(stepScope);
assertSame(b, pickedScope);
forager.phaseEnded(phaseScope);
}
private LocalSearchPhaseScope createPhaseScope() {
DefaultSolverScope solverScope = new DefaultSolverScope();
LocalSearchPhaseScope phaseScope = new LocalSearchPhaseScope(solverScope);
InnerScoreDirector scoreDirector = mock(InnerScoreDirector.class);
when(scoreDirector.getSolutionDescriptor()).thenReturn(TestdataSolution.buildSolutionDescriptor());
when(scoreDirector.getScoreDefinition()).thenReturn(new SimpleScoreDefinition());
solverScope.setScoreDirector(scoreDirector);
Random workingRandom = mock(Random.class);
when(workingRandom.nextInt(3)).thenReturn(1);
solverScope.setWorkingRandom(workingRandom);
solverScope.setBestScore(SimpleScore.valueOf(-10));
LocalSearchStepScope lastLocalSearchStepScope = new LocalSearchStepScope(phaseScope);
lastLocalSearchStepScope.setScore(SimpleScore.valueOf(-100));
phaseScope.setLastCompletedStepScope(lastLocalSearchStepScope);
return phaseScope;
}
public LocalSearchMoveScope createMoveScope(LocalSearchStepScope stepScope, Score score, boolean accepted) {
LocalSearchMoveScope moveScope = new LocalSearchMoveScope(stepScope);
moveScope.setMove(new DummyMove());
moveScope.setScore(score);
moveScope.setAccepted(accepted);
return moveScope;
}
}
| |
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.activity.server.rest.client;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Singleton;
import org.overlord.rtgov.activity.model.ActivityType;
import org.overlord.rtgov.activity.model.ActivityUnit;
import org.overlord.rtgov.activity.model.Context;
import org.overlord.rtgov.activity.server.ActivityServer;
import org.overlord.rtgov.activity.server.QuerySpec;
import org.overlord.rtgov.activity.util.ActivityUtil;
import org.overlord.rtgov.common.util.RTGovProperties;
/**
* This class provides the REST client implementation of the activity server.
*
*/
@Singleton
public class RESTActivityServer implements ActivityServer {
private static final Logger LOG=Logger.getLogger(RESTActivityServer.class.getName());
private static final String STORE="/overlord-rtgov/activity/store";
private static final String UNIT="/overlord-rtgov/activity/unit";
private static final String QUERY="/overlord-rtgov/activity/query";
private static final String EVENTS="/overlord-rtgov/activity/events";
private String _serverURL;
private String _serverUsername;
private String _serverPassword;
/**
* The default constructor.
*/
public RESTActivityServer() {
_serverURL = RTGovProperties.getProperty("RESTActivityServer.serverURL",
"http://localhost:8080");
_serverUsername = RTGovProperties.getProperty("RESTActivityServer.serverUsername",
"");
_serverPassword = RTGovProperties.getProperty("RESTActivityServer.serverPassword",
"");
}
/**
* This method sets the URL of the Activity Server.
*
* @param url The URL
*/
public void setServerURL(String url) {
_serverURL = url;
}
/**
* This method gets the URL of the Activity Server.
*
* @return The URL
*/
public String getServerURL() {
return (_serverURL);
}
/**
* This method sets the username for the Activity Server.
*
* @param username The username
*/
public void setServerUsername(String username) {
_serverUsername = username;
}
/**
* This method gets the username for the Activity Server.
*
* @return The username
*/
public String getServerUsername() {
return (_serverUsername);
}
/**
* This method sets the password for the Activity Server.
*
* @param password The password
*/
public void setServerPassword(String password) {
_serverPassword = password;
}
/**
* This method gets the password for the Activity Server.
*
* @return The password
*/
public String getServerPassword() {
return (_serverPassword);
}
/**
* This method initializes the authentication properties on the supplied
* URL connection.
*
* @param connection The connection
*/
protected void initAuth(HttpURLConnection connection) {
String userPassword = _serverUsername + ":" + _serverPassword;
String encoding = org.apache.commons.codec.binary.Base64.encodeBase64String(userPassword.getBytes());
StringBuffer buf=new StringBuffer(encoding);
for (int i=0; i < buf.length(); i++) {
if (Character.isWhitespace(buf.charAt(i))) {
buf.deleteCharAt(i);
i--;
}
}
connection.setRequestProperty("Authorization", "Basic " + buf.toString());
}
/**
* {@inheritDoc}
*/
public void store(List<ActivityUnit> activities) throws Exception {
URL storeUrl = new URL(_serverURL+STORE);
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer["+storeUrl+"] store: "+activities);
}
HttpURLConnection connection = (HttpURLConnection) storeUrl.openConnection();
initAuth(connection);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Type",
"application/json");
java.io.OutputStream os=connection.getOutputStream();
os.write(ActivityUtil.serializeActivityUnitList(activities));
os.flush();
os.close();
java.io.InputStream is=connection.getInputStream();
byte[] b = new byte[is.available()];
is.read(b);
is.close();
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer result: "+new String(b));
}
}
/**
* {@inheritDoc}
*/
public ActivityUnit getActivityUnit(String id) throws Exception {
ActivityUnit ret=null;
URL queryUrl = new URL(_serverURL+UNIT+"?id="+id);
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer["+queryUrl+"] getActivityUnit: "+id);
}
HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
initAuth(connection);
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Type",
"application/json");
java.io.InputStream is=connection.getInputStream();
byte[] b=new byte[is.available()];
is.read(b);
is.close();
ret = ActivityUtil.deserializeActivityUnit(b);
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer getActivityUnit result: "+ret);
}
return (ret);
}
/**
* {@inheritDoc}
*/
public List<ActivityType> getActivityTypes(Context context,
long from, long to) throws Exception {
URL queryUrl = new URL(_serverURL+EVENTS+"?type="+context.getType()
+"&value="+context.getValue()
+"&from="+from
+"&to="+to);
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer["+queryUrl+"] getActivityTypes: "+context
+" from="+from+" to="+to);
}
return (getActivityTypes(queryUrl));
}
/**
* {@inheritDoc}
*/
public List<ActivityType> getActivityTypes(Context context) throws Exception {
URL queryUrl = new URL(_serverURL+EVENTS+"?type="+context.getType()
+"&value="+context.getValue());
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer["+queryUrl+"] getActivityTypes: "+context);
}
return (getActivityTypes(queryUrl));
}
/**
* This method retrieves the activity types associated with the supplied
* query URL.
*
* @param queryUrl The query URL
* @return The list of activity types
* @throws Exception Failed to get activity types
*/
protected List<ActivityType> getActivityTypes(URL queryUrl) throws Exception {
List<ActivityType> ret=null;
HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
initAuth(connection);
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Type",
"application/json");
java.io.InputStream is=connection.getInputStream();
byte[] b = new byte[is.available()];
is.read(b);
ret = ActivityUtil.deserializeActivityTypeList(b);
is.close();
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer getActivityTypes result: "+ret);
}
return (ret);
}
/**
* {@inheritDoc}
*/
public List<ActivityType> query(QuerySpec query) throws Exception {
List<ActivityType> ret=null;
URL queryUrl = new URL(_serverURL+QUERY);
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer["+queryUrl+"] query: "+query);
}
HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
initAuth(connection);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Type",
"application/json");
java.io.OutputStream os=connection.getOutputStream();
byte[] b=ActivityUtil.serializeQuerySpec(query);
os.write(b);
os.flush();
os.close();
java.io.InputStream is=connection.getInputStream();
b = new byte[is.available()];
is.read(b);
ret = ActivityUtil.deserializeActivityTypeList(b);
is.close();
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("RESTActivityServer result: "+ret);
}
return (ret);
}
}
| |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.am.repository.jdbc.management.api.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.time.LocalDateTime;
import java.util.Set;
/**
* @author Eric LELEU (eric.leleu at graviteesource.com)
* @author GraviteeSource Team
*/
@Table("applications")
public class JdbcApplication {
@Id
private String id;
private String name;
private String type;
private String description;
private String domain;
private boolean enabled;
private boolean template;
private String certificate;
@Column("created_at")
private LocalDateTime createdAt;
@Column("updated_at")
private LocalDateTime updatedAt;
// JSON
private String metadata;
private String settings;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTemplate() {
return template;
}
public void setTemplate(boolean template) {
this.template = template;
}
public String getCertificate() {
return certificate;
}
public void setCertificate(String certificate) {
this.certificate = certificate;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public String getMetadata() {
return metadata;
}
public void setMetadata(String metadata) {
this.metadata = metadata;
}
public String getSettings() {
return settings;
}
public void setSettings(String settings) {
this.settings = settings;
}
@Table("application_identities")
public static class Identity {
@Column("application_id")
private String applicationId;
private String identity;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
}
@Table("application_grants")
public static class Grant {
@Column("application_id")
private String applicationId;
@Column("grant_type")
private String grant;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getGrant() {
return grant;
}
public void setGrant(String grant) {
this.grant = grant;
}
}
@Table("application_factors")
public static class Factor {
@Column("application_id")
private String applicationId;
private String factor;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getFactor() {
return factor;
}
public void setFactor(String factor) {
this.factor = factor;
}
}
}
| |
/*
* All rights reserved. (C) Copyright 2009, Trinity College Dublin
*/
package com.mind_era.knime.hits.view.heatmap;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
import javax.xml.bind.annotation.XmlRootElement;
import com.mind_era.knime.common.Format;
import com.mind_era.knime.common.util.swing.colour.ColourSelector.ColourModel;
import com.mind_era.knime.common.view.StatTypes;
import com.mind_era.knime.hits.view.heatmap.ControlPanel.ArrangementModel;
import com.mind_era.knime.hits.view.heatmap.ViewModel.WellViewModel.Places;
/**
* This is responsible for the visual representation of the {@link Heatmap}s.
*
* @author <a href="mailto:bakosg@tcd.ie">Gabor Bakos</a>
*/
@Nonnull
@CheckReturnValue
@NotThreadSafe
@XmlRootElement(name = "viewmodel")
public class ViewModel implements ActionListener {
private final WeakHashMap<ChangeListener, Boolean> changeListeners = new WeakHashMap<ChangeListener, Boolean>();
private final WeakHashMap<ActionListener, Boolean> actionListeners = new WeakHashMap<ActionListener, Boolean>();
/**
* The shape of the well representation.
*/
public static enum Shape {
/** Circle based representation. */
Circle(4, true, true),
/** Rectangular representation. */
Rectangle(0, true, true);
private final int additionalInformationSlotsCount;
private final boolean supportThickness;
private final boolean supportSize;
private Shape(final int additionalInformationSlots,
final boolean supportThickness, final boolean supportSize) {
this.additionalInformationSlotsCount = additionalInformationSlots;
this.supportThickness = supportThickness;
this.supportSize = supportSize;
}
/**
* @return At most this many additional informations can be shown.
*/
public int getAdditionalInformationSlotsCount() {
return additionalInformationSlotsCount;
}
/**
* @return Does it supports the different thickness of the border?
*/
public boolean isSupportThickness() {
return supportThickness;
}
/**
* @return Does it support showing a parameter affecting the size of the
* result?
*/
public boolean isSupportSize() {
return supportSize;
}
}
/**
* The possible values of a parameter.
*/
public static enum ValueType {
/** The values are distinct */
Discrete,
/** The values are from a real interval. */
Continuous;
}
/**
* This class represents the layout of wells.
*/
public static class WellViewModel implements Serializable {
private static final long serialVersionUID = 7800658256156783902L;
/**
* This shows the possible places of the well splits.
*/
public static enum Places implements CompatibleValues {
/** Split by the primary splitting position. */
Primer(EnumSet.of(ValueType.Discrete, ValueType.Continuous)),
/** Split by the secondary splitting position. */
Seconder(EnumSet.of(ValueType.Discrete, ValueType.Continuous)),
/** Additional positions for results. */
Additional(EnumSet.of(ValueType.Discrete, ValueType.Continuous));
private final EnumSet<ValueType> compatibleValues;
private Places(final EnumSet<ValueType> compatibleValues) {
this.compatibleValues = compatibleValues;
}
@Override
public EnumSet<ValueType> getCompatibleValues() {
return compatibleValues;
}
}
}
/**
* States what kind of values are accepted.
*/
public static interface CompatibleValues {
/**
* @return The compatible values.
*/
public EnumSet<ValueType> getCompatibleValues();
}
/**
* This class is for the {@link SliderModel}s outside of the wells.
*/
public static class OverviewModel implements Serializable {
private static final long serialVersionUID = -4371472124531160973L;
/**
* The possible places of {@link SliderModel}s outside of the wells.
*/
public static enum Places implements CompatibleValues {
/** These are for the rows. */
Rows(EnumSet.of(ValueType.Discrete)),
/** These are for the columns */
Columns(EnumSet.of(ValueType.Discrete)),
/** These are for selecting the value. */
Choices(EnumSet.of(ValueType.Discrete)),
/** These are only on the control panel. */
Hidden(EnumSet.of(ValueType.Discrete));
private final EnumSet<ValueType> compatibleValues;
private Places(final EnumSet<ValueType> compatibleValues) {
this.compatibleValues = compatibleValues;
}
@Override
public EnumSet<ValueType> getCompatibleValues() {
return compatibleValues;
}
}
private final List<ParameterModel> rowModel = new ArrayList<ParameterModel>();
private final List<ParameterModel> colModel = new ArrayList<ParameterModel>();
private final List<ParameterModel> choiceModel = new ArrayList<ParameterModel>();
/**
* Constructs an {@link OverviewModel} based on the given
* {@link ParameterModel}s.
*
* @param rowModel
* This describes the distribution of the result by row.
* @param colModel
* This describes the distribution of the result by column.
* @param choiceModel
* This describes the distribution of the result by selection
* slider.
*/
public OverviewModel(final List<ParameterModel> rowModel,
final List<ParameterModel> colModel,
final List<ParameterModel> choiceModel) {
super();
this.rowModel.addAll(rowModel);
this.colModel.addAll(colModel);
this.choiceModel.addAll(choiceModel);
}
/**
* @return The selection slider's {@link ParameterModel}s.
*/
public List<ParameterModel> getChoiceModel() {
return Collections.unmodifiableList(choiceModel);
}
/**
* @return The column's {@link ParameterModel}s.
*/
public List<ParameterModel> getColModel() {
return Collections.unmodifiableList(colModel);
}
/**
* @return The row's {@link ParameterModel}s.
*/
public List<ParameterModel> getRowModel() {
return Collections.unmodifiableList(rowModel);
}
}
/**
* Describes the layout of a well.
*/
public static class ShapeModel implements Serializable {
private static final long serialVersionUID = 7291082607986486046L;
private final ArrangementModel arrangementModel;
private final List<ParameterModel> primerParameters = new ArrayList<ParameterModel>();
private final List<ParameterModel> secunderParameters = new ArrayList<ParameterModel>();
private final List<ParameterModel> additionalParameters = new ArrayList<ParameterModel>();
private final boolean drawBorder;
private final boolean drawPrimaryBorders;
private final boolean drawSecondaryBorders;
private final boolean drawAdditionalBorders;
private final int startAngle = 30;
private ColourModel colourModel;
/**
* Constructs a {@link ShapeModel} using the parameters.
*
* @param arrangementModel
* This describes the actual {@link SliderModel}s.
* @param primerParameters
* This describes the primary split {@link ParameterModel}s.
* @param secunderParameters
* This describes the secondary split {@link ParameterModel}
* s.
* @param additionalParameters
* This describes the additional data {@link ParameterModel}
* s.
* @param drawBorder
* If set draws a (rectangular) border around the well.
* @param drawPrimaryBorders
* If set draws borders for the primary selections.
* @param drawSecondaryBorders
* If set draws borders for the secondary selections.
* @param drawAdditionalBorders
* If set draws borders for the additional data.
*/
public ShapeModel(final ArrangementModel arrangementModel,
final List<ParameterModel> primerParameters,
final List<ParameterModel> secunderParameters,
final List<ParameterModel> additionalParameters,
final boolean drawBorder, final boolean drawPrimaryBorders,
final boolean drawSecondaryBorders,
final boolean drawAdditionalBorders) {
super();
this.arrangementModel = arrangementModel;
this.primerParameters.addAll(primerParameters);
this.secunderParameters.addAll(secunderParameters);
this.additionalParameters.addAll(additionalParameters);
this.drawBorder = drawBorder;
this.drawPrimaryBorders = drawPrimaryBorders;
this.drawSecondaryBorders = drawSecondaryBorders;
this.drawAdditionalBorders = drawAdditionalBorders;
this.colourModel = new ColourModel();
}
/**
* Constructs a {@link ShapeModel} using the parameters.
*
* @param arrangementModel
* This describes the actual {@link SliderModel}s.
* @param primerParameters
* This describes the primary split {@link ParameterModel}s.
* @param secunderParameters
* This describes the secondary split {@link ParameterModel}
* s.
* @param additionalParameters
* This describes the additional data {@link ParameterModel}
* s.
* @param drawBorders
* If set draws every possible separator line, else it draws
* none.
*/
public ShapeModel(final ArrangementModel arrangementModel,
final List<ParameterModel> primerParameters,
final List<ParameterModel> secunderParameters,
final List<ParameterModel> additionalParameters,
final boolean drawBorders) {
this(arrangementModel, primerParameters, secunderParameters,
additionalParameters, drawBorders, drawBorders,
drawBorders, drawBorders);
}
/**
* Constructs a {@link ShapeModel} using the parameters.
*
* @param arrangementModel
* This describes the actual {@link SliderModel}s.
* @param model
* The model to copy.
* @param place
* A {@link Places} in the well.
* @param drawBorder
* Sets the value of the border to at {@code place} to this
* value.
*/
public ShapeModel(final ArrangementModel arrangementModel,
final ShapeModel model, final WellViewModel.Places place,
final boolean drawBorder) {
super();
this.arrangementModel = arrangementModel;
this.primerParameters.addAll(model.primerParameters);
this.secunderParameters.addAll(model.secunderParameters);
this.additionalParameters.addAll(model.additionalParameters);
if (place == null) {
this.drawBorder = drawBorder;
this.drawPrimaryBorders = model.drawPrimaryBorders;
this.drawSecondaryBorders = model.drawSecondaryBorders;
this.drawAdditionalBorders = model.drawAdditionalBorders;
} else {
switch (place) {
case Primer:
this.drawBorder = model.drawBorder;
this.drawPrimaryBorders = drawBorder;
this.drawSecondaryBorders = model.drawSecondaryBorders;
this.drawAdditionalBorders = model.drawAdditionalBorders;
break;
case Seconder:
this.drawBorder = model.drawBorder;
this.drawPrimaryBorders = model.drawPrimaryBorders;
this.drawSecondaryBorders = model.drawBorder;
this.drawAdditionalBorders = model.drawAdditionalBorders;
break;
case Additional:
this.drawBorder = model.drawBorder;
this.drawPrimaryBorders = model.drawPrimaryBorders;
this.drawSecondaryBorders = model.drawSecondaryBorders;
this.drawAdditionalBorders = model.drawBorder;
break;
default:
throw new IllegalStateException("Wrong type: " + place);
}
}
}
/**
* @return The primary split {@link ParameterModel}s.
*/
public List<ParameterModel> getPrimerParameters() {
return Collections.unmodifiableList(primerParameters);
}
/**
* @return The secondary split {@link ParameterModel}s.
*/
public List<ParameterModel> getSeconderParameters() {
return Collections.unmodifiableList(secunderParameters);
}
/**
* @return The additional data {@link ParameterModel}s.
*/
public List<ParameterModel> getAdditionalParameters() {
return Collections.unmodifiableList(additionalParameters);
}
/**
* @return Draw outside (rectangular) border?
*/
public boolean isDrawBorder() {
return drawBorder;
}
/**
* @return Draw lines between primary separators?
*/
public boolean isDrawPrimaryBorders() {
return drawPrimaryBorders;
}
/**
* @return Draw lines between secondary separators?
*/
public boolean isDrawSecondaryBorders() {
return drawSecondaryBorders;
}
/**
* @return Draw lines around additional data?
*/
public boolean isDrawAdditionalBorders() {
return drawAdditionalBorders;
}
/**
* @return Starting angle of the primary separator (only used in the
* {@link Shape#Circle} case).
*/
public int getStartAngle() {
return startAngle;
}
/**
* @return The {@link ArrangementModel} associated to this
* {@link ShapeModel}.
*/
public ArrangementModel getArrangementModel() {
return arrangementModel;
}
/**
* @return the used {@link ColourModel}.
*/
public ColourModel getColourModel() {
return colourModel;
}
/**
* Sets the new {@link ColourModel} to {@code colourModel}.
*
* @param colourModel
* the new {@link ColourModel}.
*/
public void setColourModel(final ColourModel colourModel) {
this.colourModel = colourModel;
}
/**
* Updates the parameters.
*
* @param possibleParameters
* This contains the possible values.
* @see HeatmapNodeModel#getPossibleParameters()
*/
public void updateParameters(
final Collection<ParameterModel> possibleParameters) {
update(primerParameters, possibleParameters);
update(secunderParameters, possibleParameters);
update(additionalParameters, possibleParameters);
}
private void update(final List<ParameterModel> orig,
final Collection<ParameterModel> possibleParameters) {
final ArrayList<ParameterModel> copy = new ArrayList<ParameterModel>(
orig);
orig.clear();
for (final ParameterModel pm : copy) {
for (final ParameterModel good : possibleParameters) {
final StatTypes type = good.getType();
if (good.getShortName().equals(pm.getShortName())
&& type == pm.getType()) {
final ParameterModel merged = new ParameterModel(good
.getShortName(), type, pm.getAggregateType(),
good.getColumns(), good.getColumnValues());
if (type.isDiscrete()) {
merged.setValueCount(good.getValueCount());
merged.getColorLegend().putAll(
good.getColorLegend());
} else {
merged.setStartColor(good.getStartColor());
merged.setMiddleColor(good.getEndColor());
merged.setEndColor(good.getEndColor());
merged.setRangeMin(good.getRangeMin());
merged.setRangeMax(good.getRangeMax());
}
orig.add(merged);
break;
}
}
}
}
}
/**
* This enum lists all possible statistics which can be shown/computed for
* the values.
*/
public static enum AggregateType {
/** The median of the values based on the free parameters. */
Median,
/** The mean of the values based on the free parameters. */
Mean,
/** The standard deviation of the values based on the free parameters. */
StandardDeviation,
/** The MAD of the values based on the free parameters. */
MedianAbsoluteDeviation,
/** The minimum of the values based on the free parameters. */
Minimum,
/** The maximum of the values based on the free parameters. */
Maximum;
}
/**
* This is an important concept in the view description. This describes the
* parameters' properties, like name, possible values, aggregations,
* colours, ranges, ...
*/
public static class ParameterModel {
private final String shortName;// Maybe from row names
private @Nullable
final AggregateType aggregateType;
private int valueCount;// The count of different values
private final List<String> columns;
private final List<String> columnValues;
private double rangeMin, rangeMax;
private Color startColor, middleColor, endColor;
private final Map<Object, Color> colorLegend = new HashMap<Object, Color>();
private final StatTypes type;
/**
* Constructs a {@link ParameterModel} using the given parameters.
*
* @param shortName
* A short name for the {@link ParameterModel}.
* @param type
* The {@link StatTypes} it is belonging to.
* @param aggregateType
* The aggregation, may be {@code null}. This shows if there
* will be an aggregation by this parameter.
* @param columns
* These columns are represented in the original
* {@link TableModel}s. (Maybe not necessary to have.)
* @param columnValues
* These values are used, may be empty, meaning all.
*/
public ParameterModel(final String shortName, final StatTypes type,
@Nullable final AggregateType aggregateType,
final List<String> columns, final List<String> columnValues) {
super();
this.shortName = shortName;
this.type = type;
this.aggregateType = aggregateType;
this.columns = columns;
this.columnValues = columnValues;
}
/**
* @return How many different values are used.
*/
@Deprecated
public int getValueCount() {
return valueCount;
}
/**
* Sets the number of possible different values.
*
* @param valueCount
* The number of possible different values.
*/
@Deprecated
public void setValueCount(final int valueCount) {
assert type.isDiscrete() : type;
this.valueCount = valueCount;
}
/**
* @return The lower bound for the values.
*/
public double getRangeMin() {
return rangeMin;
}
/**
* Sets the lower bound for the values.
*
* @param rangeMin
* The new lower bound for the values.
*/
public void setRangeMin(final double rangeMin) {
assert !type.isDiscrete() : type;
this.rangeMin = rangeMin;
}
/**
* @return The upper bound for the values.
*/
public double getRangeMax() {
return rangeMax;
}
/**
* Sets the upper bound for the values.
*
* @param rangeMax
* The new upper bound for the values.
*/
public void setRangeMax(final double rangeMax) {
assert !type.isDiscrete();
this.rangeMax = rangeMax;
}
/**
* @return The {@link Color} for the lower bound.
*/
public Color getStartColor() {
return startColor;
}
/**
* Sets the colour for the lower values.
*
* @param startColor
* The colour for the lower values.
*/
public void setStartColor(final Color startColor) {
assert !type.isDiscrete() : type;
this.startColor = startColor;
}
/**
* @return The {@link Color} for the neutral value.
*/
public Color getMiddleColor() {
return middleColor;
}
/**
* Sets the colour for the neutral values.
*
* @param middleColor
* The colour for the neutral values.
*/
public void setMiddleColor(final Color middleColor) {
assert !type.isDiscrete() : type;
this.middleColor = middleColor;
}
/**
* @return The {@link Color} for the upper bound.
*/
public Color getEndColor() {
return endColor;
}
/**
* Sets the colour for the upper values.
*
* @param endColor
* The colour for the upper values.
*/
public void setEndColor(final Color endColor) {
assert !type.isDiscrete() : type;
this.endColor = endColor;
}
/**
* @return The name of this {@link ParameterModel}.
*/
public String getShortName() {
return shortName;
}
/**
* @return The {@link AggregateType} for this {@link ParameterModel}.
*/
public AggregateType getAggregateType() {
return aggregateType;
}
/**
* @return The columns from the {@link HeatmapNodeModel}.
*/
public List<String> getColumns() {
return columns;
}
/**
* @return The values used from the columns.
*/
public List<String> getColumnValues() {
return columnValues;
}
/**
* @return The color legend for different values.
*/
public Map<Object, Color> getColorLegend() {
assert type.isDiscrete() : type;
return colorLegend;
}
/**
* @return The {@link StatTypes} represented.
*/
public StatTypes getType() {
return type;
}
@Override
public String toString() {
return getShortName()
+ " "
+ getValueCount()
+ ": "
+ (getType().isDiscrete() ? getColorLegend().keySet()
: rangeMin + " " + rangeMax);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (aggregateType == null ? 0 : aggregateType.hashCode());
result = prime * result
+ (colorLegend == null ? 0 : colorLegend.hashCode());
result = prime * result
+ (columnValues == null ? 0 : columnValues.hashCode());
result = prime * result
+ (columns == null ? 0 : columns.hashCode());
result = prime * result
+ (endColor == null ? 0 : endColor.hashCode());
result = prime * result
+ (middleColor == null ? 0 : middleColor.hashCode());
long temp;
temp = Double.doubleToLongBits(rangeMax);
result = prime * result + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(rangeMin);
result = prime * result + (int) (temp ^ temp >>> 32);
result = prime * result
+ (shortName == null ? 0 : shortName.hashCode());
result = prime * result
+ (startColor == null ? 0 : startColor.hashCode());
result = prime * result + (type == null ? 0 : type.hashCode());
result = prime * result + valueCount;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ParameterModel other = (ParameterModel) obj;
if (aggregateType == null) {
if (other.aggregateType != null) {
return false;
}
} else if (!aggregateType.equals(other.aggregateType)) {
return false;
}
if (colorLegend == null) {
if (other.colorLegend != null) {
return false;
}
} else if (!colorLegend.equals(other.colorLegend)) {
return false;
}
if (columnValues == null) {
if (other.columnValues != null) {
return false;
}
} else if (!columnValues.equals(other.columnValues)) {
return false;
}
if (columns == null) {
if (other.columns != null) {
return false;
}
} else if (!columns.equals(other.columns)) {
return false;
}
if (endColor == null) {
if (other.endColor != null) {
return false;
}
} else if (!endColor.equals(other.endColor)) {
return false;
}
if (middleColor == null) {
if (other.middleColor != null) {
return false;
}
} else if (!middleColor.equals(other.middleColor)) {
return false;
}
if (Double.doubleToLongBits(rangeMax) != Double
.doubleToLongBits(other.rangeMax)) {
return false;
}
if (Double.doubleToLongBits(rangeMin) != Double
.doubleToLongBits(other.rangeMin)) {
return false;
}
if (shortName == null) {
if (other.shortName != null) {
return false;
}
} else if (!shortName.equals(other.shortName)) {
return false;
}
if (startColor == null) {
if (other.startColor != null) {
return false;
}
} else if (!startColor.equals(other.startColor)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
if (valueCount != other.valueCount) {
return false;
}
return true;
}
}
/**
* Constructs a {@link ViewModel} with a different {@link Format}.
*
* @param model
* The prototype {@link ViewModel}.
* @param format
* The new {@link Format}.
*/
public ViewModel(final ViewModel model, final Format format) {
super();
this.format = format;
this.shape = model.shape;
this.overview = model.overview;
this.main = model.main;
}
/**
* Constructs a {@link ViewModel} with a different {@link Shape}.
*
* @param model
* The prototype {@link ViewModel}.
* @param shape
* The new {@link Shape}.
*/
public ViewModel(final ViewModel model, final Shape shape) {
super();
this.format = model.format;
this.shape = shape;
this.overview = model.overview;
this.main = model.main;
}
/**
* Constructs a {@link ViewModel} with a different {@link OverviewModel}.
*
* @param model
* The prototype {@link ViewModel}.
* @param overview
* The new {@link OverviewModel}.
*/
public ViewModel(final ViewModel model, final OverviewModel overview) {
super();
this.format = model.format;
this.shape = model.shape;
this.overview = overview;
this.main = model.main;
}
/**
* Constructs a {@link ViewModel} with a different {@link ShapeModel}.
*
* @param model
* The prototype {@link ViewModel}.
* @param shapeModel
* The new {@link ShapeModel}.
*/
public ViewModel(final ViewModel model, final ShapeModel shapeModel) {
super();
this.format = model.format;
this.shape = model.shape;
this.overview = model.overview;
this.main = shapeModel;
}
/**
* Constructs a {@link ViewModel} with the basic parameters.
*
* @param format
* The format of the plate.
* @param shape
* The shape of the wells.
* @param overview
* The {@link OverviewModel}.
* @param shapeModel
* The {@link ShapeModel}.
*/
public ViewModel(final Format format, final Shape shape,
final OverviewModel overview, final ShapeModel shapeModel) {
super();
this.format = format;
this.shape = shape;
this.overview = overview;
this.main = shapeModel;
}
private final Format format;
private final Shape shape;
private final OverviewModel overview;
private final ShapeModel main;
private String labelPattern;
@Override
public void actionPerformed(final ActionEvent e) {
for (final ActionListener listener : actionListeners.keySet()) {
listener.actionPerformed(new ActionEvent(this, e.getID(), e
.getActionCommand()));
}
for (final ChangeListener listener : changeListeners.keySet()) {
listener.stateChanged(new ChangeEvent(this));
}
}
/**
* Adds a {@link ChangeListener} to {@link ViewModel}.
*
* @param listener
* A {@link ChangeListener}.
* @return It is {@code true} if it was newly added.
*/
public boolean addChangeListener(final ChangeListener listener) {
return changeListeners.put(listener, Boolean.TRUE) == null;
}
/**
* Removes the {@link ChangeListener} from {@link ViewModel}.
*
* @param listener
* A {@link ChangeListener} to remove.
* @return It is {@code true} if it was previously contained.
*/
public boolean removeChangeListener(final ChangeListener listener) {
return changeListeners.remove(listener) != null;
}
/**
* Adds an {@link ActionListener} to {@link ViewModel}.
*
* @param listener
* An {@link ActionListener}.
* @return It is {@code true} if it was newly added.
*/
public boolean addActionListener(final ActionListener listener) {
return actionListeners.put(listener, Boolean.TRUE) == null;
}
/**
* Removes the {@link ActionListener} from {@link ViewModel}.
*
* @param listener
* A {@link ActionListener} to remove.
* @return It is {@code true} if it was previously contained.
*/
public boolean removeActionListener(final ActionListener listener) {
return actionListeners.remove(listener) != null;
}
/**
* @return The current {@link Format}.
*/
public Format getFormat() {
return format;
}
/**
* @return The current {@link Shape}.
*/
public Shape getShape() {
return shape;
}
/**
* @return The current {@link OverviewModel}.
*/
public OverviewModel getOverview() {
return overview;
}
/**
* @return The current {@link ShapeModel}.
*/
public ShapeModel getMain() {
return main;
}
/**
* Updates the pattern for the labels.
*
* @param labelPattern
* The new pattern.
*/
public void setLabelPattern(final String labelPattern) {
this.labelPattern = labelPattern;
actionPerformed(new ActionEvent(this,
(int) (System.currentTimeMillis() & 0xffffffff), "newLabels"));
}
/**
* @return The pattern for the information panel and for the tooltips.
*/
public String getLabelPattern() {
return labelPattern;
}
}
| |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.masterdb.bean;
import static com.opengamma.util.db.DbDateUtils.MAX_SQL_TIMESTAMP;
import static com.opengamma.util.db.DbDateUtils.toSqlTimestamp;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import java.sql.Types;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.support.SqlLobValue;
import org.testng.annotations.Test;
import org.threeten.bp.Clock;
import org.threeten.bp.Instant;
import org.threeten.bp.ZoneOffset;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.UniqueId;
import com.opengamma.master.security.SecurityDocument;
import com.opengamma.masterdb.security.DbSecurityBeanMaster;
import com.opengamma.util.JodaBeanSerialization;
import com.opengamma.util.ZipUtils;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.AbstractDbTest;
import com.opengamma.util.test.TestGroup;
/**
* Base tests for DbSecurityBeanMaster.
*/
@Test(groups = TestGroup.UNIT_DB)
public abstract class AbstractDbSecurityBeanMasterTest extends AbstractDbTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDbSecurityBeanMasterTest.class);
private static final ExternalIdBundle BUNDLE_201 = ExternalIdBundle.of(ExternalId.of("C", "D"), ExternalId.of("E", "F"));
private static final ExternalIdBundle BUNDLE_102 = ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("C", "D"), ExternalId.of("GH", "HI"));
private static final ExternalIdBundle BUNDLE_101 = ExternalIdBundle.of(ExternalId.of("A", "B"), ExternalId.of("C", "D"), ExternalId.of("E", "F"));
protected DbSecurityBeanMaster _secMaster;
protected Instant _version1Instant;
protected Instant _version2Instant;
protected int _totalSecurities;
public AbstractDbSecurityBeanMasterTest(final String databaseType, final String databaseVersion, final boolean readOnly) {
super(databaseType, databaseVersion);
LOGGER.info("running testcases for {}", databaseType);
}
//-------------------------------------------------------------------------
@Override
protected void doSetUp() {
init();
}
@Override
protected void doTearDown() {
_secMaster = null;
}
@Override
protected void doTearDownClass() {
_secMaster = null;
}
//-------------------------------------------------------------------------
private void init() {
_secMaster = new DbSecurityBeanMaster(getDbConnector());
// id bigint NOT NULL,
// oid bigint NOT NULL,
// ver_from_instant timestamp without time zone NOT NULL,
// ver_to_instant timestamp without time zone NOT NULL,
// corr_from_instant timestamp without time zone NOT NULL,
// corr_to_instant timestamp without time zone NOT NULL,
// name varchar(255) NOT NULL,
// main_type char NOT NULL,
// sub_type varchar(255) NOT NULL,
// java_type varchar(255) NOT NULL,
// packed_data blob NOT NULL,
final Instant now = Instant.now();
_secMaster.setClock(Clock.fixed(now, ZoneOffset.UTC));
_version1Instant = now.minusSeconds(100);
_version2Instant = now.minusSeconds(50);
LOGGER.debug("test data now: {}", _version1Instant);
LOGGER.debug("test data later: {}", _version2Instant);
final JdbcOperations template = _secMaster.getDbConnector().getJdbcOperations();
template.update("INSERT INTO secb_document VALUES (?,?,?,?,?, ?,?,?,?,?, ?)",
101, 101, toSqlTimestamp(_version1Instant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1Instant), MAX_SQL_TIMESTAMP,
"TestSecurity101", "S", "EQUITY", "EquitySecurity", blob("TestSecurity101", BUNDLE_101));
template.update("INSERT INTO secb_document VALUES (?,?,?,?,?, ?,?,?,?,?, ?)",
102, 102, toSqlTimestamp(_version1Instant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version1Instant), MAX_SQL_TIMESTAMP,
"TestSecurity102", "S", "EQUITY", "EquitySecurity", blob("TestSecurity102", BUNDLE_102));
template.update("INSERT INTO secb_document VALUES (?,?,?,?,?, ?,?,?,?,?, ?)",
201, 201, toSqlTimestamp(_version1Instant), toSqlTimestamp(_version2Instant), toSqlTimestamp(_version1Instant), MAX_SQL_TIMESTAMP,
"TestSecurity201", "S", "EQUITY", "EquitySecurity", blob("TestSecurity201", BUNDLE_201));
template.update("INSERT INTO secb_document VALUES (?,?,?,?,?, ?,?,?,?,?, ?)",
202, 201, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP, toSqlTimestamp(_version2Instant), MAX_SQL_TIMESTAMP,
"TestSecurity202", "S", "EQUITY", "EquitySecurity", blob("TestSecurity202", BUNDLE_201));
_totalSecurities = 3;
// id bigint not null,
// key_scheme varchar(255) not null,
// key_value varchar(255) not null,
template.update("INSERT INTO secb_idkey VALUES (?,?,?)",
1, "A", "B");
template.update("INSERT INTO secb_idkey VALUES (?,?,?)",
2, "C", "D");
template.update("INSERT INTO secb_idkey VALUES (?,?,?)",
3, "E", "F");
template.update("INSERT INTO secb_idkey VALUES (?,?,?)",
4, "GH", "HI");
// security_id bigint not null,
// idkey_id bigint not null,
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
101, 1);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
101, 2);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
101, 3);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
102, 1);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
102, 2);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
102, 4);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
201, 2);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
201, 3);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
202, 2);
template.update("INSERT INTO secb_doc2idkey VALUES (?,?)",
202, 3);
}
private Object blob(final String name, final ExternalIdBundle bundle) {
final EquitySecurity value = new EquitySecurity("LONDON", "LON", "LSE", Currency.GBP);
value.setName(name);
value.setExternalIdBundle(bundle);
final String xml = JodaBeanSerialization.serializer(false).xmlWriter().write(value);
final byte[] bytes = ZipUtils.deflateString(xml);
final SqlLobValue lob = new SqlLobValue(bytes, getDbConnector().getDialect().getLobHandler());
return new SqlParameterValue(Types.BLOB, lob);
}
//-------------------------------------------------------------------------
protected void assert101(final SecurityDocument test) {
final UniqueId uniqueId = UniqueId.of("DbSec", "101", "0");
assertNotNull(test);
assertEquals(uniqueId, test.getUniqueId());
assertEquals(_version1Instant, test.getVersionFromInstant());
assertEquals(null, test.getVersionToInstant());
assertEquals(_version1Instant, test.getCorrectionFromInstant());
assertEquals(null, test.getCorrectionToInstant());
final EquitySecurity security = (EquitySecurity) test.getSecurity();
assertNotNull(security);
assertEquals(uniqueId, security.getUniqueId());
assertEquals("TestSecurity101", security.getName());
assertEquals("EQUITY", security.getSecurityType());
assertEquals(BUNDLE_101, security.getExternalIdBundle());
}
protected void assert102(final SecurityDocument test) {
final UniqueId uniqueId = UniqueId.of("DbSec", "102", "0");
assertNotNull(test);
assertEquals(uniqueId, test.getUniqueId());
assertEquals(_version1Instant, test.getVersionFromInstant());
assertEquals(null, test.getVersionToInstant());
assertEquals(_version1Instant, test.getCorrectionFromInstant());
assertEquals(null, test.getCorrectionToInstant());
final EquitySecurity security = (EquitySecurity) test.getSecurity();
assertNotNull(security);
assertEquals(uniqueId, security.getUniqueId());
assertEquals("TestSecurity102", security.getName());
assertEquals("EQUITY", security.getSecurityType());
assertEquals(BUNDLE_102, security.getExternalIdBundle());
}
protected void assert201(final SecurityDocument test) {
final UniqueId uniqueId = UniqueId.of("DbSec", "201", "0");
assertNotNull(test);
assertEquals(uniqueId, test.getUniqueId());
assertEquals(_version1Instant, test.getVersionFromInstant());
assertEquals(_version2Instant, test.getVersionToInstant());
assertEquals(_version1Instant, test.getCorrectionFromInstant());
assertEquals(null, test.getCorrectionToInstant());
final EquitySecurity security = (EquitySecurity) test.getSecurity();
assertNotNull(security);
assertEquals(uniqueId, security.getUniqueId());
assertEquals("TestSecurity201", security.getName());
assertEquals("EQUITY", security.getSecurityType());
assertEquals(BUNDLE_201, security.getExternalIdBundle());
}
protected void assert202(final SecurityDocument test) {
final UniqueId uniqueId = UniqueId.of("DbSec", "201", "1");
assertNotNull(test);
assertEquals(uniqueId, test.getUniqueId());
assertEquals(_version2Instant, test.getVersionFromInstant());
assertEquals(null, test.getVersionToInstant());
assertEquals(_version2Instant, test.getCorrectionFromInstant());
assertEquals(null, test.getCorrectionToInstant());
final EquitySecurity security = (EquitySecurity) test.getSecurity();
assertNotNull(security);
assertEquals(uniqueId, security.getUniqueId());
assertEquals("TestSecurity202", security.getName());
assertEquals("EQUITY", security.getSecurityType());
assertEquals(BUNDLE_201, security.getExternalIdBundle());
}
}
| |
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.Common.FileUtil;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.core.MethodScriptCompiler;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.testing.StaticTest;
import static com.laytonsmith.testing.StaticTest.RunCommand;
import static com.laytonsmith.testing.StaticTest.SRun;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
*
*
*/
public class DataHandlingTest {
MCServer fakeServer;
MCPlayer fakePlayer;
com.laytonsmith.core.environments.Environment env;
public DataHandlingTest() throws Exception{
StaticTest.InstallFakeServerFrontend();
env = Static.GenerateStandaloneEnvironment();
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
fakePlayer = StaticTest.GetOnlinePlayer();
fakeServer = StaticTest.GetFakeServer();
env.getEnv(CommandHelperEnvironment.class).SetPlayer(fakePlayer);
}
@After
public void tearDown() {
}
@Test(timeout = 10000)
public void testFor1() throws Exception {
String config = "/for = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 5), inc(@i),\n"
+ " array_push(@array, @i)\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/for");
verify(fakePlayer).sendMessage("{0, 1, 2, 3, 4}");
}
@Test(expected = ConfigRuntimeException.class, timeout=10000)
public void testFor3() throws Exception {
String script =
" assign(@array, array())"
+ " for('nope', lt(@i, 5), inc(@i),\n"
+ " array_push(@array, @i)\n"
+ " )\n"
+ " msg(@array)\n";
MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
}
@Test(timeout = 10000)
public void testForeach1() throws Exception {
String config = "/for = >>>\n"
+ " assign(@array, array(1, 2, 3, 4, 5))\n"
+ " assign(@array2, array())"
+ " foreach(@array, @i,\n"
+ " array_push(@array2, @i)\n"
+ " )\n"
+ " msg(@array2)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/for");
verify(fakePlayer).sendMessage("{1, 2, 3, 4, 5}");
}
@Test(timeout = 10000)
public void testForeach2() throws Exception {
String config = "/for = >>>\n"
+ " assign(@array, array(1, 2, 3, 4, 5))\n"
+ " assign(@array2, array())"
+ " foreach(@array, @i,\n"
+ " if(equals(@i, 1), continue(2))"
+ " array_push(@array2, @i)\n"
+ " )\n"
+ " msg(@array2)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/for");
verify(fakePlayer).sendMessage("{3, 4, 5}");
}
@Test(timeout = 10000)
public void testForeach3() throws Exception {
String config = "/for = >>>\n"
+ " assign(@array, array(1, 2, 3, 4, 5))\n"
+ " assign(@array1, array(1, 2, 3, 4, 5))\n"
+ " assign(@array2, array())\n"
+ " foreach(@array1, @j,"
+ " foreach(@array, @i,\n"
+ " if(equals(@i, 3), break(2))"
+ " array_push(@array2, @i)\n"
+ " )\n"
+ " )"
+ " msg(@array2)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/for");
verify(fakePlayer).sendMessage("{1, 2}");
}
@Test(timeout = 10000)
public void testForeachWithArraySlice() throws Exception{
SRun("foreach(1..2, @i, msg(@i))", fakePlayer);
verify(fakePlayer).sendMessage("1");
verify(fakePlayer).sendMessage("2");
}
@Test(timeout = 10000)
public void testForeachWithKeys1() throws Exception{
SRun("@array = array(1: 'one', 2: 'two') @string = '' foreach(@array, @key, @value, @string .= (@key.':'.@value.';')) msg(@string)", fakePlayer);
verify(fakePlayer).sendMessage("1:one;2:two;");
}
@Test(timeout = 10000)
public void testForeachWithKeys2() throws Exception{
SRun("@array = array('one': 1, 'two': 2) @string = '' foreach(@array, @key, @value, @string .= (@key.':'.@value.';')) msg(@string)", fakePlayer);
verify(fakePlayer).sendMessage("one:1;two:2;");
}
@Test(timeout = 10000)
public void testForeachWithKeys3() throws Exception{
SRun("@array = array('one': 1, 'two': 2)\nforeach(@array, @key, @value){\n\tmsg(@key.':'.@value)\n}", fakePlayer);
verify(fakePlayer).sendMessage("one:1");
verify(fakePlayer).sendMessage("two:2");
}
@Test
public void testForelse() throws Exception{
SRun("forelse(assign(@i, 0), @i < 0, @i++, msg('fail'), msg('pass'))", fakePlayer);
verify(fakePlayer).sendMessage("pass");
verify(fakePlayer, times(0)).sendMessage("fail");
}
@Test
public void testForeachelse() throws Exception{
SRun("foreachelse(array(), @val, msg('fail'), msg('pass'))", fakePlayer);
SRun("foreachelse(array(1), @val, msg('pass'), msg('fail'))", fakePlayer);
SRun("foreachelse(1..2, @val, msg('pass'), msg('fail'))", fakePlayer);
verify(fakePlayer, times(4)).sendMessage("pass");
verify(fakePlayer, times(0)).sendMessage("fail");
}
@Test(timeout = 10000)
public void testCallProcIsProc() throws Exception {
when(fakePlayer.isOp()).thenReturn(true);
String config = "/for = >>>\n"
+ " msg(is_proc(_proc))\n"
+ " proc(_proc,"
+ " msg('hello world')"
+ " )"
+ " msg(is_proc(_proc))"
+ " call_proc(_proc)"
+ "<<<\n";
RunCommand(config, fakePlayer, "/for");
verify(fakePlayer).sendMessage("false");
verify(fakePlayer).sendMessage("true");
verify(fakePlayer).sendMessage("hello world");
}
/**
* There is a bug that causes an infinite loop, so we put a 10 second
* timeout
*
* @throws Exception
*/
@Test(timeout = 10000)
public void testContinue1() throws Exception {
String config = "/continue = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 5), inc(@i),\n"
+ " if(equals(@i, 2), continue(1))\n"
+ " array_push(@array, @i)\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/continue");
verify(fakePlayer).sendMessage("{0, 1, 3, 4}");
}
@Test(timeout = 10000)
public void testContinue2() throws Exception {
String config = "/continue = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 5), inc(@i),\n"
+ " if(equals(@i, 2), continue(2))\n"
+ " array_push(@array, @i)\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/continue");
verify(fakePlayer).sendMessage("{0, 1, 4}");
}
@Test(timeout = 10000)
public void testContinue3() throws Exception {
String config = "/continue = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 5), inc(@i),\n"
+ " if(equals(@i, 2), continue(3))\n"
+ " array_push(@array, @i)\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/continue");
verify(fakePlayer).sendMessage("{0, 1}");
}
@Test(timeout = 10000)
public void testBreak1() throws Exception {
String config = "/break = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 2), inc(@i),\n"
+ " for(assign(@j, 0), lt(@j, 5), inc(@j),\n"
+ " if(equals(@j, 2), break())\n"
+ " array_push(@array, concat('j:', @j))\n"
+ " )\n"
+ " array_push(@array, concat('i:', @i))\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/break");
verify(fakePlayer).sendMessage("{j:0, j:1, i:0, j:0, j:1, i:1}");
}
@Test(timeout = 10000)
public void testBreak2() throws Exception {
String config = "/break = >>>\n"
+ " assign(@array, array())"
+ " for(assign(@i, 0), lt(@i, 2), inc(@i),\n"
+ " for(assign(@j, 0), lt(@j, 5), inc(@j),\n"
+ " if(equals(@j, 2), break(2))\n"
+ " array_push(@array, concat('j:', @j))\n"
+ " )\n"
+ " array_push(@array, concat('i:', @i))\n"
+ " )\n"
+ " msg(@array)\n"
+ "<<<\n";
RunCommand(config, fakePlayer, "/break");
verify(fakePlayer).sendMessage("{j:0, j:1}");
}
@Test(timeout = 10000)
public void testInclude() throws Exception, IOException {
String script =
"include('unit_test_inc.ms')";
//Create the test file
File test = new File("unit_test_inc.ms");
FileUtil.write("msg('hello')", test);
MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, new File("./script.txt"), true)), env, null, null);
verify(fakePlayer).sendMessage("hello");
//delete the test file
test.delete();
test.deleteOnExit();
}
@Test(timeout = 10000)
public void testExportImportIVariable() throws Exception {
when(fakePlayer.isOp()).thenReturn(true);
String script1 =
"assign(@var, 10)"
+ "export(@var)";
SRun(script1, null);
SRun("import(@var) msg(@var)", fakePlayer);
verify(fakePlayer).sendMessage("10");
}
@Test(timeout = 10000)
public void testExportImportStringValue1() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("export('hi', 20)", fakePlayer);
SRun("msg(import('hi'))", fakePlayer);
verify(fakePlayer).sendMessage("20");
}
@Test
public void testExportImportStringValue2() throws Exception{
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@test, array(1, 2, 3))"
+ "export('myarray', @test)"
+ "msg(@newtest)", fakePlayer);
SRun("assign(@newtest, import('myarray')) msg(@newtest)", fakePlayer);
verify(fakePlayer).sendMessage("{1, 2, 3}");
}
@Test
public void testExportImportWithProcs1() throws Exception{
SRun("proc(_derping," +
" msg(import('borked'))"+
" assign(@var, import('borked'))" +
" assign(@var, array('Am', 'I', 'borked?'))" +
" export('borked', @var)" +
" msg(import('borked'))" +
")\n" +
"_derping()\n"+
"_derping()", fakePlayer);
verify(fakePlayer).sendMessage("null");
verify(fakePlayer, times(3)).sendMessage("{Am, I, borked?}");
}
@Test
public void testExportImportWithProcs2() throws Exception{
SRun("assign(@array, array(1, 2))"
+ "export('myarray', @array)", fakePlayer);
SRun("proc(_get, return(import('myarray')))"
+ "msg(_get())", fakePlayer);
verify(fakePlayer).sendMessage("{1, 2}");
}
@Test(timeout = 10000)
public void testIsBoolean() throws Exception {
SRun("msg(is_boolean(1)) msg(is_boolean(true))", fakePlayer);
verify(fakePlayer).sendMessage("false");
verify(fakePlayer).sendMessage("true");
}
@Test(timeout = 10000)
public void testIsInteger() throws Exception {
SRun("msg(is_integer(5.0)) msg(is_integer('s')) msg(is_integer(5))", fakePlayer);
verify(fakePlayer, times(2)).sendMessage("false");
verify(fakePlayer).sendMessage("true");
}
@Test(timeout = 10000)
public void testIsDouble() throws Exception {
SRun("msg(is_double(5)) msg(is_double('5.0')) msg(is_double(5.0))", fakePlayer);
verify(fakePlayer, times(2)).sendMessage("false");
verify(fakePlayer).sendMessage("true");
}
@Test(timeout = 10000)
public void testIsNull() throws Exception {
SRun("msg(is_null('null')) msg(is_null(null))", fakePlayer);
verify(fakePlayer).sendMessage("false");
verify(fakePlayer).sendMessage("true");
}
@Test(timeout = 10000)
public void testIsNumeric() throws Exception {
SRun("msg(is_numeric('s')) "
+ " msg(is_numeric(null))"
+ " msg(is_numeric(true))"
+ " msg(is_numeric(2))"
+ " msg(is_numeric(2.0))", fakePlayer);
verify(fakePlayer, times(1)).sendMessage("false");
verify(fakePlayer, times(4)).sendMessage("true");
}
@Test(timeout = 10000)
public void testIsIntegral() throws Exception {
SRun("msg(is_integral(5.5)) msg(is_integral(5)) msg(is_integral(4.0))", fakePlayer);
verify(fakePlayer).sendMessage("false");
verify(fakePlayer, times(2)).sendMessage("true");
}
@Test(timeout = 10000)
public void testDoubleCastToInteger() throws Exception {
SRun("msg(integer(4.5))", fakePlayer);
verify(fakePlayer).sendMessage("4");
}
@Test(timeout = 10000)
public void testClosure1() throws Exception {
SRun("assign(@go, closure(console( 'Hello World' ))) msg(@go)", fakePlayer);
verify(fakePlayer).sendMessage("console('Hello World')");
}
@Test(timeout = 10000)
public void testClosure2() throws Exception {
SRun("assign(@go, closure(msg('Hello World')))", fakePlayer);
verify(fakePlayer, times(0)).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure3() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@go, closure(msg('Hello' 'World')))\n"
+ "execute(@go)", fakePlayer);
verify(fakePlayer).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure4() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@hw, 'Hello World')\n"
+ "assign(@go, closure(msg(@hw)))\n"
+ "execute(@go)", fakePlayer);
verify(fakePlayer).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure5() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@hw, 'Nope')\n"
+ "assign(@go, closure(@hw, msg(@hw)))\n"
+ "execute('Hello World', @go)", fakePlayer);
verify(fakePlayer).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure6() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@hw, 'Hello World')\n"
+ "assign(@go, closure(msg(@hw)))\n"
+ "execute('Nope', @go)", fakePlayer);
verify(fakePlayer).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure7() throws Exception {
when(fakePlayer.isOp()).thenReturn(Boolean.TRUE);
SRun("assign(@go, closure(assign(@hw, 'Hello World'), msg(@hw)))\n"
+ "execute(@go)", fakePlayer);
verify(fakePlayer).sendMessage("Hello World");
}
@Test(timeout = 10000)
public void testClosure8() throws Exception {
when(fakePlayer.isOp()).thenReturn(true);
SRun("execute(Hello, World, closure(msg(@arguments)))", fakePlayer);
verify(fakePlayer).sendMessage("{Hello, World}");
}
@Test(timeout = 10000)
public void testClosure9() throws Exception {
when(fakePlayer.isOp()).thenReturn(true);
SRun("assign(@a, closure(@array, assign(@array[0], 'Hello World')))\n"
+ "assign(@value, array())\n"
+ "execute(@value, @a)\n"
+ "msg(@value)", fakePlayer);
verify(fakePlayer).sendMessage("{Hello World}");
}
@Test(timeout=10000)
public void testWhile() throws Exception{
SRun("assign(@i, 2) while(@i > 0, @i-- msg('hi'))", fakePlayer);
verify(fakePlayer, times(2)).sendMessage("hi");
}
@Test(timeout=10000)
public void testDoWhile() throws Exception{
SRun("assign(@i, 2) dowhile(@i-- msg('hi'), @i > 0)", fakePlayer);
verify(fakePlayer, times(2)).sendMessage("hi");
}
@Test
public void testToRadix() throws Exception {
assertEquals("f", SRun("to_radix(15, 16)", null));
assertEquals("1111", SRun("to_radix(15, 2)", null));
}
@Test
public void testParseInt() throws Exception {
assertEquals("15", SRun("parse_int('F', 16)", null));
assertEquals("15", SRun("parse_int('1111', 2)", null));
}
@Test
public void testClosureReturnsFromExecute() throws Exception {
assertEquals("3", SRun("execute(closure(return(3)))", fakePlayer));
}
}
| |
package com.ra4king.circuitsim.gui;
import static com.ra4king.circuitsim.gui.Properties.Direction.NORTH;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.ra4king.circuitsim.gui.Connection.PortConnection;
import com.ra4king.circuitsim.gui.Properties.Direction;
import com.ra4king.circuitsim.simulator.CircuitState;
import com.ra4king.circuitsim.simulator.Port.Link;
import com.ra4king.circuitsim.simulator.WireValue;
import com.ra4king.circuitsim.simulator.WireValue.State;
import javafx.geometry.Bounds;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
/**
* @author Roi Atalla
*/
public class GuiUtils {
// Can't instantiate this
private GuiUtils() {}
public static final int BLOCK_SIZE = 10;
private static class FontInfo {
int size;
boolean bold;
boolean oblique;
FontInfo(int size, boolean bold, boolean oblique) {
this.size = size;
this.bold = bold;
this.oblique = oblique;
}
@Override
public int hashCode() {
return size ^ (bold ? 0x1000 : 0) ^ (oblique ? 0x2000 : 0);
}
@Override
public boolean equals(Object other) {
if(!(other instanceof FontInfo)) {
return false;
}
FontInfo info = (FontInfo)other;
return info.size == this.size && info.bold == this.bold && info.oblique == this.oblique;
}
}
private static Map<FontInfo, Font> fonts = new HashMap<>();
public static Font getFont(int size) {
return getFont(size, false, false);
}
public static Font getFont(int size, boolean bold) {
return getFont(size, bold, false);
}
public static Font getFont(int size, boolean bold, boolean oblique) {
FontInfo info = new FontInfo(size, bold, oblique);
if(fonts.containsKey(info)) {
return fonts.get(info);
} else {
String fontFile;
if(bold && oblique) {
fontFile = "/fonts/DejaVuSansMono-BoldOblique.ttf";
} else if(bold) {
fontFile = "/fonts/DejaVuSansMono-Bold.ttf";
} else if(oblique) {
fontFile = "/fonts/DejaVuSansMono-Oblique.ttf";
} else {
fontFile = "/fonts/DejaVuSansMono.ttf";
}
Font font = Font.loadFont(GuiUtils.class.getResourceAsStream(fontFile), size);
fonts.put(info, font);
return font;
}
}
public static int getCircuitCoord(double a) {
return ((int)Math.round(a) + BLOCK_SIZE / 2) / BLOCK_SIZE;
}
public static int getScreenCircuitCoord(double a) {
return getCircuitCoord(a) * BLOCK_SIZE;
}
private static Map<Font, Map<String, Bounds>> boundsSeen = new HashMap<>();
public static Bounds getBounds(Font font, String string) {
return getBounds(font, string, true);
}
public static Bounds getBounds(Font font, String string, boolean save) {
if(save) {
Map<String, Bounds> strings = boundsSeen.computeIfAbsent(font, f -> new HashMap<>());
return strings.computeIfAbsent(string, s -> {
Text text = new Text(string);
text.setFont(font);
return text.getLayoutBounds();
});
} else {
Text text = new Text(string);
text.setFont(font);
return text.getLayoutBounds();
}
}
public interface Drawable {
void draw(int x, int y, int width, int height);
}
public static void drawShape(Drawable drawable, GuiElement element) {
drawable.draw(element.getScreenX(), element.getScreenY(), element.getScreenWidth(), element.getScreenHeight());
}
public static void drawName(GraphicsContext graphics, ComponentPeer<?> component, Direction direction) {
if(!component.getComponent().getName().isEmpty()) {
Bounds bounds = GuiUtils.getBounds(graphics.getFont(), component.getComponent().getName());
double x, y;
switch(direction) {
case EAST:
x = component.getScreenX() + component.getScreenWidth() + 5;
y = component.getScreenY() + (component.getScreenHeight() + bounds.getHeight()) * 0.4;
break;
case WEST:
x = component.getScreenX() - bounds.getWidth() - 3;
y = component.getScreenY() + (component.getScreenHeight() + bounds.getHeight()) * 0.4;
break;
case SOUTH:
x = component.getScreenX() + (component.getScreenWidth() - bounds.getWidth()) * 0.5;
y = component.getScreenY() + component.getScreenHeight() + bounds.getHeight();
break;
case NORTH:
x = component.getScreenX() + (component.getScreenWidth() - bounds.getWidth()) * 0.5;
y = component.getScreenY() - 5;
break;
default:
throw new IllegalArgumentException("How can Direction be anything else??");
}
graphics.setFill(Color.BLACK);
graphics.fillText(component.getComponent().getName(), x, y);
}
}
public static void drawValue(GraphicsContext graphics, String string, int x, int y, int width) {
Bounds bounds = GuiUtils.getBounds(graphics.getFont(), string, false);
if(string.length() == 1) {
graphics.fillText(string, x + (width - bounds.getWidth()) * 0.5, y + bounds.getHeight() * 0.75 + 1);
} else {
for(int i = 0, row = 1; i < string.length(); row++) {
String sub = string.substring(i, i + Math.min(8, string.length() - i));
i += sub.length();
graphics.fillText(sub, x + 1, y + bounds.getHeight() * 0.75 * row + 1);
}
}
}
/**
* Draws a clock input (triangle symbol) facing the southern border
*/
public static void drawClockInput(GraphicsContext graphics, Connection connection, Direction direction) {
double x = connection.getScreenX() + connection.getScreenWidth() * 0.5;
double y = connection.getScreenY() + connection.getScreenWidth() * 0.5;
switch(direction) {
case NORTH:
graphics.strokeLine(x - 5, y, x, y + 6);
graphics.strokeLine(x, y + 6, x + 5, y);
break;
case SOUTH:
graphics.strokeLine(x - 5, y, x, y - 6);
graphics.strokeLine(x, y - 6, x + 5, y);
break;
case EAST:
graphics.strokeLine(x, y - 5, x - 6, y);
graphics.strokeLine(x - 6, y, x, y + 5);
break;
case WEST:
graphics.strokeLine(x, y - 5, x + 6, y);
graphics.strokeLine(x + 6, y, x, y + 5);
break;
}
}
public static void setBitColor(GraphicsContext graphics, CircuitState circuitState, LinkWires linkWires) {
if(linkWires.isLinkValid()) {
Link link = linkWires.getLink();
if(link != null && circuitState != null) {
if(circuitState.isShortCircuited(link)) {
graphics.setStroke(Color.RED);
graphics.setFill(Color.RED);
} else {
setBitColor(graphics, circuitState.getMergedValue(link));
}
} else {
setBitColor(graphics, State.X);
}
} else {
graphics.setStroke(Color.ORANGE);
graphics.setFill(Color.ORANGE);
}
}
private static final Color ONE_COLOR = Color.GREEN.brighter();
private static final Color ZERO_COLOR = Color.GREEN.darker();
private static final Color X_1BIT_COLOR = Color.BLUE;
private static final Color X_MULTIBIT_COLOR = Color.BLUE.darker();
public static void setBitColor(GraphicsContext graphics, WireValue value) {
if(value.getBitSize() == 1) {
setBitColor(graphics, value.getBit(0));
} else if(value.isValidValue()) {
graphics.setStroke(Color.BLACK);
graphics.setFill(Color.BLACK);
} else {
graphics.setStroke(X_MULTIBIT_COLOR);
graphics.setFill(X_MULTIBIT_COLOR);
}
}
public static void setBitColor(GraphicsContext graphics, State bitState) {
switch(bitState) {
case ONE:
graphics.setStroke(ONE_COLOR);
graphics.setFill(ONE_COLOR);
break;
case ZERO:
graphics.setStroke(ZERO_COLOR);
graphics.setFill(ZERO_COLOR);
break;
case X:
graphics.setStroke(X_1BIT_COLOR);
graphics.setFill(X_1BIT_COLOR);
break;
}
}
public static PortConnection rotatePortCCW(PortConnection connection, boolean useWidth) {
int x = connection.getXOffset();
int y = connection.getYOffset();
int width = useWidth ? connection.getParent().getWidth() : connection.getParent().getHeight();
return new PortConnection(connection.getParent(),
connection.getPort(),
connection.getName(),
y, width - x);
}
public static void rotatePorts(List<PortConnection> connections,
Direction source,
Direction destination) {
List<Direction> order = Arrays.asList(Direction.EAST, NORTH, Direction.WEST, Direction.SOUTH);
Stream<PortConnection> stream = connections.stream();
int index = order.indexOf(source);
boolean useWidth = true;
while(order.get(index++ % order.size()) != destination) {
boolean temp = useWidth;
stream = stream.map(port -> rotatePortCCW(port, temp));
useWidth = !useWidth;
}
List<PortConnection> newConns = stream.collect(Collectors.toList());
connections.clear();
connections.addAll(newConns);
}
public static void rotateElementSize(GuiElement element, Direction source, Direction destination) {
List<Direction> order = Arrays.asList(Direction.EAST, NORTH, Direction.WEST, Direction.SOUTH);
int index = order.indexOf(source);
while(order.get(index++ % order.size()) != destination) {
int width = element.getWidth();
int height = element.getHeight();
element.setWidth(height);
element.setHeight(width);
}
}
/**
* Source orientation is assumed EAST
*/
public static void rotateGraphics(GuiElement element, GraphicsContext graphics, Direction direction) {
int x = element.getScreenX();
int y = element.getScreenY();
int width = element.getScreenWidth();
int height = element.getScreenHeight();
graphics.translate(x + width * 0.5, y + height * 0.5);
switch(direction) {
case NORTH:
graphics.rotate(270);
graphics.translate(-x - height * 0.5, -y - width * 0.5);
break;
case SOUTH:
graphics.rotate(90);
graphics.translate(-x - height * 0.5, -y - width * 0.5);
break;
case WEST:
graphics.rotate(180);
default:
graphics.translate(-x - width * 0.5, -y - height * 0.5);
}
}
}
| |
package org.hl7.fhir.instance.utils;
import java.util.List;
import org.hl7.fhir.instance.formats.IParser;
import org.hl7.fhir.instance.formats.ParserType;
import org.hl7.fhir.instance.model.ConceptMap;
import org.hl7.fhir.instance.model.OperationOutcome.IssueSeverity;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.ValueSet;
import org.hl7.fhir.instance.model.ValueSet.ConceptDefinitionComponent;
import org.hl7.fhir.instance.model.ValueSet.ConceptSetComponent;
import org.hl7.fhir.instance.model.ValueSet.ValueSetExpansionComponent;
import org.hl7.fhir.instance.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
import org.hl7.fhir.instance.validation.IResourceValidator;
/**
* This is the standard interface used for access to underlying FHIR
* services through the tools and utilities provided by the reference
* implementation.
*
* The functionality it provides is
* - get access to parsers, validators, narrative builders etc
* (you can't create these directly because they need access
* to the right context for their information)
*
* - find resources that the tools need to carry out their tasks
*
* - provide access to terminology services they need.
* (typically, these terminology service requests are just
* passed through to the local implementation's terminology
* service)
*
* @author Grahame
*/
public interface IWorkerContext {
// -- Parsers (read and write instances) ----------------------------------------
/**
* Get a parser to read/write instances. Use the defined type (will be extended
* as further types are added, though the only currently anticipate type is RDF)
*
* XML/JSON - the standard renderers
* XHTML - render the narrative only (generate it if necessary)
*
* @param type
* @return
*/
public IParser getParser(ParserType type);
/**
* Get a parser to read/write instances. Determine the type
* from the stated type. Supported value for type:
* - the recommended MIME types
* - variants of application/xml and application/json
* - _format values xml, json
*
* @param type
* @return
*/
public IParser getParser(String type);
/**
* Get a JSON parser
*
* @return
*/
public IParser newJsonParser();
/**
* Get an XML parser
*
* @return
*/
public IParser newXmlParser();
/**
* Get a generator that can generate narrative for the instance
*
* @return a prepared generator
*/
public INarrativeGenerator getNarrativeGenerator(String prefix, String basePath);
/**
* Get a validator that can check whether a resource is valid
*
* @return a prepared generator
* @throws Exception
*/
public IResourceValidator newValidator() throws Exception;
// -- resource fetchers ---------------------------------------------------
/**
* Find an identified resource. The most common use of this is to access the the
* standard conformance resources that are part of the standard - structure
* definitions, value sets, concept maps, etc.
*
* Also, the narrative generator uses this, and may access any kind of resource
*
* The URI is called speculatively for things that might exist, so not finding
* a matching resouce, return null, not an error
*
* The URI can have one of 3 formats:
* - a full URL e.g. http://acme.org/fhir/ValueSet/[id]
* - a relative URL e.g. ValueSet/[id]
* - a logical id e.g. [id]
*
* It's an error if the second form doesn't agree with class_. It's an
* error if class_ is null for the last form
*
* @param resource
* @param Reference
* @return
* @throws Exception
*/
public <T extends Resource> T fetchResource(Class<T> class_, String uri) throws EOperationOutcome, Exception;
/**
* find whether a resource is available.
*
* Implementations of the interface can assume that if hasResource ruturns
* true, the resource will usually be fetched subsequently
*
* @param class_
* @param uri
* @return
*/
public <T extends Resource> boolean hasResource(Class<T> class_, String uri);
// -- Terminology services ------------------------------------------------------
// these are the terminology services used internally by the tools
/**
* Find a value set for the nominated system uri.
* return null if there isn't one (then the tool might try
* supportsSystem)
*
* @param system
* @return
*/
public ValueSet fetchCodeSystem(String system);
/**
* True if the underlying terminology service provider will do
* expansion and code validation for the terminology. Corresponds
* to the extension
*
* http://hl7.org/fhir/StructureDefinition/conformance-supported-system
*
* in the Conformance resource
*
* @param system
* @return
*/
public boolean supportsSystem(String system);
/**
* find concept maps for a source
* @param url
* @return
*/
public List<ConceptMap> findMapsForSource(String url);
/**
* ValueSet Expansion - see $expand
*
* @param source
* @return
*/
public ValueSetExpansionOutcome expandVS(ValueSet source);
/**
* Value set expanion inside the internal expansion engine - used
* for references to supported system (see "supportsSystem") for
* which there is no value set.
*
* @param inc
* @return
*/
public ValueSetExpansionComponent expandVS(ConceptSetComponent inc);
public class ValidationResult {
private ConceptDefinitionComponent definition;
private IssueSeverity severity;
private String message;
public ValidationResult(IssueSeverity severity, String message) {
this.severity = severity;
this.message = message;
}
public ValidationResult(ConceptDefinitionComponent definition) {
this.definition = definition;
}
public ValidationResult(IssueSeverity severity, String message, ConceptDefinitionComponent definition) {
this.severity = severity;
this.message = message;
this.definition = definition;
}
public boolean isOk() {
return definition != null;
}
public String getDisplay() {
return definition == null ? "??" : definition.getDisplay();
}
public ConceptDefinitionComponent asConceptDefinition() {
return definition;
}
public IssueSeverity getSeverity() {
return severity;
}
public String getMessage() {
return message;
}
}
/**
* Validation of a code - consult the terminology service
* to see whether it is known. If known, return a description of it
*
* note: always return a result, with either an error or a code description
*
* corresponds to 2 terminology service calls: $validate-code and $lookup
*
* @param system
* @param code
* @param display
* @return
*/
public ValidationResult validateCode(String system, String code, String display);
/**
* Validation of a code - consult the terminology service
* to see whether it is known. If known, return a description of it
* Also, check whether it's in the provided value set
*
* note: always return a result, with either an error or a code description, or both (e.g. known code, but not in the value set)
*
* corresponds to 2 terminology service calls: $validate-code and $lookup
*
* @param system
* @param code
* @param display
* @return
*/
public ValidationResult validateCode(String system, String code, String display, ValueSet vs);
/**
* Validation of a code - consult the terminology service
* to see whether it is known. If known, return a description of it
* Also, check whether it's in the provided value set fragment (for supported systems with no value set definition)
*
* note: always return a result, with either an error or a code description, or both (e.g. known code, but not in the value set)
*
* corresponds to 2 terminology service calls: $validate-code and $lookup
*
* @param system
* @param code
* @param display
* @return
*/
public ValidationResult validateCode(String system, String code, String display, ConceptSetComponent vsi);
}
| |
package io.logz.jmx2graphite;
import com.codahale.metrics.graphite.GraphiteSender;
import com.google.common.base.Throwables;
import com.google.common.io.Closeables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.nurkiewicz.asyncretry.AsyncRetryExecutor;
import com.nurkiewicz.asyncretry.RetryExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.SocketFactory;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import java.util.regex.Pattern;
/**
* A client to a Carbon server that sends all metrics after they have been pickled in configurable sized batches
*
* NOTE: Thi is taken from com.codahale.metrics.graphite.PickledGraphite version 3.1.2, until they will
* add a write timeout
*/
public class PickledGraphite implements GraphiteSender {
private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class);
private final static int DEFAULT_BATCH_SIZE = 100;
private static final int DEFAULT_WRITE_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(20);
private int batchSize;
// graphite expects a python-pickled list of nested tuples.
private List<MetricTuple> metrics = new LinkedList<MetricTuple>();
private final String hostname;
private final int port;
private final InetSocketAddress address;
private final SocketFactory socketFactory;
private final Charset charset;
private Socket socket;
private Writer writer;
private int failures;
private long writeTimeoutMs;
private final ScheduledExecutorService scheduler;
private final RetryExecutor executor;
/**
* Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults
* to a batchSize of 100
*
* @param address
* the address of the Carbon server
*/
public PickledGraphite(InetSocketAddress address) {
this(address, DEFAULT_BATCH_SIZE);
}
/**
* Creates a new client which connects to the given address using the default {@link SocketFactory}.
*
* @param address
* the address of the Carbon server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
*/
public PickledGraphite(InetSocketAddress address, int batchSize) {
this(address, SocketFactory.getDefault(), batchSize);
}
/**
* Creates a new client which connects to the given address and socket factory.
*
* @param address
* the address of the Carbon server
* @param socketFactory
* the socket factory
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
*/
public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize) {
this(address, socketFactory, UTF_8, batchSize);
}
/**
* Creates a new client which connects to the given address and socket factory.
*
* @param address
* the address of the Carbon server
* @param socketFactory
* the socket factory
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
* @param writeTimeoutMs
* The timeout in milliseconds for writing the batched metrics to the socket (As a whole)
*/
public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize, int writeTimeoutMs) {
this(address, socketFactory, UTF_8, batchSize, writeTimeoutMs);
}
/**
* Creates a new client which connects to the given address and socket factory using the given character set.
*
* @param address
* the address of the Carbon server
* @param socketFactory
* the socket factory
* @param charset
* the character set used by the server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
*/
public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize) {
this(address, socketFactory, charset, batchSize, DEFAULT_WRITE_TIMEOUT_MS);
}
/**
* Creates a new client which connects to the given address and socket factory using the given character set.
*
* @param address
* the address of the Carbon server
* @param socketFactory
* the socket factory
* @param charset
* the character set used by the server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
* @param writeTimeoutMs
* The timeout in milliseconds for writing the batched metrics to the socket (As a whole)
*/
public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize,
int writeTimeoutMs) {
this(address, null, -1, socketFactory, charset, batchSize, writeTimeoutMs);
}
/**
* Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults
* to a batchSize of 100
*
* @param hostname
* the hostname of the Carbon server
* @param port
* the port of the Carbon server
*/
public PickledGraphite(String hostname, int port) {
this(hostname, port, DEFAULT_BATCH_SIZE);
}
/**
* Creates a new client which connects to the given address using the default {@link SocketFactory}.
*
* @param hostname
* the hostname of the Carbon server
* @param port
* the port of the Carbon server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
*/
public PickledGraphite(String hostname, int port, int batchSize) {
this(hostname, port, SocketFactory.getDefault(), batchSize, DEFAULT_WRITE_TIMEOUT_MS);
}
/**
* Creates a new client which connects to the given address using the default {@link SocketFactory}.
*
* @param hostname
* the hostname of the Carbon server
* @param port
* the port of the Carbon server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
* @param writeTimeoutMs
* The timeout in milliseconds for writing the batched metrics to the socket (As a whole)
*/
public PickledGraphite(String hostname, int port, int batchSize, int writeTimeoutMs) {
this(hostname, port, SocketFactory.getDefault(), batchSize, writeTimeoutMs);
}
/**
* Creates a new client which connects to the given address and socket factory.
*
* @param hostname
* the hostname of the Carbon server
* @param port
* the port of the Carbon server
* @param socketFactory
* the socket factory
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
* @param writeTimeoutMs
* The timeout in milliseconds for writing the batched metrics to the socket (As a whole)
*/
public PickledGraphite(String hostname, int port, SocketFactory socketFactory, int batchSize, int writeTimeoutMs) {
this(null, hostname, port, socketFactory, UTF_8, batchSize, writeTimeoutMs);
}
/**
* Creates a new client which connects to the given address and socket factory using the given character set.
*
* @param hostname
* the hostname of the Carbon server
* @param port
* the port of the Carbon server
* @param socketFactory
* the socket factory
* @param charset
* the character set used by the server
* @param batchSize
* how many metrics are bundled into a single pickle request to graphite
* @param writeTimeoutMs
* The timeout in milliseconds for writing the batched metrics to the socket (As a whole)
*/
public PickledGraphite(InetSocketAddress address, String hostname, int port, SocketFactory socketFactory, Charset charset, int batchSize,
int writeTimeoutMs) {
this.address = address;
this.hostname = hostname;
this.port = port;
this.socketFactory = socketFactory;
this.charset = charset;
this.batchSize = batchSize;
this.writeTimeoutMs = writeTimeoutMs;
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("Jmx2GraphitePickledSender-%d")
.build();
scheduler = Executors.newSingleThreadScheduledExecutor(threadFactory);
executor = new AsyncRetryExecutor(scheduler)
.retryIf(this::brokenPipe)
.retryOn(SocketException.class)
.withExponentialBackoff(500, 2) //500ms times 2 after each retry
.withMaxDelay(writeTimeoutMs)
.withUniformJitter() //add between +/- 100 ms randomly
.withMaxRetries(3)
.firstRetryNoDelay();
}
private boolean brokenPipe(Throwable t) {
return t instanceof SocketException && "Broken pipe".equals(t.getMessage());
}
@Override
public void connect() throws IllegalStateException, IOException {
if (isConnected()) {
throw new IllegalStateException("Already connected");
}
InetSocketAddress address = this.address;
if (address == null) {
address = new InetSocketAddress(hostname, port);
}
if (address.getAddress() == null) {
throw new UnknownHostException(address.getHostName());
}
this.socket = socketFactory.createSocket(address.getAddress(), address.getPort());
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset));
LOGGER.debug("Connected to graphite at "+address);
}
@Override
public boolean isConnected() {
return socket != null && socket.isConnected() && !socket.isClosed();
}
/**
* Convert the metric to a python tuple of the form:
* <p/>
* (timestamp, (name, value))
* <p/>
* And add it to the list of metrics. If we reach the batch size, write them out.
*
* @param name
* the name of the metric
* @param value
* the value of the metric
* @param timestamp
* the timestamp of the metric
* @throws IOException
* if there was an error sending the metric
*/
@Override
public void send(String name, String value, long timestamp) throws IOException {
metrics.add(new MetricTuple(sanitize(name), timestamp, sanitize(value)));
if (metrics.size() >= batchSize) {
writeMetrics();
}
}
@Override
public void flush() throws IOException {
writeMetrics();
if (writer != null) {
writer.flush();
}
}
private void disconnect() throws IOException {
try {
Closeables.close(writer, true);
} finally {
Closeables.close(socket, true);
this.socket = null;
this.writer = null;
}
}
@Override
public void close() throws IOException {
try {
flush();
} finally {
disconnect();
}
}
@Override
public int getFailures() {
return failures;
}
private void ensureConnected() throws IOException {
if (!isConnected()) connect();
}
/**
* 1. Run the pickler script to package all the pending metrics into a single message
* 2. Send the message to graphite
* 3. Clear out the list of metrics
*/
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
private void writeMetrics() throws IOException {
try {
executor.doWithRetry(retryContext -> {
if (retryContext.getRetryCount() > 0) {
LOGGER.info("Failed writing metrics (Error: "+retryContext.getLastThrowable()+"). Trying again (Retry #"+retryContext.getRetryCount()+")");
}
tryWritingMetrics();
if (retryContext.getRetryCount() > 0) {
LOGGER.info("Successfully wrote metrics at attempt #"+(retryContext.getRetryCount()+1));
}
}).get(writeTimeoutMs, TimeUnit.MILLISECONDS);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Wrote {} metrics", metrics.size());
}
} catch (InterruptedException e) {
this.failures++;
throw new RuntimeException("Got interrupted while waiting for pickled metrics to be finished writing to the socket", e);
} catch (ExecutionException e) {
this.failures++;
throw new RuntimeException("Failed writing pickled metrics to the socket: "+e.getCause().getMessage(), e.getCause());
} catch (TimeoutException e) {
// In case of timeouts let's close so that next write will attempt to open a new socket
disconnect();
throw new IOException("Got timeout ("+writeTimeoutMs+"ms) on waiting for pickled metrics to be written to the socket");
} finally {
// if there was an error, we might miss some data. for now, drop those on the floor and
// try to keep going.
metrics.clear();
}
// if (metrics.size() > 0) {
// try {
// byte[] payload = pickleMetrics(metrics);
// byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array();
//
// Future<?> future = executorService.submit(() -> {
// try {
// OutputStream outputStream = socket.getOutputStream();
// outputStream.write(header);
// outputStream.write(payload);
// outputStream.flush();
// } catch (SocketException e) {
// if (e.getMessage().equals("Broken pipe")) {
// try {
// disconnect();
// } catch (IOException e2) {
// LOGGER.warn("Failed to disconnect from Graphite", e);
// }
// throw e;
// }
// } catch (IOException e) {
// throw Throwables.propagate(e);
// }
// });
//
// try {
// future.get(writeTimeoutMs, TimeUnit.MILLISECONDS);
// } catch (InterruptedException e) {
// this.failures++;
// throw new RuntimeException("Got interrupted while waiting for pickled metrics to be finished writing to the socket", e);
// } catch (ExecutionException e) {
// this.failures++;
// throw new RuntimeException("Failed writing pickled metrics to the socket: "+e.getCause().getMessage(), e.getCause());
// } catch (TimeoutException e) {
// // In case of timeouts let's close so that next write will attempt to open a new socket
// disconnect();
// throw new IOException("Got timeout on waiting for pickled metrics to be written to the socket");
// }
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Wrote {} metrics", metrics.size());
// }
// } catch (IOException e) {
// this.failures++;
// throw e;
// } finally {
// // if there was an error, we might miss some data. for now, drop those on the floor and
// // try to keep going.
// metrics.clear();
// }
// }
}
private void tryWritingMetrics() throws IOException {
if (metrics.size() > 0) {
ensureConnected();
try {
byte[] payload = pickleMetrics(metrics);
byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(header);
outputStream.write(payload);
outputStream.flush();
} catch (SocketException e) {
if (e.getMessage().equals("Broken pipe")) {
try {
LOGGER.info("Pipe (socket) is broken - disconnecting from Graphite");
disconnect();
} catch (IOException e2) {
LOGGER.warn("Failed to disconnect from Graphite", e);
}
throw e;
}
}
}
}
/**
* Minimally necessary pickle opcodes.
*/
private final char
MARK = '(',
STOP = '.',
LONG = 'L',
STRING = 'S',
APPEND = 'a',
LIST = 'l',
TUPLE = 't',
QUOTE = '\'',
LF = '\n';
/**
* See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html
*
* @throws IOException
*/
byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); // Extremely rough estimate of 75 bytes per message
Writer pickled = new OutputStreamWriter(out, charset);
pickled.append(MARK);
pickled.append(LIST);
for (MetricTuple tuple : metrics) {
// start the outer tuple
pickled.append(MARK);
// the metric name is a string.
pickled.append(STRING);
// the single quotes are to match python's repr("abcd")
pickled.append(QUOTE);
pickled.append(tuple.name);
pickled.append(QUOTE);
pickled.append(LF);
// start the inner tuple
pickled.append(MARK);
// timestamp is a long
pickled.append(LONG);
pickled.append(Long.toString(tuple.timestamp));
// the trailing L is to match python's repr(long(1234))
pickled.append(LONG);
pickled.append(LF);
// and the value is a string.
pickled.append(STRING);
pickled.append(QUOTE);
pickled.append(tuple.value);
pickled.append(QUOTE);
pickled.append(LF);
pickled.append(TUPLE); // inner close
pickled.append(TUPLE); // outer close
pickled.append(APPEND);
}
// every pickle ends with STOP
pickled.append(STOP);
pickled.flush();
return out.toByteArray();
}
static class MetricTuple {
String name;
long timestamp;
String value;
MetricTuple(String name, long timestamp, String value) {
this.name = name;
this.timestamp = timestamp;
this.value = value;
}
}
protected String sanitize(String s) {
return WHITESPACE.matcher(s).replaceAll("-");
}
}
| |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.cpp;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ResourceSet;
import com.google.devtools.build.lib.actions.RunfilesSupplier;
import com.google.devtools.build.lib.analysis.actions.CommandLine;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Action used by LTOBackendArtifacts to create an LTOBackendAction. Similar to {@link SpawnAction},
* except that inputs are discovered from the imports file created by the ThinLTO indexing step for
* each backend artifact.
*
* <p>See {@link LTOBackendArtifacts} for a high level description of the ThinLTO build process. The
* LTO indexing step takes all bitcode .o files and decides which other .o file symbols can be
* imported/inlined. The additional input files for each backend action are then written to an
* imports file. Therefore these new inputs must be discovered here by subsetting the imports paths
* from the set of all bitcode artifacts, before executing the backend action.
*
* <p>For more information on ThinLTO see
* http://blog.llvm.org/2016/06/thinlto-scalable-and-incremental-lto.html.
*/
public final class LTOBackendAction extends SpawnAction {
private Collection<Artifact> mandatoryInputs;
private Map<PathFragment, Artifact> bitcodeFiles;
private Artifact imports;
private static final String GUID = "72ce1eca-4625-4e24-a0d8-bb91bb8b0e0e";
public LTOBackendAction(
Collection<Artifact> inputs,
Map<PathFragment, Artifact> allBitcodeFiles,
Artifact importsFile,
Collection<Artifact> outputs,
ActionOwner owner,
CommandLine argv,
boolean isShellCommand,
Map<String, String> environment,
Set<String> clientEnvironmentVariables,
Map<String, String> executionInfo,
String progressMessage,
RunfilesSupplier runfilesSupplier,
String mnemonic) {
super(
owner,
ImmutableList.<Artifact>of(),
inputs,
outputs,
AbstractAction.DEFAULT_RESOURCE_SET,
argv,
isShellCommand,
ImmutableMap.copyOf(environment),
ImmutableSet.copyOf(clientEnvironmentVariables),
ImmutableMap.copyOf(executionInfo),
progressMessage,
runfilesSupplier,
mnemonic,
false,
null);
mandatoryInputs = inputs;
bitcodeFiles = allBitcodeFiles;
imports = importsFile;
}
@Override
public boolean discoversInputs() {
return true;
}
private Set<Artifact> computeBitcodeInputs(Collection<PathFragment> inputPaths) {
HashSet<Artifact> bitcodeInputs = new HashSet<>();
for (PathFragment inputPath : inputPaths) {
Artifact inputArtifact = bitcodeFiles.get(inputPath);
if (inputArtifact != null) {
bitcodeInputs.add(inputArtifact);
}
}
return bitcodeInputs;
}
@Nullable
@Override
public Iterable<Artifact> discoverInputs(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException, InterruptedException {
// Build set of files this LTO backend artifact will import from.
HashSet<PathFragment> importSet = new HashSet<>();
try {
for (String line : FileSystemUtils.iterateLinesAsLatin1(imports.getPath())) {
if (!line.isEmpty()) {
PathFragment execPath = PathFragment.create(line);
if (execPath.isAbsolute()) {
throw new ActionExecutionException(
"Absolute paths not allowed in imports file " + imports.getPath() + ": " + execPath,
this,
false);
}
importSet.add(PathFragment.create(line));
}
}
} catch (IOException e) {
throw new ActionExecutionException(
"error iterating imports file " + imports.getPath(), e, this, false);
}
// Convert the import set of paths to the set of bitcode file artifacts.
Set<Artifact> bitcodeInputSet = computeBitcodeInputs(importSet);
if (bitcodeInputSet.size() != importSet.size()) {
throw new ActionExecutionException(
"error computing inputs from imports file " + imports.getPath(), this, false);
}
updateInputs(createInputs(bitcodeInputSet, getMandatoryInputs()));
return bitcodeInputSet;
}
@Override
public Collection<Artifact> getMandatoryInputs() {
return mandatoryInputs;
}
private static Iterable<Artifact> createInputs(
Set<Artifact> newInputs, Collection<Artifact> curInputs) {
Set<Artifact> result = new LinkedHashSet<>(newInputs);
result.addAll(curInputs);
return result;
}
@Override
public Iterable<Artifact> getAllowedDerivedInputs() {
return bitcodeFiles.values();
}
@Override
public void execute(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException, InterruptedException {
super.execute(actionExecutionContext);
}
@Override
protected String computeKey() {
Fingerprint f = new Fingerprint();
f.addString(GUID);
f.addStrings(getArguments());
f.addString(getMnemonic());
f.addPaths(getRunfilesSupplier().getRunfilesDirs());
ImmutableList<Artifact> runfilesManifests = getRunfilesSupplier().getManifests();
for (Artifact runfilesManifest : runfilesManifests) {
f.addPath(runfilesManifest.getExecPath());
}
for (Artifact input : getMandatoryInputs()) {
f.addPath(input.getExecPath());
}
for (PathFragment bitcodePath : bitcodeFiles.keySet()) {
f.addPath(bitcodePath);
}
f.addPath(imports.getExecPath());
f.addStringMap(getEnvironment());
f.addStringMap(getExecutionInfo());
return f.hexDigestAndReset();
}
/** Builder class to construct {@link LTOBackendAction} instances. */
public static class Builder extends SpawnAction.Builder {
private Map<PathFragment, Artifact> bitcodeFiles;
private Artifact imports;
public Builder addImportsInfo(
Map<PathFragment, Artifact> allBitcodeFiles, Artifact importsFile) {
this.bitcodeFiles = allBitcodeFiles;
this.imports = importsFile;
return this;
}
@Override
protected SpawnAction createSpawnAction(
ActionOwner owner,
NestedSet<Artifact> tools,
NestedSet<Artifact> inputsAndTools,
ImmutableList<Artifact> outputs,
ResourceSet resourceSet,
CommandLine actualCommandLine,
boolean isShellCommand,
ImmutableMap<String, String> env,
ImmutableSet<String> clientEnvironmentVariables,
ImmutableMap<String, String> executionInfo,
String progressMessage,
RunfilesSupplier runfilesSupplier,
String mnemonic) {
return new LTOBackendAction(
inputsAndTools.toCollection(),
bitcodeFiles,
imports,
outputs,
owner,
actualCommandLine,
isShellCommand,
env,
clientEnvironmentVariables,
executionInfo,
progressMessage,
runfilesSupplier,
mnemonic);
}
}
}
| |
package com.abewy.android.apps.klyph.facebook.request;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.abewy.android.apps.klyph.core.graph.GraphObject;
import com.abewy.android.apps.klyph.core.graph.GraphType;
import com.abewy.android.apps.klyph.core.request.RequestQuery;
import com.facebook.HttpMethod;
/**
* @author Jonathan
*
*/
public abstract class KlyphQuery implements RequestQuery
{
private boolean hasMoreData = true;
public KlyphQuery()
{
}
@Override
public boolean isFQL()
{
return true;
}
@Override
public boolean isMultiQuery()
{
return false;
}
@Override
public boolean isBatchQuery()
{
return false;
}
@Override
public String getQuery(String id, String offset)
{
return "";
}
@Override
public String getQuery(List<GraphObject> previousResults, String id, String offset)
{
return "";
}
@Override
public HttpMethod getHttpMethod()
{
return HttpMethod.GET;
}
@Override
public Bundle getParams()
{
return null;
}
@Override
public boolean returnId()
{
return false;
}
@Override
public List<GraphObject> handleResult(JSONObject result)
{
return null;
}
@Override
public List<GraphObject> handleResult(JSONArray result)
{
return null;
}
@Override
public List<GraphObject> handleResult(JSONArray[] result)
{
return null;
}
@Override
public List<GraphObject> handleResult(List<GraphObject> previousResults, JSONArray result)
{
return null;
}
@Override
public List<GraphObject> handleResult(List<GraphObject> previousResults, JSONArray[] result)
{
return null;
}
@Override
public RequestQuery getNextQuery()
{
return null;
}
@Override
public boolean isNextQuery()
{
return false;
}
protected String getOffset(String offset, String defaultOffset)
{
if (offset != null)
return offset;
return defaultOffset;
}
protected String multiQuery(String... queries)
{
String query = "{";
for (int i = 0; i < queries.length; i++)
{
String q = queries[i];
query += "'query" + (i + 1) + "':'" + q + "'";
if (i < queries.length - 1)
query += ",";
}
query += "}";
return query;
}
protected void assocData(JSONArray initData, JSONArray addData, String initKey, String addKey, String initValue, String addValue)
{
assocData(initData, addData, initKey, addKey, initValue, addValue, null, null);
}
protected void assocData(JSONArray initData, JSONArray addData, String initKey, String addKey, String initValue, String addValue,
String initType, GraphType addType)
{
for (int i = 0; i < initData.length(); i++)
{
try
{
JSONObject initObject = initData.getJSONObject(i);
for (int j = 0; j < addData.length(); j++)
{
JSONObject addObject = addData.getJSONObject(j);
if (initObject.optJSONArray(initKey) != null)
{
JSONArray initArray = initObject.optJSONArray(initKey);
for (int k = 0; k < initArray.length(); k++)
{
Object fromKeyValue = initArray.get(k);
Object toKeyValue = addObject.get(addKey);
if (fromKeyValue != null && fromKeyValue.equals(toKeyValue))
{
initObject.accumulate(initValue, addObject.get(addValue));
if (initType != null)
initObject.accumulate(initType, addType);
}
}
}
else
{
Object fromKeyValue = initObject.get(initKey);
Object toKeyValue = addObject.get(addKey);
if (fromKeyValue != null && fromKeyValue.equals(toKeyValue))
{
initObject.put(initValue, addObject.get(addValue));
if (initType != null)
initObject.put(initType, addType);
}
}
}
}
catch (JSONException e)
{
Log.d("KlyphQuery", "assoc_data " + e.getMessage());
}
}
}
protected void assocData2(JSONArray initData, JSONArray addData, String initKey, String addKey, String initValue, String addValue,
String initType, String addType)
{
for (int i = 0; i < initData.length(); i++)
{
try
{
JSONObject initObject = initData.getJSONObject(i);
for (int j = 0; j < addData.length(); j++)
{
JSONObject addObject = addData.getJSONObject(j);
if (initObject.optJSONArray(initKey) != null)
{
JSONArray initArray = initObject.optJSONArray(initKey);
for (int k = 0; k < initArray.length(); k++)
{
Object fromKeyValue = initArray.get(k);
Object toKeyValue = addObject.get(addKey);
if (fromKeyValue != null && fromKeyValue.equals(toKeyValue))
{
initObject.accumulate(initValue, addObject.get(addValue));
if (initType != null)
initObject.accumulate(initType, addObject.get(addType));
}
}
}
else
{
Object fromKeyValue = initObject.get(initKey);
Object toKeyValue = addObject.get(addKey);
if (fromKeyValue != null && fromKeyValue.equals(toKeyValue))
{
initObject.put(initValue, addObject.get(addValue));
if (initType != null)
initObject.put(initType, addObject.get(addType));
}
}
}
}
catch (JSONException e)
{}
}
}
/**
* Assoc a string array with an object array
*/
protected void assocData3(JSONArray initData, JSONArray addData, String initKey, String addKey, String putKey)
{
for (int i = 0; i < initData.length(); i++)
{
JSONObject initObject = initData.optJSONObject(i);
if (initObject.optJSONArray(initKey) != null)
{
JSONArray initArray = initObject.optJSONArray(initKey);
for (int j = 0; j < initArray.length(); j++)
{
String value = initArray.optString(j);
for (int k = 0; k < addData.length(); k++)
{
JSONObject addObject = addData.optJSONObject(k);
if (addObject != null)
{
String addValue = addObject.optString(addKey);
if (value.equals(addValue))
{
try
{
if (initObject.optJSONArray(putKey) == null)
initObject.putOpt(putKey, new JSONArray());
initObject.accumulate(putKey, addObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
}
}
}
}
/**
*
*/
protected void assocStreamToEvent(JSONArray streams, JSONArray events)
{
for (int i = 0; i < streams.length(); i++)
{
JSONObject initObject = streams.optJSONObject(i);
String postId = initObject.optString("post_id");
postId = postId.substring(postId.indexOf("_") + 1);
for (int j = 0; j < events.length(); j++)
{
JSONObject event = events.optJSONObject(j);
String eid = event.optString("eid");
if (postId.equals(eid))
{
try
{
initObject.putOpt("event", event);
}
catch (JSONException e)
{
// e.printStackTrace();
}
}
}
}
}
protected void assocStreamToLikedPages(JSONArray streams, JSONArray pages)
{
for (int i = 0; i < streams.length(); i++)
{
JSONObject initObject = streams.optJSONObject(i);
int type = initObject.optInt("type");
if (type != 161 && type != 0)
continue;
JSONArray arrayTags = initObject.optJSONArray("description_tags");
JSONObject objectTags = initObject.optJSONObject("description_tags");
if (arrayTags != null && arrayTags.length() > 0)
{
JSONArray subArray = arrayTags.optJSONArray(0);
for (int j = 0; j < subArray.length(); j++)
{
JSONObject o = subArray.optJSONObject(j);
String id = o.optString("id");
for (int k = 0; k < pages.length(); k++)
{
JSONObject page = pages.optJSONObject(k);
String pageId = page.optString("page_id");
if (id.equals(pageId))
{
try
{
initObject.accumulate("liked_pages", page);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
}
else if (objectTags != null)
{
for (Iterator iterator = objectTags.keys(); iterator.hasNext();)
{
String key = (String) iterator.next();
JSONArray subArray = objectTags.optJSONArray(key);
for (int j = 0; j < subArray.length(); j++)
{
JSONObject o = subArray.optJSONObject(j);
String id = o.optString("id");
for (int k = 0; k < pages.length(); k++)
{
JSONObject page = pages.optJSONObject(k);
String pageId = page.optString("page_id");
if (id.equals(pageId))
{
try
{
if (initObject.optJSONArray("liked_pages") == null)
initObject.putOpt("liked_pages", new JSONArray());
initObject.accumulate("liked_pages", page);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
}
}
}
}
protected void assocStreamToObjectBySubPostId(JSONArray left, JSONArray right, String rightId, String leftParam)
{
int n = left.length();
int m = right.length();
for (int i = 0; i < n; i++)
{
JSONObject leftObject = left.optJSONObject(i);
String leftIdValue = leftObject.optString("post_id");
int index = leftIdValue.indexOf("_");
leftIdValue = leftIdValue.substring(index + 1);
for (int j = 0; j < m; j++)
{
JSONObject rightObject = right.optJSONObject(j);
String rightIdValue = rightObject.optString(rightId);
if (leftIdValue.equals(rightIdValue))
{
try
{
leftObject.putOpt(leftParam, rightObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
}
protected void assocStreamToObjectById(JSONArray left, JSONArray right, String leftId, String rightId, String leftParam)
{
int n = left.length();
int m = right.length();
for (int i = 0; i < n; i++)
{
JSONObject leftObject = left.optJSONObject(i);
String leftIdValue = leftObject.optString(leftId);
for (int j = 0; j < m; j++)
{
JSONObject rightObject = right.optJSONObject(j);
String rightIdValue = rightObject.optString(rightId);
if (leftIdValue.equals(rightIdValue))
{
try
{
leftObject.putOpt(leftParam, rightObject);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
}
protected void assocStreamToStatus(JSONArray streams, JSONArray status)
{
for (int i = 0; i < streams.length(); i++)
{
boolean found = false;
JSONObject initObject = streams.optJSONObject(i);
String pId = initObject.optString("post_id");
int startIndex = pId.indexOf("_");
if (startIndex > -1)
{
String subId = pId.substring(startIndex + 1);
for (int j = 0, n = status.length(); j < n; j++)
{
JSONObject s = status.optJSONObject(j);
String sId = s.optString("status_id");
if (sId != null && subId.equals(sId))
{
try
{
initObject.putOpt("status", s);
}
catch (JSONException e)
{
Log.d("KlyphQuery", "assocStreamToStatus error " + e.getMessage());
}
found = true;
break;
}
}
}
if (found == true)
continue;
JSONObject attachment = initObject.optJSONObject("attachment");
if (attachment != null)
{
String id = attachment.optString("href");
int index = id.indexOf("posts/");
if (index == -1)
continue;
id = id.substring(index + 6);
for (int j = 0; j < status.length(); j++)
{
JSONObject s = status.optJSONObject(j);
String sId = s.optString("status_id");
if (id.equals(sId))
{
try
{
initObject.putOpt("status", s);
}
catch (JSONException e)
{
Log.d("KlyphQuery", "assocStreamToStatus error " + e.getMessage());
}
break;
}
}
}
}
}
protected void assocPostToPhoto(JSONArray posts, JSONArray photos)
{
assocPostToObjectById("photo", posts, photos, "object_id", "id", "photoObject");
}
protected void assocPostToVideo(JSONArray posts, JSONArray videos)
{
assocPostToObjectById("video", posts, videos, "object_id", "id", "videoObject");
}
protected void assocPostToLink(JSONArray posts, JSONArray links)
{
assocPostToObjectById("link", posts, links, "object_id", "id", "linkObject");
}
private void assocPostToObjectById(String type, JSONArray left, JSONArray right, String leftId, String rightId, String leftParam)
{
int n = left.length();
int m = right.length();
for (int i = 0; i < n; i++)
{
JSONObject leftObject = left.optJSONObject(i);
String lType = leftObject.optString("type");
if (lType == null || !lType.equals(type))
continue;
String leftIdValue = leftObject.optString(leftId);
if (leftIdValue == null)
continue;
for (int j = 0; j < m; j++)
{
JSONObject rightObject = right.optJSONObject(j);
String rightIdValue = rightObject.optString(rightId);
if (leftIdValue.equals(rightIdValue))
{
try
{
leftObject.putOpt(leftParam, rightObject);
}
catch (JSONException e)
{
Log.d("KlyphQuery", "Exception " + e.getMessage());
e.printStackTrace();
}
break;
}
}
}
}
@Override
public boolean hasMoreData()
{
return hasMoreData;
}
/**
* Take care ! Tables checkins, feed, home, links, notes, photos, posts,
* statuses, tagged, videos may return subset results, meaning that result
* count may be different than the offset limit parameter
*
* @param hasMoreData
* true if hasMoreData, false otherwise.
*/
protected void setHasMoreData(boolean hasMoreData)
{
this.hasMoreData = hasMoreData;
}
protected boolean isOffsetDefined(String offset)
{
return offset != null && offset.length() > 0;
}
}
| |
package com.js.jsonTest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.js.json.*;
import com.js.testUtils.*;
import static com.js.basic.Tools.*;
import static com.js.json.JSONTools.*;
public class JSONTest extends MyTest {
private JSONParser json(String s) {
json = new JSONParser(s);
return json;
}
private JSONParser json;
public void testNumbers() {
String script[] = { "0", "1", "-123.52e20", "-123.52e-20", "0.5" };
for (int i = 0; i < script.length; i++) {
String s = script[i];
json(s);
double d = json.nextDouble();
assertFalse(json.hasNext());
assertEquals(Double.parseDouble(s), d, 1e-10);
}
}
public void testBadNumbers() {
// final boolean db = true;
if (db)
pr("\n\n\n\n----------------------------------------------------------\ntestBadNumbers\n");
String script[] = { "-", "00", "12.", ".42", "123ee", "123e-", };
for (int i = 0; i < script.length; i++) {
String s = script[i];
if (db)
pr("\n-----------------\n constructing json for '" + s + "'");
try {
json(s);
fail("expected exception with '" + s + "'");
} catch (JSONException e) {
}
}
if (db)
pr("\n\n\n");
}
private JSONEncoder newEnc() {
enc = null;
return enc();
}
private JSONEncoder enc() {
if (enc == null)
enc = new JSONEncoder();
return enc;
}
private JSONEncoder enc;
public void testStreamConstructor() throws UnsupportedEncodingException {
String orig = "[0,1,2,3,\"hello\"]";
InputStream stream = new ByteArrayInputStream(orig.getBytes("UTF-8"));
json = new JSONParser(stream);
Object a = json.next();
assertTrue(a instanceof ArrayList);
enc().encode(a);
String s = enc.toString();
assertStringsMatch(s, orig);
}
public void testArray() {
String orig = "[0,1,2,3,\"hello\"]";
json(orig);
json.enterList();
for (int i = 0; i < 4; i++) {
assertTrue(json.hasNext());
assertEquals(i, json.nextInt());
}
assertTrue(json.hasNext());
assertStringsMatch("hello", json.nextString());
assertFalse(json.hasNext());
json.exit();
}
public void testReadMapAsSingleObject() {
String s = "{'description':{'type':'text','hint':'enter something here'}}";
s = swapQuotes(s);
json(s);
Map map = (Map) json.next();
assertTrue(map.containsKey("description"));
}
public void testMap() {
String orig = "{\"u\":14,\"m\":false,\"w\":null,\"k\":true}";
json(orig);
json.enterMap();
Map m = new HashMap();
for (int i = 0; i < 4; i++) {
String key = json.nextKey();
Object value = json.next();
assertFalse(m.containsKey(key));
m.put(key, value);
}
json.exit();
assertStringsMatch(m.get("u"), "14.0");
assertStringsMatch(m.get("m"), "false");
assertTrue(m.get("w") == null);
assertStringsMatch(m.get("k"), "true");
}
public void testEncodeMap() {
JSONEncoder enc = new JSONEncoder();
enc.enterMap();
enc.encode("a");
enc.enterList();
enc.encode(12);
enc.encode(17);
enc.exit();
enc.encode("b");
enc.encode(true);
enc.exit();
String s = enc.toString();
assertStringsMatch("{\"a\":[12,17],\"b\":true}", s);
}
public void testArrays() {
int[] intArray = { 1, 2, 3, 4 };
enc().encode(intArray);
String s = enc.toString();
assertStringsMatch(s, "[1,2,3,4]");
}
public void testString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append((char) i);
}
String originalString = sb.toString();
enc().encode(originalString);
String jsonString = enc.toString();
json(jsonString);
String decodedString = json.nextString();
assertStringsMatch(decodedString, originalString);
}
public void testSymmetry() {
String script[] = {//
"0",//
"1",//
"-1.2352E20",//
"-1.2352E-20",//
"0.5",//
"{'hey':42}", //
"[1,2,3,4]",//
"{'hey':42,'you':43}",//
"{'hey':{'you':17},'array':[1,2,3,4]}",//
"{'trailing number':5}",//
"{ 'favorite song': { '_skip_order': 3, 'type': 'text','hint': 'name of song','zminlines': 5 },'wow':12 } ",//
};
for (int i = 0; i < script.length; i++) {
String s = swapQuotes(script[i]);
if (db)
pr("\n testing '" + s + "'");
json(s);
Object obj = json.next();
assertFalse(json.hasNext());
if (db)
pr(" parsed " + obj + " (type = " + obj.getClass() + ")");
newEnc().encode(obj);
String s2 = enc.toString();
if (db)
pr(" encoded is " + s2);
Object obj2 = json(s2).next();
if (db)
pr("parsed object: " + obj2);
newEnc().encode(obj2);
String s3 = enc.toString();
assertStringsMatch(s2, s3);
}
}
public void testComments() {
String script[] = {//
"{'hey':// this is a comment\n // this is also a comment\n 42}",//
"{'hey':42}",//
"[42,15// start of comment\n//Another comment immediately\n //Another comment after spaces\n,16]",//
"[42,15, 16]",//
"[42,15// zzz\n//zzz\n//zzz\n,16]", "[42,15,16]",//
};
for (int i = 0; i < script.length; i += 2) {
String s = swapQuotes(script[i + 0]);
Object obj = json(s).next();
String s2 = swapQuotes(script[i + 1]);
Object obj2 = json(s2).next();
newEnc().encode(obj);
String enc1 = enc.toString();
newEnc().encode(obj2);
String enc2 = enc.toString();
assertStringsMatch(enc1, enc2);
}
}
public void testTrailingCommas() {
String script[] = {//
"{'hey':42,'you':'outthere',}",//
"{'hey':42,'you':'outthere'}",//
"[42,15,16,17,]",//
"[42,15,16,17]",//
"[42,15,16,17,null,]",//
"[42,15,16,17,null]",//
};
for (int i = 0; i < script.length; i += 2) {
String s = swapQuotes(script[i + 0]);
Object obj = json(s).next();
String s2 = swapQuotes(script[i + 1]);
Object obj2 = json(s2).next();
newEnc().encode(obj);
String enc1 = enc.toString();
newEnc().encode(obj2);
String enc2 = enc.toString();
assertStringsMatch(enc1, enc2);
}
}
private static class OurClass implements IJSONEncoder {
public static OurClass parse(JSONParser json) {
json.enterList();
String message = json.nextString();
int number = json.nextInt();
json.exit();
return new OurClass(message, number);
}
public OurClass(String message, int number) {
map.put("message", message);
map.put("number", number);
for (int i = 0; i < array.length; i++)
array[i] = (number + i + 1) * (number + i + 1);
}
private int[] array = new int[3];
private Map map = new HashMap();
@Override
public String toString() {
return map.get("message") + "/" + map.get("number") + "/"
+ Arrays.toString(array);
}
@Override
public void encode(JSONEncoder encoder) {
Object[] items = { map.get("message"), map.get("number") };
encoder.encode(items);
}
}
public void testInterface() {
OurClass c = new OurClass("hello", 42);
enc().encode(c);
String s = enc().toString();
OurClass c2 = OurClass.parse(new JSONParser(s));
assertStringsMatch(c, c2);
}
public void testNullAsString() {
json(swapQuotes("['hello',null,'there']"));
json.enterList();
assertStringsMatch("hello", json.nextString());
assertNull(json.nextString());
assertStringsMatch("there", json.nextString());
assertFalse(json.hasNext());
}
public void testMapParsing() {
Alpha a = Alpha.generateRandomObject(this.random());
String s = JSONEncoder.toJSON(a);
Alpha a2 = Alpha.parse(new JSONParser(s));
String s2 = JSONEncoder.toJSON(a2);
assertStringsMatch(s, s2);
}
public void testPeek() {
int[] a = { 5, 12, -1, 17, 3, -1, 42, -1 };
String s = "[5,12,null,17,3,null,42,null]";
JSONParser p = new JSONParser(s);
p.enterList();
for (int i = 0; i < a.length; i++) {
assertTrue(p.hasNext());
Object q = p.peekNext();
assertTrue((a[i] < 0) == (q == null));
if (q == null) {
assertTrue(p.nextIfNull());
} else {
assertFalse(p.nextIfNull());
assertEquals(a[i], p.nextInt());
}
}
assertFalse(p.hasNext());
p.exit();
}
public void testPeek2() {
String s = "{'a':5,'b':null,'c':17}";
s = JSONTools.swapQuotes(s);
JSONParser p = new JSONParser(s);
int sum = 0;
p.enterMap();
while (p.hasNext()) {
String key = p.nextKey();
if (!p.nextIfNull()) {
if (!key.equals("a")) {
assertEquals("c", key);
}
int val = p.nextInt();
sum += val;
}
}
p.exit();
assertEquals(5 + 17, sum);
}
// A class that represents an opaque data structure that supports JSON
private static class Alpha implements IJSONEncoder {
public static Alpha generateRandomObject(Random r) {
Alpha a = new Alpha();
for (int i = r.nextInt(6) + 2; i > 0; i--) {
String key = "" + r.nextInt(10000);
double value = r.nextDouble();
a.map.put(key, value);
}
return a;
}
@Override
public void encode(JSONEncoder encoder) {
// TODO Auto-generated method stub
encoder.enterMap();
for (String s : map.keySet()) {
encoder.encode(s);
encoder.encode((Double) map.get(s));
}
encoder.exit();
}
public static Alpha parse(JSONParser json) {
Alpha a = new Alpha();
json.enterMap();
while (json.hasNext()) {
String key = json.nextKey();
double d = json.nextDouble();
a.map.put(key, d);
}
return a;
}
private Map<String, Double> map = new HashMap();
}
}
| |
package com.example.android.capstoneproject1;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import com.example.lavanya.myapplication.backend.usersApi.model.Users;
import data.MenuTableContract;
/**
* Created by lavanya on 12/4/16.
*/
public class GetMenuData {
Context mcontext;
int imageno;
String titletext;
String pricetext;
int images;
public GetMenuData(Context context) {
mcontext = context;
}
public void getcursor(Cursor cursor) {
cursorAsyncTask cursorTask = new cursorAsyncTask();
cursorTask.execute(cursor);
}
public class cursorAsyncTask extends AsyncTask<Cursor, Void, Void> {
// Cursor cursor = mcontext.getContentResolver().query(MenuTableContract.MenuEntry.CONTENT_URI, null, null, null, null);
@Override
protected Void doInBackground(Cursor... cursors) {
Cursor cursor = cursors[0];
if (cursor != null && cursor.moveToFirst()) {
do {
imageno = cursor.getInt(cursor.getColumnIndexOrThrow(MenuTableContract.MenuEntry.COLUMN_FIRST_VAL));
titletext = cursor.getString(cursor.getColumnIndexOrThrow(MenuTableContract.MenuEntry.COLUMN_FOOD_TITLE));
pricetext = cursor.getString(cursor.getColumnIndexOrThrow(MenuTableContract.MenuEntry.COLUMN_FOOD_PRICE));
images = getimage(imageno);
Starterclass starterclass = new Starterclass(images, titletext, pricetext);
DatabaseList.fullmenulist.add(starterclass);
} while (cursor.moveToNext());
cursor.close();
}
return null;
}
}
private int getimage(int imageno) {
int images = 0;
switch (imageno) {
case 300:
images = R.drawable.vsoup;
break;
case 301:
images = R.drawable.corchicksoup;
break;
case 302:
images = R.drawable.greensald;
break;
case 200:
images = R.drawable.vcutlets;
break;
case 201:
images = R.drawable.mushroom;
break;
case 202:
images = R.drawable.gobis;
break;
case 203:
images = R.drawable.gobichill;
break;
case 204:
images = R.drawable.vegpakora;
break;
case 205:
images = R.drawable.corn;
break;
case 206:
images = R.drawable.chillp;
break;
case 207:
images = R.drawable.fcutlet;
break;
case 208:
images = R.drawable.natholi;
break;
case 209:
images = R.drawable.fpakora;
break;
case 210:
images = R.drawable.gshrimp;
break;
case 211:
images = R.drawable.chemeen;
break;
case 212:
images = R.drawable.travancore;
break;
case 213:
images = R.drawable.chillchick;
break;
case 214:
images = R.drawable.chick65;
break;
case 215:
images = R.drawable.chicktick;
break;
case 216:
images = R.drawable.beefcut;
break;
case 303:
images = R.drawable.greenpeass;
break;
case 304:
images = R.drawable.vegstews;
break;
case 305:
images = R.drawable.kadalas;
break;
case 306:
images = R.drawable.vegtheeyals;
break;
case 307:
images = R.drawable.avials;
break;
case 308:
images = R.drawable.vegmappass;
break;
case 309:
images = R.drawable.morcurries;
break;
case 400:
images = R.drawable.fmolees;
break;
case 401:
images = R.drawable.fishporicha;
break;
case 402:
images = R.drawable.grillfishfr;
break;
case 403:
images = R.drawable.fishporicha;
break;
case 404:
images = R.drawable.fishcurry;
break;
case 405:
images = R.drawable.chemmeenfry;
break;
case 406:
images = R.drawable.crabfry;
break;
case 500:
images = R.drawable.porichas;
break;
case 501:
images = R.drawable.chickmappas;
break;
case 502:
images = R.drawable.chickulli;
break;
case 503:
images = R.drawable.chickrost;
break;
case 504:
images = R.drawable.chickpepr;
break;
case 505:
images = R.drawable.chicktik;
break;
case 506:
images = R.drawable.eggmasal;
break;
case 507:
images = R.drawable.omlette;
break;
case 600:
images = R.drawable.goatcurr;
break;
case 601:
images = R.drawable.goatrogans;
break;
case 602:
images = R.drawable.goatpeprs;
break;
case 603:
images = R.drawable.beeffri;
break;
case 604:
images = R.drawable.beefullis;
break;
case 605:
images = R.drawable.beefcurs;
break;
case 606:
images = R.drawable.beefchil;
break;
case 700:
images = R.drawable.malbrchickbr;
break;
case 701:
images = R.drawable.chickdumsbir;
break;
case 702:
images = R.drawable.muttonbir;
break;
case 703:
images = R.drawable.eggbir;
break;
case 704:
images = R.drawable.vegbiry;
break;
case 705:
images = R.drawable.gheerce;
break;
case 706:
images = R.drawable.vegfryrice;
break;
case 707:
images = R.drawable.chickfryrce;
break;
case 708:
images = R.drawable.vegwrap;
break;
case 709:
images = R.drawable.gobiwraps;
break;
case 710:
images = R.drawable.chicktickwrap;
break;
case 711:
images = R.drawable.beefwraps;
break;
case 800:
images = R.drawable.rotis;
break;
case 801:
images = R.drawable.garlicsnaan;
break;
case 802:
images = R.drawable.chapatis;
break;
case 803:
images = R.drawable.eggchillparatha;
break;
case 804:
images = R.drawable.appams;
break;
case 805:
images = R.drawable.puttuus;
break;
case 806:
images = R.drawable.iddipaam;
break;
case 807:
images = R.drawable.kappaa;
break;
case 808:
images = R.drawable.fruitbowls;
break;
case 809:
images = R.drawable.icecreams;
break;
case 810:
images = R.drawable.faludas;
break;
case 811:
images = R.drawable.gulbjamun;
break;
case 812:
images = R.drawable.paysampradhan;
break;
case 900:
images = R.drawable.softdrinksres;
break;
case 901:
images = R.drawable.buttermlk;
break;
case 902:
images = R.drawable.plinlassi;
break;
case 903:
images = R.drawable.mangolassis;
break;
case 904:
images = R.drawable.limesoda;
break;
case 905:
images = R.drawable.orangejuce;
break;
case 906:
images = R.drawable.teas;
break;
case 907:
images = R.drawable.coffeess;
break;
}
return images;
}
}
| |
package org.metis;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.metis.pull.WdsResourceBean;
import org.metis.sql.SqlStmnt;
import org.metis.sql.SqlToken;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.*;
/**
* Runs a lot of tests against the creation and validation of the SQL
* statements.
*
*
* @author jfernandez
*
*/
// Test methods will be executed in ascending order by name
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SqlStmntTest {
// this will be the RDB that we test against.
private static WdsResourceBean rdb;
private static ArrayList<String> list = new ArrayList<String>();
@Test
public void TestA() {
List<SqlStmnt> sqlList = null;
// this sql should throw an exception because of the empty field
// definition
String sql = "select first, lastju jmih from users where first=``";
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid "
+ "sql statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException "
+ "for this invalid sql statement: " + sql);
}
}
// this sql should throw an exception because the field's
// definition is not fully defined
sql = "select first from users where first=`integer`";
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for "
+ "this invalid sql statement: " + sql);
}
}
// this sql should throw an exception because the field's
// definition is not fully defined
sql = "select first from users where first=`:id`";
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for "
+ "this invalid sql statement: " + sql);
}
}
// this sql should throw an exception because the field's
// definition is not fully defined
sql = "select first from users where first=`:`";
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid "
+ "sql statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for "
+ "this invalid sql statement: " + sql);
}
}
// this sql should throw an exception because the field's
// definition is not fully defined
sql = "select first from users where first=`::`";
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid "
+ "sql statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException "
+ "for this invalid sql statement: " + sql);
}
}
// this sql should throw an exception because 'caca' is not a valid type
sql = "select first from users where first=`caca:first`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for "
+ "this invalid sql statement: " + sql);
}
}
// this should result in an exception because there are two sql
// statements with the same 'signature' being assigned to the
// GET method
list.clear();
list.add("select first from users where first=`integer:first`");
list.add("select last from users where first=`integer:first`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for duplicate sql test");
} catch (Exception ignore) {
}
// this should result in an exception because there are two sql
// statements with the same 'signature' being assigned to the
// GET method
list.clear();
list.add("select first from users where first=`integer:first`");
list.add("select last from users where first=`integer:FIRSt`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for duplicate sql test");
} catch (Exception ignore) {
}
// ditto
list.clear();
list.add("select first from users where first=`integer:first`");
list.add("call foo(`integer:first:in`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for duplicate sql test");
} catch (Exception ignore) {
}
// ditto
list.clear();
list.add("select first from users where first=`integer:first`");
list.add("call foo(`integer:FiRst:in`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for duplicate sql test");
} catch (Exception ignore) {
}
// this should throw an exception because the two sql statements
// have the same signature. note that the field for the second
// statement defaults to an OUT, and not an IN, param; therefore it does
// not have any input params, just like the first one
list.clear();
list.add("select first from foo");
list.add("`nvarchar:name` = call foo()");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for duplicate sql test");
} catch (Exception ignore) {
}
// this should throw an exception because a select statement cannot have
// a param field with a mode
sql = "select first from users where first=`char:first:out`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// same as above, but for insert
sql = "insert into foo values(`char:first:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// same as above, but for delete
sql = "delete from foo where first like `char:first:out` || '%' ";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Delete(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// test that anything within single quotes is not touched
sql = "delete from foo where first like `integer:first` || '%' ";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Delete(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
fail("ERROR: got this exception on single quote test: " + e.getMessage());
}
sqlList = rdb.getSqlStmnts4Delete();
//System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("delete from foo where first like ? || '%'"));
// test that anything within single quotes is not touched
sql = "delete from foo where first like `integer:first` || '`integer:last`' ";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Delete(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
fail("ERROR: got this exception on single quote test: " + e.getMessage());
}
sqlList = rdb.getSqlStmnts4Delete();
//System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("delete from foo where first like ? || '`integer:last`'"));
// this should throw an exception because a call'able cannot have
// an IN param of type rset
list.clear();
list.add("call foo(`rset:FiRst:in`)");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should throw an exception because a call'able cannot have
// an IN param of type rset; note the use of a different mode than in
// the prior test
list.clear();
list.add("call foo(`rset:FiRst:inout`)");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should throw an exception because a call'able cannot have
// an IN param of type cursor
list.clear();
list.add("call foo(`cursor:FiRst:in`)");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should throw an exception because a non call'able cannot have
// an IN param of type cursor
list.clear();
list.add("select * from users where id = `cursor:FiRst`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should throw an exception because a non call'able cannot have
// an IN param of type rset
list.clear();
list.add("select * from users where id = `rset:FiRst`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// same as above but for insert
list.clear();
list.add("insert into foo values(`rset:first`)");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// same as above but for put
list.clear();
list.add("insert into foo values(`cursor:first`)");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should fail because 'function' params cannot have an OUT mode
sql = "`rset:second` = call foo(`cursor:FiRst:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// should not throw an exception because procedures allow OUT params
sql = "call foo(`cursor:FiRst:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// should not throw an exception, for the same reason as above
sql = "call foo(`cursor:FiRst`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the one param has defaulted to an OUT param
sqlList = rdb.getSqlStmnts4Get();
List<SqlToken> tokenList = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokenList.get(0).getMode() == SqlToken.Mode.OUT);
// same as above, but this time we're using a rset instead of a cursor
sql = "call foo(`rset:FiRst`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the one param has defaulted to an OUT param
sqlList = rdb.getSqlStmnts4Get();
tokenList = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokenList.get(0).getMode() == SqlToken.Mode.OUT);
// should not throw an exception; the rset params default to OUT mode,
// while the integer param defaults to IN mode
sql = "call foo(`rset:FiRst`,`integer:sec`,`rset:third`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the proper default values have been assigned
sqlList = rdb.getSqlStmnts4Get();
tokenList = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokenList.get(0).getMode() == SqlToken.Mode.OUT);
assertEquals(true, tokenList.get(1).getMode() == SqlToken.Mode.IN);
assertEquals(true, tokenList.get(2).getMode() == SqlToken.Mode.OUT);
// same as above except that we're using a cursor
sql = "call foo(`cursor:FiRst`,`integer:sec`,`rset:third`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the proper default values have been assigned
sqlList = rdb.getSqlStmnts4Get();
tokenList = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokenList.get(0).getMode() == SqlToken.Mode.OUT);
assertEquals(true, tokenList.get(1).getMode() == SqlToken.Mode.IN);
assertEquals(true, tokenList.get(2).getMode() == SqlToken.Mode.OUT);
// combination of defaults and non defaults
sql = "call foo(`rset:FiRst`,`integer:sec:inout`,`rset:third:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the proper default values have been assigned
sqlList = rdb.getSqlStmnts4Get();
tokenList = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokenList.get(0).getMode() == SqlToken.Mode.OUT);
assertEquals(true, tokenList.get(1).getMode() == SqlToken.Mode.INOUT);
assertEquals(true, tokenList.get(2).getMode() == SqlToken.Mode.OUT);
// should not throw an exception, rset types should default to OUT
sql = "call foo(`rset:FiRst`,`rset:second`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// should throw an exception; rset and cursor are not allowed as
// function params because they default to OUT mode which is not allowed
// for functions
sql = "`rset:second` = call foo(`rset:FiRst`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// should throw an exception; rset and cursor are not allowed as
// function params
sql = "`rset:second` = call foo(`cursor:FiRst`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// should not throw an exception; the statement is valid
sql = "select first, last from users where first = 'wile' and last = "
+ "'coyote'";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
// it is not a parameterized stmt
assertEquals(false, sqlList.get(0).isPrepared());
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 1);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("GET"));
// should not throw an exception
sql = "select first from users where first =`char:first`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
// it is a parameterized stmt
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true,
"select first from users where first = ?".equals(sqlList.get(0)
.getPrepared()));
// an exception should be thrown because 'caca' is not a valid mode
sql = "call foo(`char:last:caca`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql statement: "
+ sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// an exception should be thrown because 'caca' is not a valid mode
sql = "call foo(`char:last:in`,`char:first:caca`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql statement: "
+ sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// an exception should be thrown because there are duplicate keys with
// different modes
sql = "call foo(`char:last:in`,`char:last:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql statement: "
+ sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// an exception should be thrown because there are duplicate keys with
// different valid modes
sql = "call foo(`char:last:in`,`char:last:inout`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for "
+ "this invalid sql statement: " + sql);
}
}
// should not get an exception for this one
sql = "call foo(`char:last:in`,`char:first:out`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
// it is a parameterized stmt
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("foo"));
assertEquals(true,
"call foo( ? , ? )".equals(sqlList.get(0).getPrepared()));
assertEquals(true, sqlList.get(0).getInTokens().size() == 1);
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 1);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("PUT"));
// should not get an exception for this one
list.clear();
list.add("call Foo(`char:last:inout`)");
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
// it is a parameterized stmt
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("Foo"));
assertEquals(true, "call Foo( ? )".equals(sqlList.get(0).getPrepared()));
assertEquals(true, sqlList.get(0).getInTokens().size() == 1);
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 1);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("PUT"));
// leading and trailing escape characters are ok for call'ables.
// add a space between 'foo' and '('
sql = "{ call foo (`char:last:in`,`char:first:out`) } ";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("foo"));
assertEquals(true, sqlList.get(0).getInTokens().size() == 1);
assertEquals(true,
"call foo ( ? , ? )".equals(sqlList.get(0).getPrepared()));
// it doesn't make sense to have more than one IN param with the same
// name for a callable
sql = "call foo(`char:last:in`,`char:last:in`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql "
+ "statement: " + sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this is valid, same input param for a prepared statement is being
// used in multiple locations
sql = "select * from users where foo =`char:first` or bar =`char:first`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).getKeyTokens().size() == 1);
assertEquals(false, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true,
"select * from users where foo = ? or bar = ?".equals(sqlList
.get(0).getPrepared()));
assertEquals(true, sqlList.get(0).getNumKeyTokens() == 1);
// exception should not be thrown; this is valid
list.add("select * from users where foo =`char:first`");
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
list.clear();
list.add("update foo set attr1='bar'");
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
sqlList = rdb.getSqlStmnts4Post();
assertEquals(true, sqlList == null);
sqlList = rdb.getSqlStmnts4Delete();
assertEquals(true, sqlList == null);
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 2);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("GET"));
assertEquals(true, rdb.getSupportedMethods()[1].equalsIgnoreCase("PUT"));
// no exception should be thrown
list.clear();
list.add("select * from users where foo =`char:first` or bar =`char:first`");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
list.clear();
list.add("update foo set attr1='bar'");
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
sqlList = rdb.getSqlStmnts4Post();
assertEquals(true, sqlList == null);
sqlList = rdb.getSqlStmnts4Delete();
assertEquals(true, sqlList == null);
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 2);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("GET"));
assertEquals(true, rdb.getSupportedMethods()[1].equalsIgnoreCase("PUT"));
// an exception will be thrown because the function statement
// will never be used. So there's no point putting it on
// the list.
list.clear();
list.add("`integer:id` = call foo()");
list.add("select * from foo");
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for redundant function "
+ "test");
} catch (Exception e) {
}
// this test should throw an exception because you have two non-prepared
// statements with neither of them having any input params
list.clear();
list.add("select first from foo where first like '%smith' ");
list.add("select * from foo");
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for two non-prepared "
+ "statements test");
} catch (Exception e) {
}
// test the use of the 'pkey' field
sql = "insert into car (id, mpg) values (`pkey:id`,s_car.nextval,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the pkey calue is "id"
sqlList = rdb.getSqlStmnts4Post();
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values ( s_car.nextval , ? )"));
// test the use of the 'pkey' field
sql = "insert into car ( id , mpg ) values (`pkey:id` ,s_car.nextval,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
// confirm that the pkey calue is "id"
sqlList = rdb.getSqlStmnts4Post();
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car ( id , mpg ) values ( s_car.nextval , ? )"));
// test the use of the 'pkey' field in other parts of the statement
sql = "insert into car (id, mpg) values `pkey:id` (s_car.nextval,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Post();
// System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values (s_car.nextval , ? )"));
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// test the use of the 'pkey' field in other parts of the statement
sql = "insert into car (id, mpg) values (`pkey:id`,s_car.nextval,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Post();
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values ( s_car.nextval , ? )"));
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// test the use of the 'pkey' field in other parts of the statement
sql = "insert into car (id, mpg) values (s_car.nextval,`pkey:id`,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Post();
// System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values (s_car.nextval , ? )"));
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// test the use of the 'pkey' field in other parts of the statement
sql = "insert into car (id,mpg) values (s_car.nextval,`integer:mpg`,`pkey:id`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Post();
//System.out.println(sqlList.get(0).getPrepared());
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values (s_car.nextval , ? )"));
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// test the use of the 'pkey' field in other parts of the statement
sql = "insert into car (id, mpg) values (s_car.nextval,`integer:mpg`) `pkey:id`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Post();
assertEquals(
true,
sqlList.get(0)
.getPrepared()
.equals("insert into car (id , mpg) values (s_car.nextval , ? )"));
assertEquals(true, sqlList.get(0).getPrimaryKey() != null);
assertEquals(true, sqlList.get(0).getPrimaryKey().equals("id"));
// we should get an exception because a statement cannot start with pkey
sql = "`pkey:id` insert into car (id, mpg) values (s_car.nextval,`integer:mpg`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
// we should get an exception because two pkeys are not allowed
sql = "insert into car (id, mpg) values (`pkey:id`, s_car.nextval,`integer:mpg`) `pkey:id`";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
// we should get an exception because pkey cannot be used as out param
// for a function
sql = "`pkey:id` = call foo(`char:last:in`,`char:first:in`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
// we should get an exception because pkey can only be used in insert
// statements
sql = "`integer:id` = call foo(`pkey:id`,`char:last:in`,`char:first:in`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Post(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
// same as above, but with a select
list.add("select first from foo where `pkey:id` first like '%smith' ");
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
// same as above, but with a update
list.add("update car set mpg=28 where id=123 `pkey:id`");
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception for pkey function test");
} catch (Exception e) {
}
}
// test stored functions
@Test
public void TestB() {
// make sure we have a rdb
assertEquals(true, (rdb != null));
List<SqlStmnt> sqlList = null;
String sql = "`integer:id` = call foo(`char:last:in`,`char:first:in`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Put(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Put();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).isFunction());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("foo"));
assertEquals(true,
"? = call foo( ? , ? )".equals(sqlList.get(0).getPrepared()));
// ensure proper method(s) are supported
assertEquals(true, rdb.getSupportedMethods().length == 1);
assertEquals(true, rdb.getSupportedMethods()[0].equalsIgnoreCase("PUT"));
// test '=call' being one string
sql = "`integer:id` =call foo(`char:last:in`,`char:first`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).isFunction());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("foo"));
assertEquals(true,
"? =call foo( ? , ? )".equals(sqlList.get(0).getPrepared()));
// test '=call' and first in field being one string
sql = "`integer:id`=call foo(`char:last`,`char:first`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).isFunction());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("foo"));
assertEquals(true,
"? =call foo( ? , ? )".equals(sqlList.get(0).getPrepared()));
sql = "{`integer:id` =call FOO(`char:last:in`,`char:first:in`)}";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
fail("ERROR: got this Exception for this valid sql statement: "
+ sql);
}
sqlList = rdb.getSqlStmnts4Get();
assertEquals(true, sqlList != null);
assertEquals(true, sqlList.get(0).isPrepared());
assertEquals(true, sqlList.get(0).isCallable());
assertEquals(true, sqlList.get(0).isFunction());
assertEquals(true, sqlList.get(0).getStoredProcName().equals("FOO"));
assertEquals(true,
"? =call FOO( ? , ? )".equals(sqlList.get(0).getPrepared()));
List<SqlToken> tokens = sqlList.get(0).getSortedKeyTokens();
assertEquals(true, tokens.get(0).getKey().equals("id"));
assertEquals(true, tokens.get(1).getKey().equals("last"));
assertEquals(true, tokens.get(2).getKey().equals("first"));
// exception should be thrown because of in-balanced braces
sql = "{`integer:id` =call FOO(`char:last`,`char:first`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean();
rdb.setDataSource(new DummyDataSource());
try {
rdb.setSqls4Get(list);
fail("ERROR: did not get Exception for this invalid sql statement: "
+ sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
sql = "`integer:id` = call foo(`char:name:in`,`integer:id`)";
list.clear();
list.add(sql);
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get Exception for this invalid sql statement: "
+ sql);
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
fail("ERROR: did not get IllegalArgumentException for this "
+ "invalid sql statement: " + sql);
}
}
// this should throw an exception because there are two params with
// the same name
list.clear();
sql = "`integer:id` = call foo(`char:name`,`integer:id`)";
list.add(sql);
sql = "select * from foo";
list.add(sql);
rdb = new WdsResourceBean(); // create a new RDB for this test case
rdb.setDataSource(new DummyDataSource());
rdb.setSqls4Get(list);
try {
rdb.afterPropertiesSet();
fail("ERROR: did not get exception when one was expected");
} catch (Exception e) {
}
}
}
| |
package creation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputAdapter;
import util.GOLErrorHandler;
import util.GOLFileHandler;
/**
* Represents the controller of the implementation. It communicates state
* changes between the model and view. The controller also controls the
* simulation loop, processing changes and input as they come along.
*
* @author Cameron Rader (github: Mr-Sniffles)
*
*/
public class GOLController {
// #########################################################################
// Global Variables/Constants
// #########################################################################
/**
* Displays information from the model to the user.
*/
private GOLView view;
/**
* Holds the logic and data of the simulation and performs simulation
* calculations.
*/
private CellWorld model;
/**
* Delay(in milliseconds) between each tick of the simulation.
*/
private int simulationDelay;
/**
* True if the simulation is running, false otherwise.
*/
private boolean isRunning;
/**
* True if the left mouse button is being held down, false if it is not.
*/
private boolean mouseButtonDown;
// #########################################################################
// Constructors
// #########################################################################
/**
* Initializes a default, null MVC structure. View and model must be set
* before simulation can be used.
*/
public GOLController() {
this.view = null;
this.model = null;
}
/**
* Initializes a MVC structure given a view and a model.
*
* @precondition view and model are initialized
*
* @param view
* View to display
* @param model
* Model to act on
*/
public GOLController(GOLView view, CellWorld model) {
this.view = view;
this.model = model;
this.init();
}
// #########################################################################
// Helper Methods
// #########################################################################
/**
* Initialize the controller by connecting listeners to the view and
* initializing local controller variables. Also syncs the view with the
* model.
*/
private void init() {
simulationDelay = 100;
isRunning = false;
mouseButtonDown = false;
// sync the view with model data
view.resizeGrid(model.getWorldSize());
this.updateViewGrid();
view.setPopulationLabelValue(model.getPopulationCount());
view.setGenerationLabelValue(model.getTickCount());
// add menu listeners
view.addSaveItemListener(new SaveItemListener());
view.addLoadItemListener(new LoadItemListener());
view.addResizeItemListener(new ResizeItemListener());
// add cell panel listeners
this.addViewGridListeners();
// add speed listeners
view.addSpeedAdjustListener(new SpeedAdjustListener());
view.addSpeedDisplayListener(new SpeedDisplayListener());
// add button control listeners
view.addStartStopToggleListener(new StartStopToggleListener());
view.addResetButtonListener(new ResetButtonListener());
view.addClearButtonListener(new ClearButtonListener());
}
// #########################################################################
// Controller Methods
// #########################################################################
/**
* Set the controller's underlying model.
*
* @param model
* Model to set
*/
public void setModel(CellWorld model) {
this.model = model;
}
/**
* Set the controller's view that will be used to display data from the
* model.
*
* @param view
* View to set
*/
public void setView(GOLView view) {
this.view = view;
}
/**
* Add listeners to every cell panel in the view grid display
*
* @postcondition Each cell panel belonging to the view has a listener
* attached to it.
*/
private void addViewGridListeners() {
for (int x = 0; x < model.getWorldSize(); x++) {
for (int y = 0; y < model.getWorldSize(); y++) {
view.addCellPanelListener(x, y, new GridCellListener());
}
}
}
/**
* Start the simulation loop in a new thread.
*
* @precondition All required data is initialized and the simulation is
* ready to begin.
*
* @postcondition The simulation loop is running.
*/
public void beginSimulation() {
new Thread(new SimulationLoop()).start();
}
/**
* Reset the simulation to its initial state.
*
* @precondition All required data is initialized.
*
* @postcondition The simulation is stopped, the model is reset, and the
* view displays the data from the new reset model.
*/
private void resetSimulation() {
isRunning = false;
model.reset();
view.setPopulationLabelValue(model.getPopulationCount());
view.setGenerationLabelValue(model.getTickCount());
view.setStartStopToggleText("Start");
this.updateViewGrid();
}
/**
* Clear the simulation completely.
*
* @precondition All required data is initialized.
*
* @postcondition The simulation is stopped, the model is cleared, and the
* view displays the data from the new reset model.
*/
private void clearSimulation() {
isRunning = false;
view.clear();
model.clear();
this.updateViewGrid();
}
/**
* Update all cell panels of the view with the corresponding data from the
* model's world.
*
* @precondition All required data is initialized.
*
* @postcondition The view's panel grid is updated to match model's world.
*/
private void updateViewGrid() {
for (int x = 0; x < model.getWorldSize(); x++) {
for (int y = 0; y < model.getWorldSize(); y++) {
view.updateGridCell(x, y, model.getCellState(x, y));
}
}
}
/**
* Load a new cell panel grid in the view that matches the model's world.
* Should only be called if the new grid is a different size than the
* current one.
*
* @postcondition View's panel grid is updated to match model's world,
* including size.
*/
private void loadNewViewGrid() {
view.resizeGrid(model.getWorldSize());
this.addViewGridListeners();
this.updateViewGrid();
}
/**
* Resize both the model and the view grids to a size of resizeValue
*
* @param resizeValue
* New size of the model/view grids
*
* @postcondition Grid of model/view are resized to a size of resizeValue
*/
private void resizeAll(int resizeValue) {
model.resize(resizeValue);
this.loadNewViewGrid();
}
// #########################################################################
// Internal Classes
// #########################################################################
/**
* Listener for view's save menu item.
*/
class SaveItemListener implements ActionListener {
/**
* Flag the simulation as not running, adjust appropriate view
* components, and open a save dialog.
*/
@Override
public void actionPerformed(ActionEvent e) {
isRunning = false;
view.setStartStopToggleText("Start");
int action = view.showSaveFileChooser();
File selection = view.getFileChooserSelection();
if ( selection != null && action == JFileChooser.APPROVE_OPTION ) {
try {
GOLFileHandler.saveWorldFile(selection, model);
} catch (IOException exc) {
exc.printStackTrace();
System.err.println("\nError: Unable to save world.");
}
}
}
}
/**
* Listener for view's load menu item.
*/
class LoadItemListener implements ActionListener {
/**
* Flag the simulation as not running, adjust appropriate view
* components, and open a load dialog. Will also update view upon
* loading a world configuration.
*/
@Override
public void actionPerformed(ActionEvent e) {
isRunning = false;
view.setStartStopToggleText("Start");
int action = view.showLoadFileChooser();
File selection = view.getFileChooserSelection();
if ( selection != null && action == JFileChooser.APPROVE_OPTION ) {
try {
int[][] world = GOLFileHandler.parseWorldFile(selection);
model.loadWorld(world);
loadNewViewGrid();
view.setPopulationLabelValue(model.getPopulationCount());
view.setGenerationLabelValue(model.getTickCount());
} catch (IOException exc) {
exc.printStackTrace();
System.err.println("\nError: Cannot read file. "
+ "Make sure formatting is correct.");
}
}
}
}
/**
* Listener for view's resize menu item.
*/
class ResizeItemListener implements ActionListener {
/**
* Flag the simulation as not running, adjust appropriate view
* components, and open a resize dialog. Will also check for appropriate
* input. If input is valid, then resize view and model cell grids.
*/
@Override
public void actionPerformed(ActionEvent e) {
isRunning = false;
view.setStartStopToggleText("Start");
view.showResizeDialog();
String valueString = view.getResizeDialogValue();
if ( valueString != null ) {
try {
int resizeValue = Integer.parseInt(valueString);
if ( resizeValue > 0 ) {
resizeAll(resizeValue);
} else {
JOptionPane.showMessageDialog(view,
"Size must be a positive integer.");
}
} catch (NumberFormatException exc) {
exc.printStackTrace();
System.err.println("\nError: Input was not a number");
}
}
}
}
/**
* Listener for view's speed adjust slider.
*/
class SpeedAdjustListener implements ChangeListener {
/**
* Gets new value from speed adjust slider and updates model and view
* components.
*/
@Override
public void stateChanged(ChangeEvent e) {
int newSpeed = view.getSpeedAdjustValue();
view.setSpeedDisplayText(newSpeed + "");
simulationDelay = newSpeed;
}
}
/**
* Listener for view's speed display.
*/
class SpeedDisplayListener implements ActionListener {
/**
* Gets new value from the speed display field and updates model and
* view components. Also sanitizes input that is outside the speed
* adjust slider's range.
*/
@Override
public void actionPerformed(ActionEvent e) {
int newSpeed = view.getSpeedDisplayValue();
if ( newSpeed > 1000 ) {
newSpeed = 1000;
} else if ( newSpeed < 0 ) {
newSpeed = 0;
}
view.setSpeedAdjustValue(newSpeed);
simulationDelay = newSpeed;
}
}
/**
* Listener for view's start/stop toggle button.
*/
class StartStopToggleListener implements ActionListener {
/**
* Inverts the running flag. If the simulation is being flagged to run
* for the first time(tickCount = 0), then also sets the initial state
* of the model.
*/
@Override
public void actionPerformed(ActionEvent e) {
if ( model.getTickCount() == 0 ) {
model.syncInitialState();
}
isRunning = !isRunning;
if ( isRunning ) {
view.setStartStopToggleText("Stop");
} else {
view.setStartStopToggleText("Start");
}
}
}
/**
* Listener for view's reset button.
*/
class ResetButtonListener implements ActionListener {
/**
* Resets the entire simulation to its initial state.
*/
@Override
public void actionPerformed(ActionEvent e) {
resetSimulation();
}
}
/**
* Listener for view's clear button.
*/
class ClearButtonListener implements ActionListener {
/**
* Clears the entire simulation to a blank state.
*/
@Override
public void actionPerformed(ActionEvent e) {
clearSimulation();
}
}
/**
* Listener for view's cell panel.
*/
class GridCellListener extends MouseInputAdapter {
/**
* Helper method that inverts the cell clicked in the model and view,
* and update population count accordingly.
*
* @param e
* Event passed by mouse listener
*/
private void invertCell(MouseEvent e) {
CellPanel src = (CellPanel) e.getSource();
int x = src.getxPos();
int y = src.getyPos();
view.invertGridCell(x, y);
model.invertCellState(x, y);
view.setPopulationLabelValue(model.getPopulationCount());
}
/**
* Flag the left mouse button as pressed down and invert the cell
* clicked.
*/
@Override
public void mousePressed(MouseEvent e) {
mouseButtonDown = true;
this.invertCell(e);
}
/**
* Flag the left mouse button as released.
*/
@Override
public void mouseReleased(MouseEvent e) {
mouseButtonDown = false;
}
/**
* Invert the cell that the cursor is over if the left mouse button is
* flagged as pressed down.
*/
@Override
public void mouseEntered(MouseEvent e) {
if ( mouseButtonDown ) {
this.invertCell(e);
}
}
}
/**
* Simulation control loop. Runs indefinitely once the simulation has been
* initialized and started.
*/
class SimulationLoop implements Runnable {
/**
* Perform a model tick and update view with new model data.
*/
private void update() {
model.tick();
updateViewGrid();
view.setPopulationLabelValue(model.getPopulationCount());
view.setGenerationLabelValue(model.getTickCount());
}
/**
* If the simulation is flagged as running then process model ticks;
* otherwise, simply fire a keep-alive signal.
*/
@Override
public void run() {
while (true) {
if ( isRunning ) {
this.update();
try {
Thread.sleep(simulationDelay);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(GOLErrorHandler.THREAD_INTERRUPT_ERROR);
}
}
System.out.print(""); // keep-alive
}
}
}
}
| |
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2011, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/test/jdbc2/TimestampTest.java,v 1.23 2008/10/19 19:52:33 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.test.jdbc2;
import org.postgresql.test.TestUtil;
import junit.framework.TestCase;
import java.sql.*;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.postgresql.PGStatement;
import org.postgresql.jdbc2.TimestampUtils;
import org.postgresql.core.BaseConnection;
/*
* Test get/setTimestamp for both timestamp with time zone and
* timestamp without time zone datatypes
*
*/
public class TimestampTest extends TestCase
{
private Connection con;
public TimestampTest(String name)
{
super(name);
}
protected void setUp() throws Exception
{
con = TestUtil.openDB();
TestUtil.createTable(con, TSWTZ_TABLE, "ts timestamp with time zone");
TestUtil.createTable(con, TSWOTZ_TABLE, "ts timestamp without time zone");
TestUtil.createTable(con, DATE_TABLE, "ts date");
}
protected void tearDown() throws Exception
{
TestUtil.dropTable(con, TSWTZ_TABLE);
TestUtil.dropTable(con, TSWOTZ_TABLE);
TestUtil.dropTable(con, DATE_TABLE);
TestUtil.closeDB(con);
}
/**
* Ensure the driver doesn't modify a Calendar that is passed in.
*/
public void testCalendarModification() throws SQLException
{
Calendar cal = Calendar.getInstance();
Calendar origCal = (Calendar)cal.clone();
PreparedStatement ps = con.prepareStatement("INSERT INTO " + TSWOTZ_TABLE + " VALUES (?)");
ps.setDate(1, new Date(0), cal);
ps.executeUpdate();
assertEquals(origCal, cal);
ps.setTimestamp(1, new Timestamp(0), cal);
ps.executeUpdate();
assertEquals(origCal, cal);
ps.setTime(1, new Time(0), cal);
// Can't actually execute this one because of type mismatch,
// but all we're really concerned about is the set call.
// ps.executeUpdate();
assertEquals(origCal, cal);
ps.close();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ts FROM " + TSWOTZ_TABLE);
assertTrue(rs.next());
rs.getDate(1, cal);
assertEquals(origCal, cal);
rs.getTimestamp(1, cal);
assertEquals(origCal, cal);
rs.getTime(1, cal);
assertEquals(origCal, cal);
rs.close();
stmt.close();
}
public void testInfinity() throws SQLException
{
runInfinityTests(TSWTZ_TABLE, PGStatement.DATE_POSITIVE_INFINITY);
runInfinityTests(TSWTZ_TABLE, PGStatement.DATE_NEGATIVE_INFINITY);
runInfinityTests(TSWOTZ_TABLE, PGStatement.DATE_POSITIVE_INFINITY);
runInfinityTests(TSWOTZ_TABLE, PGStatement.DATE_NEGATIVE_INFINITY);
if (TestUtil.haveMinimumServerVersion(con, "8.4"))
{
runInfinityTests(DATE_TABLE, PGStatement.DATE_POSITIVE_INFINITY);
runInfinityTests(DATE_TABLE, PGStatement.DATE_NEGATIVE_INFINITY);
}
}
private void runInfinityTests(String table, long value) throws SQLException
{
GregorianCalendar cal = new GregorianCalendar();
// Pick some random timezone that is hopefully different than ours
// and exists in this JVM.
cal.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
String strValue;
if (value == PGStatement.DATE_POSITIVE_INFINITY) {
strValue = "infinity";
} else {
strValue = "-infinity";
}
Statement stmt = con.createStatement();
stmt.executeUpdate(TestUtil.insertSQL(table, "'" + strValue + "'"));
stmt.close();
PreparedStatement ps = con.prepareStatement(TestUtil.insertSQL(table, "?"));
ps.setTimestamp(1, new Timestamp(value));
ps.executeUpdate();
ps.setTimestamp(1, new Timestamp(value), cal);
ps.executeUpdate();
ps.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select ts from " + table);
while (rs.next()) {
assertEquals(strValue, rs.getString(1));
Timestamp ts = rs.getTimestamp(1);
assertEquals(value, ts.getTime());
Date d = rs.getDate(1);
assertEquals(value, d.getTime());
Timestamp tscal = rs.getTimestamp(1, cal);
assertEquals(value, tscal.getTime());
}
rs.close();
assertEquals(3, stmt.executeUpdate("DELETE FROM " + table));
stmt.close();
}
/*
* Tests the timestamp methods in ResultSet on timestamp with time zone
* we insert a known string value (don't use setTimestamp) then see that
* we get back the same value from getTimestamp
*/
public void testGetTimestampWTZ() throws SQLException
{
Statement stmt = con.createStatement();
TimestampUtils tsu = ((BaseConnection)con).getTimestampUtils();
//Insert the three timestamp values in raw pg format
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS1WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS2WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS3WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + TS4WTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate1.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate2.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate3.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate4.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime1.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime2.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime3.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime4.getTime())) + "'")));
// Fall through helper
timestampTestWTZ();
assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWTZ_TABLE));
stmt.close();
}
/*
* Tests the timestamp methods in PreparedStatement on timestamp with time zone
* we insert a value using setTimestamp then see that
* we get back the same value from getTimestamp (which we know works as it was tested
* independently of setTimestamp
*/
public void testSetTimestampWTZ() throws SQLException
{
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWTZ_TABLE, "?"));
pstmt.setTimestamp(1, TS1WTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS2WTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS3WTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS4WTZ);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Timestamp
pstmt.setObject(1, TS1WTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS2WTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS3WTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS4WTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With Strings
pstmt.setObject(1, TS1WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS2WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS3WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS4WTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Date
pstmt.setObject(1, tmpDate1, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate2, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate3, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate4, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Time
pstmt.setObject(1, tmpTime1, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime2, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime3, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime4, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// Fall through helper
timestampTestWTZ();
assertEquals(20, stmt.executeUpdate("DELETE FROM " + TSWTZ_TABLE));
pstmt.close();
stmt.close();
}
/*
* Tests the timestamp methods in ResultSet on timestamp without time zone
* we insert a known string value (don't use setTimestamp) then see that
* we get back the same value from getTimestamp
*/
public void testGetTimestampWOTZ() throws SQLException
{
Statement stmt = con.createStatement();
TimestampUtils tsu = ((BaseConnection)con).getTimestampUtils();
//Insert the three timestamp values in raw pg format
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS5WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS6WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS5WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS6WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS1WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS2WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS3WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS4WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS5WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + TS6WOTZ_PGFORMAT + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate1WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate2WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate3WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate4WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate5WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpDate6WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime1WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime2WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime3WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime4WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime5WOTZ.getTime())) + "'")));
assertEquals(1, stmt.executeUpdate(TestUtil.insertSQL(TSWOTZ_TABLE, "'" + tsu.toString(null, new java.sql.Timestamp(tmpTime6WOTZ.getTime())) + "'")));
// Fall through helper
timestampTestWOTZ();
assertEquals(30, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
stmt.close();
}
/*
* Tests the timestamp methods in PreparedStatement on timestamp without time zone
* we insert a value using setTimestamp then see that
* we get back the same value from getTimestamp (which we know works as it was tested
* independently of setTimestamp
*/
public void testSetTimestampWOTZ() throws SQLException
{
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(TestUtil.insertSQL(TSWOTZ_TABLE, "?"));
pstmt.setTimestamp(1, TS1WOTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS2WOTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS3WOTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS4WOTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS5WOTZ);
assertEquals(1, pstmt.executeUpdate());
pstmt.setTimestamp(1, TS6WOTZ);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Timestamp
pstmt.setObject(1, TS1WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS2WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS3WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS4WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS5WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS6WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With Strings
pstmt.setObject(1, TS1WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS2WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS3WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS4WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS5WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, TS6WOTZ_PGFORMAT, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Date
pstmt.setObject(1, tmpDate1WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate2WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate3WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate4WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate5WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpDate6WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// With java.sql.Time
pstmt.setObject(1, tmpTime1WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime2WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime3WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime4WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime5WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.setObject(1, tmpTime6WOTZ, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
// Fall through helper
timestampTestWOTZ();
assertEquals(30, stmt.executeUpdate("DELETE FROM " + TSWOTZ_TABLE));
pstmt.close();
stmt.close();
}
/*
* Helper for the TimestampTests. It tests what should be in the db
*/
private void timestampTestWTZ() throws SQLException
{
Statement stmt = con.createStatement();
ResultSet rs;
java.sql.Timestamp t;
rs = stmt.executeQuery("select ts from " + TSWTZ_TABLE); //removed the order by ts
assertNotNull(rs);
for (int i = 0; i < 3; i++)
{
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(TS1WTZ, t);
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(TS2WTZ, t);
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(TS3WTZ, t);
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(TS4WTZ, t);
}
// Testing for Date
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate1.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate2.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate3.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate4.getTime(), t.getTime());
// Testing for Time
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime1.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime2.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime3.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime4.getTime(), t.getTime());
assertTrue(! rs.next()); // end of table. Fail if more entries exist.
rs.close();
stmt.close();
}
/*
* Helper for the TimestampTests. It tests what should be in the db
*/
private void timestampTestWOTZ() throws SQLException
{
Statement stmt = con.createStatement();
ResultSet rs;
java.sql.Timestamp t;
rs = stmt.executeQuery("select ts from " + TSWOTZ_TABLE); //removed the order by ts
assertNotNull(rs);
for (int i = 0; i < 3; i++)
{
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS1WOTZ));
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS2WOTZ));
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS3WOTZ));
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS4WOTZ));
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS5WOTZ));
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertTrue(t.equals(TS6WOTZ));
}
// Testing for Date
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate1WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate2WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate3WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate4WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate5WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpDate6WOTZ.getTime(), t.getTime());
// Testing for Time
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime1WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime2WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime3WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime4WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime5WOTZ.getTime(), t.getTime());
assertTrue(rs.next());
t = rs.getTimestamp(1);
assertNotNull(t);
assertEquals(tmpTime6WOTZ.getTime(), t.getTime());
assertTrue(! rs.next()); // end of table. Fail if more entries exist.
rs.close();
stmt.close();
}
private static java.sql.Timestamp getTimestamp(int y, int m, int d, int h, int mn, int se, int f, String tz)
{
java.sql.Timestamp l_return = null;
java.text.DateFormat l_df;
try
{
String l_ts;
l_ts = TestUtil.fix(y, 4) + "-" +
TestUtil.fix(m, 2) + "-" +
TestUtil.fix(d, 2) + " " +
TestUtil.fix(h, 2) + ":" +
TestUtil.fix(mn, 2) + ":" +
TestUtil.fix(se, 2) + " ";
if (tz == null)
{
l_df = new java.text.SimpleDateFormat("y-M-d H:m:s");
}
else
{
l_ts = l_ts + tz;
l_df = new java.text.SimpleDateFormat("y-M-d H:m:s z");
}
java.util.Date l_date = l_df.parse(l_ts);
l_return = new java.sql.Timestamp(l_date.getTime());
l_return.setNanos(f);
}
catch (Exception ex)
{
fail(ex.getMessage());
}
return l_return;
}
private static final java.sql.Timestamp TS1WTZ = getTimestamp(1950, 2, 7, 15, 0, 0, 100000000, "PST");
private static final String TS1WTZ_PGFORMAT = "1950-02-07 15:00:00.1-08";
private static final java.sql.Timestamp TS2WTZ = getTimestamp(2000, 2, 7, 15, 0, 0, 120000000, "GMT");
private static final String TS2WTZ_PGFORMAT = "2000-02-07 15:00:00.12+00";
private static final java.sql.Timestamp TS3WTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123000000, "GMT");
private static final String TS3WTZ_PGFORMAT = "2000-07-07 15:00:00.123+00";
private static final java.sql.Timestamp TS4WTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123456000, "GMT");
private static final String TS4WTZ_PGFORMAT = "2000-07-07 15:00:00.123456+00";
private static final java.sql.Timestamp TS1WOTZ = getTimestamp(1950, 2, 7, 15, 0, 0, 100000000, null);
private static final String TS1WOTZ_PGFORMAT = "1950-02-07 15:00:00.1";
private static final java.sql.Timestamp TS2WOTZ = getTimestamp(2000, 2, 7, 15, 0, 0, 120000000, null);
private static final String TS2WOTZ_PGFORMAT = "2000-02-07 15:00:00.12";
private static final java.sql.Timestamp TS3WOTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123000000, null);
private static final String TS3WOTZ_PGFORMAT = "2000-07-07 15:00:00.123";
private static final java.sql.Timestamp TS4WOTZ = getTimestamp(2000, 7, 7, 15, 0, 0, 123456000, null);
private static final String TS4WOTZ_PGFORMAT = "2000-07-07 15:00:00.123456";
private static final java.sql.Timestamp TS5WOTZ = new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY);
private static final String TS5WOTZ_PGFORMAT = "-infinity";
private static final java.sql.Timestamp TS6WOTZ = new Timestamp(PGStatement.DATE_POSITIVE_INFINITY);
private static final String TS6WOTZ_PGFORMAT = "infinity";
private static final String TSWTZ_TABLE = "testtimestampwtz";
private static final String TSWOTZ_TABLE = "testtimestampwotz";
private static final String DATE_TABLE = "testtimestampdate";
private static final java.sql.Date tmpDate1 = new java.sql.Date(TS1WTZ.getTime());
private static final java.sql.Time tmpTime1 = new java.sql.Time(TS1WTZ.getTime());
private static final java.sql.Date tmpDate2 = new java.sql.Date(TS2WTZ.getTime());
private static final java.sql.Time tmpTime2 = new java.sql.Time(TS2WTZ.getTime());
private static final java.sql.Date tmpDate3 = new java.sql.Date(TS3WTZ.getTime());
private static final java.sql.Time tmpTime3 = new java.sql.Time(TS3WTZ.getTime());
private static final java.sql.Date tmpDate4 = new java.sql.Date(TS4WTZ.getTime());
private static final java.sql.Time tmpTime4 = new java.sql.Time(TS4WTZ.getTime());
private static final java.sql.Date tmpDate1WOTZ = new java.sql.Date(TS1WOTZ.getTime());
private static final java.sql.Time tmpTime1WOTZ = new java.sql.Time(TS1WOTZ.getTime());
private static final java.sql.Date tmpDate2WOTZ = new java.sql.Date(TS2WOTZ.getTime());
private static final java.sql.Time tmpTime2WOTZ = new java.sql.Time(TS2WOTZ.getTime());
private static final java.sql.Date tmpDate3WOTZ = new java.sql.Date(TS3WOTZ.getTime());
private static final java.sql.Time tmpTime3WOTZ = new java.sql.Time(TS3WOTZ.getTime());
private static final java.sql.Date tmpDate4WOTZ = new java.sql.Date(TS4WOTZ.getTime());
private static final java.sql.Time tmpTime4WOTZ = new java.sql.Time(TS4WOTZ.getTime());
private static final java.sql.Date tmpDate5WOTZ = new java.sql.Date(TS5WOTZ.getTime());
private static final java.sql.Date tmpTime5WOTZ = new java.sql.Date(TS5WOTZ.getTime());
private static final java.sql.Date tmpDate6WOTZ = new java.sql.Date(TS6WOTZ.getTime());
private static final java.sql.Date tmpTime6WOTZ = new java.sql.Date(TS6WOTZ.getTime());
}
| |
/**
* (c) Copyright 2014 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kiji.schema.util;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.ApiStability;
/**
* A keyed cache which keeps track of how many outstanding users of the cached value exist.
* When the reference count falls to 0, the cached value (which must implement
* {@link java.io.Closeable}), is removed from the cache and closed.
*
* Clients of {@code ReferenceCountedCache} *must* have a corresponding {@link #release(K)} call
* for every {@link #get(K)} after the cached object will no longer be used. After the
* {@link #release(K)} call, the cached object must no longer be used.
*
* The {@code ReferenceCountedCache} may optionally be closed, which will preemptively close all
* cached entries regardless of reference count. See the javadoc of {@link #close()} for caveats.
*
* @param <K> key type of cache.
* @param <V> value type (must implement {@link java.io.Closeable}) of cache.
*/
@ApiAudience.Framework
@ApiStability.Experimental
public final class ReferenceCountedCache<K, V extends Closeable> implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ReferenceCountedCache.class);
private final ConcurrentMap<K, CacheEntry<V>> mMap = Maps.newConcurrentMap();
private final Function<K, V> mCacheLoader;
/**
* Flag to indicate whether this reference counted cache is still open. Must only be mutated
* by {@link #close()} to set it to false.
*/
private volatile boolean mIsOpen = true;
/**
* Private default constructor.
* @param cacheLoader function to compute cached values on demand. Should never return null.
*/
private ReferenceCountedCache(Function<K, V> cacheLoader) {
mCacheLoader = cacheLoader;
}
/**
* Create a {@code ReferenceCountedCache} using the supplied function to create cached values
* on demand. The function may be evaluated with the same key multiple times in the case that
* the key becomes invalidated due to the reference count falling to 0. A function need not handle
* the case of a null key, but it should never return a null value for any key.
*
* @param cacheLoader function to compute cached values on demand. Should never return null.
* @return a new {@link ReferenceCountedCache}.
* @param <K> key type of cache.
* @param <V> value type (must implement {@link java.io.Closeable}) of cache.
*/
public static <K, V extends Closeable> ReferenceCountedCache<K, V> create(
Function<K, V> cacheLoader
) {
return new ReferenceCountedCache<K, V>(cacheLoader);
}
/*
Notes on thread safety, etc:
This cache uses a lock-per-entry scheme to reduce lock contention across threads accessing
different keys. Any access to a CacheEntry must be synchronized on that instance.
*/
/**
* Returns the value associated with {@code key} in this cache, first loading that value if
* necessary. No observable state associated with this cache is modified until loading completes.
*
* @param key for which to retrieve cached value.
* @return cached value associated with the key.
*/
public V get(K key) {
Preconditions.checkState(mIsOpen, "ReferenceCountedCache is closed.");
Preconditions.checkNotNull(key);
while (true) {
final CacheEntry<V> entry = mMap.get(key);
if (entry != null) {
// There is a cached entry.
synchronized (entry) {
// We need to check that the cached entry is still valid, because we didn't hold the
// entry's lock when we retrieved it.
if (entry.getCount() > 0) {
// The entry is still valid.
entry.incrementAndGetCount();
return entry.getValue();
}
// Someone else cleaned up the retrieved entry; try again.
}
} else {
// No cached entry; attempt to make a new one.
final CacheEntry<V> newEntry = new CacheEntry<V>();
synchronized (newEntry) {
// Synchronize on `newEntry` so that no one else can use it in the time between
// we insert it in the cache and we set the value.
if (mMap.putIfAbsent(key, newEntry) == null) {
// We successfully made a new entry and cached it
V value = mCacheLoader.apply(key);
newEntry.setValue(value);
newEntry.incrementAndGetCount();
return value;
}
// Someone else created it first; try again.
}
}
}
}
/**
* Indicate to the cache that the client is done using the cached value for the given key. Clients
* of {@link ReferenceCountedCache} must call this after finishing using the value retrieved from
* the cache. The retrieved is no longer guaraunteed to be valid after it is released back to the
* {@link ReferenceCountedCache}
*
* @param key to cache entry no longer being used by the client.
* @throws java.io.IOException if closing the cached value throws an {@code IOException}.
*/
public void release(K key) throws IOException {
Preconditions.checkState(mIsOpen, "ReferenceCountedCache is closed.");
Preconditions.checkNotNull(key);
CacheEntry<V> entry = mMap.get(key);
Preconditions.checkState(entry != null, "No cached value for key '%s'.", key);
synchronized (entry) {
if (entry.decrementAndGetCount() == 0) {
// We need to remove the entry from the cache and clean up the value.
mMap.remove(key);
entry.getValue().close();
}
}
}
/**
* Returns whether this cache contains <i>or</i> contained a cached entry for the provided key.
*
* @param key to check for a cached entry.
* @return whether this cache contains <i>or</i> contained a cached entry for the key.
*/
public boolean containsKey(K key) {
Preconditions.checkNotNull(key);
return mMap.containsKey(key);
}
/**
* Make a best effort at closing all the cached values. This method is *not* guaranteed to close
* every cached value if there are concurrent users of the cache. As a result, this method
* should only be relied upon if only a single thread is using this cache while {@code #close} is
* called.
*
* @throws IOException if any entry throws an IOException while closing. An entry throwing an
* IOException will prevent any further entries from being cleaned up.
*/
@Override
public void close() throws IOException {
mIsOpen = false;
for (Map.Entry<K, CacheEntry<V>> entry : mMap.entrySet()) {
// Attempt to remove the entry from the cache
if (mMap.remove(entry.getKey(), entry.getValue())) {
// If successfull, close the value
CacheEntry<V> cacheEntry = entry.getValue();
synchronized (cacheEntry) {
cacheEntry.getValue().close();
}
}
}
}
/**
* A cache entry which includes a value and a reference count. This class is *not* thread safe.
* All method calls should be externally synchronized.
*/
private static final class CacheEntry<V> {
private V mValue;
private int mCount = 0;
/**
* Set the value of this entry. Should only be called a single time.
*
* @param value to set entry.
* @return this.
*/
public CacheEntry<V> setValue(V value) {
Preconditions.checkState(mValue == null, "Value already set.");
mValue = Preconditions.checkNotNull(value);
return this;
}
/**
* Returns the value held by this cache entry.
*
* @return the value.
*/
public V getValue() {
Preconditions.checkState(mValue != null, "Value not yet set.");
return mValue;
}
/**
* Increment the reference count and return the new count.
*
* @return the newly incremented count.
*/
public int incrementAndGetCount() {
return ++mCount;
}
/**
* Decrement the reference count and return the new count.
*
* @return the newly decremented count.
*/
public int decrementAndGetCount() {
return --mCount;
}
/**
* Get the reference count.
*
* @return the reference count.
*/
public int getCount() {
return mCount;
}
}
}
| |
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.utils.statistics;
import java.io.PrintStream;
/**
* This class will contain commonly used statistical
* tests. At present, the only test available is
* the t-test. This can be used in paired or unpaired
* modes, and in each case one or two-sided tests may
* be applied. The other useful feature
*/
public class StatisticalTests
{
//static Class dummy = Stats.class;
public static double sqr(double x)
{
return x * x;
}
public static double sumSquareDiff(double[] x, double mean)
{
double tot = 0.0;
for (int i = 0; i < x.length; i++)
{
tot += sqr(x[i] - mean);
}
return tot;
}
public static double correlation(double[] x, double[] y)
{
double mx = Stats.mean(x);
double my = Stats.mean(y);
double xy = sumProdDiff(x, y, mx, my);
double xx = sumSquareDiff(x, mx);
double yy = sumSquareDiff(y, my);
return xy / Math.sqrt(xx * yy);
}
public static double sumSquare(double[] x)
{
double tot = 0.0;
for (int i = 0; i < x.length; i++)
{
tot += x[i] * x[i];
}
return tot;
}
public static double sumProdDiff(double[] x, double[] y, double mx, double my)
{
double tot = 0.0;
for (int i = 0; i < x.length; i++)
{
tot += (x[i] - mx) * (y[i] - my);
}
return tot;
}
/**
* Calculates the probability with which the
* null hypothesis (that the means are equal)
* can be rejected in favour of the alternative
* hypothesis that they are not equal (hence uses
* a two-sided test). The samples are not paired
* and do not have to be of equal size,
*/
public static double tNotPairedOneSided(double[] s1, double[] s2)
{
return tNotPaired(s1, s2, false);
}
/**
* Calculates the probability with which the
* null hypothesis (that the means are equal)
* can be rejected in favour of the alternative
* hypothesis that one is greater than the other
* (hence uses a single-sided test).
* The samples are not paired
* and do not have to be of equal size,
*/
public static double tNotPairedTwoSided(double[] s1, double[] s2)
{
return tNotPaired(s1, s2, true);
}
/**
* Calculates the probability with which the
* null hypothesis (that the means are equal)
* can be rejected in favour of the alternative
* hypothesis. Uses a twoSided test if twoSided = true,
* otherwise uses a one-sided test.
*/
public static double tNotPaired(double[] s1, double[] s2, boolean twoSided)
{
double m1 = Stats.mean(s1);
double m2 = Stats.mean(s2);
double ss1 = sumSquareDiff(s1, m1);
double ss2 = sumSquareDiff(s2, m2);
return tNotPaired(m1, m2, ss1, ss2, s1.length, s2.length, twoSided);
}
public static double tNotPaired(
double m1, double m2, double ss1, double ss2, int n1, int n2, boolean twoSided)
{
double nu = n1 + n2 - 2;
double stderr =
Math.sqrt((ss1 + ss2) * (1.0 / n1 + 1.0 / n2) / nu);
double t = (m1 - m2) / stderr;
if (twoSided)
{
return tTest(t, nu);
}
else
{
return tSingle(t, nu);
}
}
/**
* Applies a one-sided t-test to two arrays of paired samples.
* The arrays must be the same size; failure to ensure this
* could cause an ArrayOutOfBoundsException.
*/
public static double tPairedOneSided(double[] s1, double[] s2)
{
return tPaired(s1, s2, false);
}
/**
* Applies a two-sided t-test to two arrays of paired samples.
* The arrays must be the same size; failure to ensure this
* could cause an ArrayOutOfBoundsException.
*/
public static double tPairedTwoSided(double[] s1, double[] s2)
{
return tPaired(s1, s2, true);
}
/**
* Applies a t-test to two arrays of paired samples.
* One or two-sided is chosen depending on the value of
* the boolean variable 'two-sided'.
* The arrays must be the same size; failure to ensure this
* could cause an ArrayOutOfBoundsException.
*/
public static double tPaired(double[] s1, double[] s2, boolean twoSided)
{
double[] d = new double[s1.length];
for (int i = 0; i < d.length; i++)
{
d[i] = s1[i] - s2[i];
}
return tPaired(d, twoSided); // , Stats.mean(s1) - Stats.mean(s2));
}
/*
private static double tPaired2(double[] s1, double[] s2) {
double var1 = Stats.variance(s1);
double var2 = Stats.variance(s2);
double covar = Stats.covar(s1, s2);
// System.out.println("Covar = " + covar);
double nu = s1.length - 1;
double m1 = Stats.mean(s1);
double m2 = Stats.mean(s2);
double stderr = Math.sqrt((var1 + var2 - 2 * covar) / s1.length);
double t = (m1 - m2) / stderr;
return tTest(t, nu);
}
*/
/**
* Applies the t-test to an array of the differences
* between paired samples of observations.
*/
public static double tPairedOneSided(double[] d)
{
return tPaired(d, false);
}
public static double tPairedTwoSided(double[] d)
{
return tPaired(d, true);
}
public static double tPaired(double[] d, boolean twoSided)
{
// need to decide whether to do single or double sided!
double mean = Stats.mean(d);
double variance = Stats.variance(d);
// double var2 = sumSquareDiff(d, mean) / (d.length - 1);
System.out.println(mean + " : " + variance);
// Wait.Input();
double stderr = Math.sqrt(variance / d.length);
double nu = d.length - 1;
double t = mean / stderr;
System.out.println("t = " + t);
if (twoSided)
{
return tTest(t, nu);
}
else
{
return tSingle(t, nu);
}
}
/**
* This method returns the distance x from the mean m
* such that the area under the t distribution
* (estimated from the data d) between (m - x) and (m + x) is equal
* to conf.
* <p>
* In other words, it finds the desired confidence interval of the
* mean of the population from which the data is
* drawn. For example, if conf = 0.95, then there
* is a 95% chance that the mean lies between (m - x) and (m + x).
*
* @param d
* the array of data
* @param conf
* the desired confidence interval
*
* @return the spread around the sample mean of the population mean
* within that confidence interval
*/
public static double confDiff(double[] d, double conf)
{
// find the alpha which gives this confidence level
double mean = Stats.mean(d);
// System.out.println("SDEV = " + Stats.sdev(d));
double stderr = Stats.stderr(d);
double nu = d.length - 1.0;
double t = findt(1.0 - (1.0 - conf) / 1, nu);
// System.out.println(t + "\t" + conf + "\t" + nu);
return t * stderr;
}
private static void printConfs(double[] d, double conf, PrintStream ps)
{
double cd = confDiff(d, conf);
double m = Stats.mean(d);
ps.println("At " + conf + " : " + (m - cd) + " < " + m + " < " + (m + cd));
}
/**
* Finds the value of t that would match the required
* confidence and nu.
*/
public static double findt(double conf, double nu)
{
double eps = 0.00001; // accuracy
// do a binary search for it
double lower = 1.0;
double upper = 100.0;
double mid = 0.0;
for (int i = 0; i < 100; i++)
{
mid = (lower + upper) / 2;
// each time, if mid is too big
// fix lower to mid
// else fix upper to mid
double cur = tTest(mid, nu);
if (Math.abs(conf - cur) < eps)
{
// System.out.println("Converged to " + cur + " in " + i + " iterations");
return mid;
}
if (cur < conf) // mid too small
{
lower = mid;
}
else // mid too big
{
upper = mid;
}
}
return mid;
}
/**
* Bin root - a binary search for a square root.
* I wrote this purely to check my recollection
* of how this kind of search can be used to invert
* functions.
*/
private static double binRoot(double x)
{
double eps = 0.0001; // accuracy
// do a binary search for it
// find the square root of x using a binary search
double lower = 0.0;
double upper = x;
double mid = 0.0;
for (int i = 0; i < 100; i++)
{
mid = (lower + upper) / 2;
// each time, if mid is too big
// fix lower to mid
// else fix upper to mid
double cur = mid * mid;
if (Math.abs(x - cur) < eps)
{
// System.out.println("Converged to " + cur + " in " + i + " iterations");
return mid;
}
if (cur < x) // mid too small
{
lower = mid;
}
else // mid too big
{
upper = mid;
}
}
return mid;
}
/**
* Applies the two-sided t-test given the value of t and nu.
* To do this it calls betai.
*/
public static double tTest(double t, double nu)
{
double a = nu / 2.0;
double b = 0.5;
double x = nu / (nu + t * t);
return 1.0 - betai(a, b, x); // to be done
}
/**
* Applies the single-sided t-test given the value of t and nu.
* To do this it calls betai.
*/
public static double tSingle(double t, double nu)
{
return 1.0 - (1.0 - tTest(t, nu)) / 2;
}
protected static double gammln(double xx)
{
double stp = 2.50662827465;
double x, tmp, ser;
x = xx - 1.0;
tmp = x + 5.5;
tmp = (x + 0.5) * Math.log(tmp) - tmp;
ser = 1.0
+ 76.18009173 / (x + 1.0)
- 86.50532033 / (x + 2.0)
+ 24.01409822 / (x + 3.0)
- 1.231739516 / (x + 4.0)
+ 0.120858003 / (x + 5.0)
- 0.536382e-5 / (x + 6.0);
return tmp + Math.log(stp * ser); // finish
}
protected static double betai(double a, double b, double x)
{
// can be used to find t statistic
double bt;
if ((x < 0.0) || (x > 1.0))
{
System.out.println("Error in betai: " + x);
}
if ((x == 0.0) || (x == 1.0))
{
bt = 0.0;
}
else
{
bt = Math.exp(gammln(a + b) - gammln(a) - gammln(b)
+ a * Math.log(x)
+ b * Math.log(1.0 - x));
}
if (x < (a + 1.0) / (a + b + 2.0))
{
return bt * betacf(a, b, x) / a;
}
else
{
return 1.0 - bt * betacf(b, a, 1.0 - x) / b;
}
}
protected static double betacf(double a, double b, double x)
{
int maxIts = 100;
double eps = 3.0e-7;
double tem, qap, qam, qab, em, d;
double bz, bpp, bp, bm, az, app;
double am, aold, ap;
am = 1.0;
bm = 1.0;
az = 1.0;
qab = a + b;
qap = a + 1.0;
qam = a - 1.0;
bz = 1.0 - qab * x / qap;
for (int m = 1; m <= maxIts; m++)
{
em = m;
tem = em + em;
d = em * (b - m) * x / ((qam + tem) * (a + tem));
ap = az + d * am;
bp = bz + d * bm;
d = -(a + em) * (qab + em) * x / ((a + tem) * (qap + tem));
app = ap + d * az;
bpp = bp + d * bz;
aold = az;
am = ap / bpp;
bm = bp / bpp;
az = app / bpp;
bz = 1.0;
if (Math.abs(az - aold) < eps * Math.abs(az))
{
return az;
}
}
System.out.println("a or b too big, or maxIts too small");
return -1;
}
/**
* Fills an array with uniform random numbers
* within +/- 0.5 of the mean.
*/
private static void fillUniform(double[] d, double mean)
{
for (int i = 0; i < d.length; i++)
{
d[i] = Math.random() + mean - 0.5;
}
}
private static void test()
{
System.out.println(tTest(1.311, 29));
System.out.println(tSingle(1.311, 29));
System.out.println(tTest(1.699, 29));
System.out.println(tTest(2.045, 29));
System.out.println(tTest(0.9, 29));
System.out.println(tTest(0.95, 29));
}
/**
* This uses an example from Statistics for Business and Economics
* (page 293 - 294)
* to check the calculation of the confidence intervals
* for the mean of a dataset.
* <p>
* The data is: double[] mpg = {18.6, 18.4, 19.2, 20.8, 19.4, 20.5};
* <p>
* Running the program proiduces the following output:
* <p>
* <pre>
* At 0.8 : 18.89 < 19.48 < 20.07
* At 0.9 : 18.67 < 19.48 < 20.29
* At 0.95 : 18.45 < 19.48 < 20.51
* At 0.99 : 17.86 < 19.48 < 21.09
* </pre>
* <p>
* <p>
* This matches closely with the book - any differences
* are due to small errors in the book version due to
* the limited number of decimal places used (2) in the
* handworked example.
*/
public static void confTest()
{
double[] mpg = {18.6, 18.4, 19.2, 20.8, 19.4, 20.5};
// System.out.println("Variance2 = " + Stats.variance2(mpg));
// System.out.println("Mean = " + Stats.mean(mpg));
// System.out.println("Var = " + Stats.variance(mpg));
// Wait.Input();
// System.exit(0);
confTest(mpg);
// Wait.Input();
}
private static void confTest(double[] s)
{
printConfs(s, 0.8, System.out);
printConfs(s, 0.9, System.out);
printConfs(s, 0.95, System.out);
printConfs(s, 0.99, System.out);
}
private static void addConst(double[] v1, double[] v2, double c)
{
for (int i = 0; i < v1.length; i++)
{
v2[i] = v1[i] + c;
}
}
/**
* Runs a t-test on some text book data.
* <p>
* The data is from page 362 of Statistics for Business and Economics
*/
private static void testT()
{
double[] s1 = {137, 135, 83, 125, 47, 46, 114, 157, 57, 144};
double[] s2 = {53, 114, 81, 86, 34, 66, 89, 113, 88, 111};
System.out.println("(Paired (one)) Reject h0 with prob. " + tPairedOneSided(s1, s2));
System.out.println("(Paired (two)) Reject h0 with prob. " + tPairedTwoSided(s1, s2));
System.out.println("(Not paired (one)) Reject h0 with prob. " + tNotPairedOneSided(s1, s2));
System.out.println("(Not paired (two)) Reject h0 with prob. " + tNotPairedTwoSided(s1, s2));
}
/**
* Runs through some text-book utils to check that
* the statistical tests are working properly.
*/
public static void main(String[] args)
{
// test the t-statistic
// example from business stats book used in order to check it
confTest();
// testT();
System.exit(0);
/*
test();
System.out.println("\n\n" + binRoot(81));
Wait.Input();
double t = 0.11;
double nu = 9.0;
System.out.println(tTest(t, nu));
*/
int n = 10;
double[] dd = new double[n];
fillUniform(dd, 0.0);
double[] d = new double[n];
for (int i = 0; i < 10; i++)
{
fillUniform(d, i / 10.0);
// addConst(dd, d, i / 10.0);
// System.out.println(i + "\t " + tPaired(d, dd) + "\t " + tPaired2(d, dd) + "\t" + tNotPaired(d, dd));
}
}
}
| |
package org.ethereum.crypto;
import org.ethereum.util.Utils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.AsymmetricCipherKeyPair;
import org.spongycastle.crypto.BufferedBlockCipher;
import org.spongycastle.crypto.KeyEncoder;
import org.spongycastle.crypto.KeyGenerationParameters;
import org.spongycastle.crypto.agreement.ECDHBasicAgreement;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.engines.AESFastEngine;
import org.spongycastle.crypto.engines.IESEngine;
import org.spongycastle.crypto.generators.ECKeyPairGenerator;
import org.spongycastle.crypto.generators.EphemeralKeyPairGenerator;
import org.spongycastle.crypto.generators.KDF2BytesGenerator;
import org.spongycastle.crypto.macs.HMac;
import org.spongycastle.crypto.modes.SICBlockCipher;
import org.spongycastle.crypto.params.*;
import org.spongycastle.crypto.parsers.ECIESPublicKeyParser;
import org.spongycastle.math.ec.ECPoint;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.security.SecureRandom;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.junit.Assert.assertEquals;
public class CryptoTest {
private static final Logger log = LoggerFactory.getLogger("test");
@Test
public void test1() {
byte[] result = HashUtil.sha3("horse".getBytes());
assertEquals("c87f65ff3f271bf5dc8643484f66b200109caffe4bf98c4cb393dc35740b28c0",
Hex.toHexString(result));
result = HashUtil.sha3("cow".getBytes());
assertEquals("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4",
Hex.toHexString(result));
}
@Test
public void test3() {
BigInteger privKey = new BigInteger("cd244b3015703ddf545595da06ada5516628c5feadbf49dc66049c4b370cc5d8", 16);
byte[] addr = ECKey.fromPrivate(privKey).getAddress();
assertEquals("89b44e4d3c81ede05d0f5de8d1a68f754d73d997", Hex.toHexString(addr));
}
@Test
public void test4() {
byte[] cowBytes = HashUtil.sha3("cow".getBytes());
byte[] addr = ECKey.fromPrivate(cowBytes).getAddress();
assertEquals("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826", Hex.toHexString(addr).toUpperCase());
}
@Test
public void test5() {
byte[] horseBytes = HashUtil.sha3("horse".getBytes());
byte[] addr = ECKey.fromPrivate(horseBytes).getAddress();
assertEquals("13978AEE95F38490E9769C39B2773ED763D9CD5F", Hex.toHexString(addr).toUpperCase());
}
@Test /* performance test */
public void test6() {
long firstTime = System.currentTimeMillis();
System.out.println(firstTime);
for (int i = 0; i < 1000; ++i) {
byte[] horseBytes = HashUtil.sha3("horse".getBytes());
byte[] addr = ECKey.fromPrivate(horseBytes).getAddress();
assertEquals("13978AEE95F38490E9769C39B2773ED763D9CD5F", Hex.toHexString(addr).toUpperCase());
}
long secondTime = System.currentTimeMillis();
System.out.println(secondTime);
System.out.println(secondTime - firstTime + " millisec");
// 1) result: ~52 address calculation every second
}
@Test /* real tx hash calc */
public void test7() {
String txRaw = "F89D80809400000000000000000000000000000000000000008609184E72A000822710B3606956330C0D630000003359366000530A0D630000003359602060005301356000533557604060005301600054630000000C5884336069571CA07F6EB94576346488C6253197BDE6A7E59DDC36F2773672C849402AA9C402C3C4A06D254E662BF7450DD8D835160CBB053463FED0B53F2CDD7F3EA8731919C8E8CC";
byte[] txHashB = HashUtil.sha3(Hex.decode(txRaw));
String txHash = Hex.toHexString(txHashB);
assertEquals("4b7d9670a92bf120d5b43400543b69304a14d767cf836a7f6abff4edde092895", txHash);
}
@Test /* real block hash calc */
public void test8() {
String blockRaw = "F885F8818080A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347940000000000000000000000000000000000000000A0BCDDD284BF396739C224DBA0411566C891C32115FEB998A3E2B4E61F3F35582AA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934783800000808080C0C0";
byte[] blockHashB = HashUtil.sha3(Hex.decode(blockRaw));
String blockHash = Hex.toHexString(blockHashB);
System.out.println(blockHash);
}
@Test
public void test9() {
// TODO: https://tools.ietf.org/html/rfc6979#section-2.2
// TODO: https://github.com/bcgit/bc-java/blob/master/core/src/main/java/org/bouncycastle/crypto/signers/ECDSASigner.java
System.out.println(new BigInteger(Hex.decode("3913517ebd3c0c65000000")));
System.out.println(Utils.getValueShortString(new BigInteger("69000000000000000000000000")));
}
@Test
public void test10() {
BigInteger privKey = new BigInteger("74ef8a796480dda87b4bc550b94c408ad386af0f65926a392136286784d63858", 16);
byte[] addr = ECKey.fromPrivate(privKey).getAddress();
assertEquals("ba73facb4f8291f09f27f90fe1213537b910065e", Hex.toHexString(addr));
}
@Test // basic encryption/decryption
public void test11() throws Throwable {
byte[] keyBytes = sha3("...".getBytes());
log.info("key: {}", Hex.toHexString(keyBytes));
byte[] ivBytes = new byte[16];
byte[] payload = Hex.decode("22400891000000000000000000000000");
KeyParameter key = new KeyParameter(keyBytes);
ParametersWithIV params = new ParametersWithIV(key, new byte[16]);
AESFastEngine engine = new AESFastEngine();
SICBlockCipher ctrEngine = new SICBlockCipher(engine);
ctrEngine.init(true, params);
byte[] cipher = new byte[16];
ctrEngine.processBlock(payload, 0, cipher, 0);
log.info("cipher: {}", Hex.toHexString(cipher));
byte[] output = new byte[cipher.length];
ctrEngine.init(false, params);
ctrEngine.processBlock(cipher, 0, output, 0);
assertEquals(Hex.toHexString(output), Hex.toHexString(payload));
log.info("original: {}", Hex.toHexString(payload));
}
@Test // big packet encryption
public void test12() throws Throwable {
AESFastEngine engine = new AESFastEngine();
SICBlockCipher ctrEngine = new SICBlockCipher(engine);
byte[] keyBytes = Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1");
byte[] ivBytes = new byte[16];
byte[] payload = Hex.decode("0109efc76519b683d543db9d0991bcde99cc9a3d14b1d0ecb8e9f1f66f31558593d746eaa112891b04ef7126e1dce17c9ac92ebf39e010f0028b8ec699f56f5d0c0d00");
byte[] cipherText = Hex.decode("f9fab4e9dd9fc3e5d0d0d16da254a2ac24df81c076e3214e2c57da80a46e6ae4752f4b547889fa692b0997d74f36bb7c047100ba71045cb72cfafcc7f9a251762cdf8f");
KeyParameter key = new KeyParameter(keyBytes);
ParametersWithIV params = new ParametersWithIV(key, ivBytes);
ctrEngine.init(true, params);
byte[] in = payload;
byte[] out = new byte[in.length];
int i = 0;
while(i < in.length){
ctrEngine.processBlock(in, i, out, i);
i += engine.getBlockSize();
if (in.length - i < engine.getBlockSize())
break;
}
// process left bytes
if (in.length - i > 0){
byte[] tmpBlock = new byte[16];
System.arraycopy(in, i, tmpBlock, 0, in.length - i);
ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
System.arraycopy(tmpBlock, 0, out, i, in.length - i);
}
log.info("cipher: {}", Hex.toHexString(out));
assertEquals(Hex.toHexString(cipherText), Hex.toHexString(out));
}
@Test // cpp keys demystified
public void test13() throws Throwable {
// us.secret() a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1
// us.public() caa3d5086b31529bb00207eabf244a0a6c54d807d2ac0ec1f3b1bdde0dbf8130c115b1eaf62ce0f8062bcf70c0fefbc97cec79e7faffcc844a149a17fcd7bada
// us.address() 47d8cb63a7965d98b547b9f0333a654b60ffa190
ECKey key = ECKey.fromPrivate(Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1"));
String address = Hex.toHexString(key.getAddress());
String pubkey = Hex.toHexString(key.getPubKeyPoint().getEncoded(/* uncompressed form */ false));
log.info("address: " + address);
log.info("pubkey: " + pubkey);
assertEquals("47d8cb63a7965d98b547b9f0333a654b60ffa190", address);
assertEquals("04caa3d5086b31529bb00207eabf244a0a6c54d807d2ac0ec1f3b1bdde0dbf8130c115b1eaf62ce0f8062bcf70c0fefbc97cec79e7faffcc844a149a17fcd7bada", pubkey);
}
@Test // ECIES_AES128_SHA256 + No Ephemeral Key + IV(all zeroes)
public void test14() throws Throwable{
AESFastEngine aesFastEngine = new AESFastEngine();
IESEngine iesEngine = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA256Digest()),
new HMac(new SHA256Digest()),
new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);
ECKeyPairGenerator eGen = new ECKeyPairGenerator();
KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
eGen.init(gParam);
AsymmetricCipherKeyPair p1 = eGen.generateKeyPair();
AsymmetricCipherKeyPair p2 = eGen.generateKeyPair();
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
ECKeyPairGenerator generator = new ECKeyPairGenerator();
generator.init(keygenParams);
ECKeyPairGenerator gen = new ECKeyPairGenerator();
gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));
iesEngine.init(true, p1.getPrivate(), p2.getPublic(), parametersWithIV);
byte[] message = Hex.decode("010101");
log.info("payload: {}", Hex.toHexString(message));
byte[] cipher = iesEngine.processBlock(message, 0, message.length);
log.info("cipher: {}", Hex.toHexString(cipher));
IESEngine decryptorIES_Engine = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator (new SHA256Digest()),
new HMac(new SHA256Digest()),
new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
decryptorIES_Engine.init(false, p2.getPrivate(), p1.getPublic(), parametersWithIV);
byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);
log.info("orig: " + Hex.toHexString(orig));
}
@Test // ECIES_AES128_SHA256 + Ephemeral Key + IV(all zeroes)
public void test15() throws Throwable{
byte[] privKey = Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1");
ECKey ecKey = ECKey.fromPrivate(privKey);
ECPrivateKeyParameters ecPrivKey = new ECPrivateKeyParameters(ecKey.getPrivKey(), ECKey.CURVE);
ECPublicKeyParameters ecPubKey = new ECPublicKeyParameters(ecKey.getPubKeyPoint(), ECKey.CURVE);
AsymmetricCipherKeyPair myKey = new AsymmetricCipherKeyPair(ecPubKey, ecPrivKey);
AESFastEngine aesFastEngine = new AESFastEngine();
IESEngine iesEngine = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator(new SHA256Digest()),
new HMac(new SHA256Digest()),
new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);
ECKeyPairGenerator eGen = new ECKeyPairGenerator();
KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
eGen.init(gParam);
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
ECKeyPairGenerator generator = new ECKeyPairGenerator();
generator.init(keygenParams);
EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(generator, new KeyEncoder()
{
public byte[] getEncoded(AsymmetricKeyParameter keyParameter)
{
return ((ECPublicKeyParameters)keyParameter).getQ().getEncoded();
}
});
ECKeyPairGenerator gen = new ECKeyPairGenerator();
gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));
iesEngine.init(myKey.getPublic(), parametersWithIV, kGen);
byte[] message = Hex.decode("010101");
log.info("payload: {}", Hex.toHexString(message));
byte[] cipher = iesEngine.processBlock(message, 0, message.length);
log.info("cipher: {}", Hex.toHexString(cipher));
IESEngine decryptorIES_Engine = new IESEngine(
new ECDHBasicAgreement(),
new KDF2BytesGenerator (new SHA256Digest()),
new HMac(new SHA256Digest()),
new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
decryptorIES_Engine.init(myKey.getPrivate(), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE));
byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);
log.info("orig: " + Hex.toHexString(orig));
}
}
| |
package it.finsiel.siged.mvc.presentation.actionform.protocollo;
import it.finsiel.siged.constant.Constants;
import it.finsiel.siged.model.organizzazione.Organizzazione;
import it.finsiel.siged.model.organizzazione.Ufficio;
import it.finsiel.siged.model.organizzazione.Utente;
import it.finsiel.siged.mvc.vo.lookup.TitolarioVO;
import it.finsiel.siged.mvc.vo.organizzazione.UfficioVO;
import it.finsiel.siged.util.DateUtil;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class RicercaEvidenzaForm extends ActionForm implements
AlberoUfficiUtentiForm {
static Logger logger = Logger
.getLogger(RicercaEvidenzaForm.class.getName());
private int ufficioResponsabileId;
private int utenteResponsabileId;
private String dataEvidenzaDa;
private String dataEvidenzaA;
private TitolarioVO titolario;
private int titolarioPrecedenteId;
private int titolarioSelezionatoId;
private Collection titolariFigli;
private int ufficioCorrenteId;
private String ufficioCorrentePath;
private int ufficioSelezionatoId;
private int utenteSelezionatoId;
private Collection ufficiDipendenti;
private UfficioVO ufficioCorrente;
private Collection utenti;
private int aooId;
private int ufficioRicercaId;
private Utente utenteCorrente;
private String fascicoliProcedimenti = "F";
// private String referente;
// public String getReferente() {
// return referente;
// }
//
// public void setReferente(String referente) {
// this.referente = referente;
// }
private Collection evidenzeProcedimenti;
private Collection evidenzeFascicoli;
private ArrayList elencoEvidenze = new ArrayList();
public Utente getUtenteCorrente() {
return utenteCorrente;
}
public void setUtenteCorrente(Utente utenteCorrente) {
this.utenteCorrente = utenteCorrente;
}
public int getUfficioRicercaId() {
return ufficioRicercaId;
}
public void setUfficioRicercaId(int ufficioRicercaId) {
this.ufficioRicercaId = ufficioRicercaId;
}
public int getAooId() {
return aooId;
}
public void setAooId(int aooId) {
this.aooId = aooId;
}
public void inizializzaForm() {
setDataEvidenzaA(null);
setDataEvidenzaDa(null);
setTitolariFigli(null);
setTitolario(null);
setTitolarioPrecedenteId(0);
setTitolarioSelezionatoId(0);
setUfficioCorrenteId(0);
setFascicoliProcedimenti("F");
}
public Collection getUtenti() {
return utenti;
}
public void setUtenti(Collection utenti) {
this.utenti = utenti;
}
public Collection getTitolariFigli() {
return titolariFigli;
}
public void setTitolariFigli(Collection titolariFigli) {
this.titolariFigli = titolariFigli;
}
public TitolarioVO getTitolario() {
return titolario;
}
public void setTitolario(TitolarioVO titolario) {
this.titolario = titolario;
}
public int getTitolarioPrecedenteId() {
return titolarioPrecedenteId;
}
public void setTitolarioPrecedenteId(int titolarioPrecedenteId) {
this.titolarioPrecedenteId = titolarioPrecedenteId;
}
public int getTitolarioSelezionatoId() {
return titolarioSelezionatoId;
}
public void setTitolarioSelezionatoId(int titolarioSelezionatoId) {
this.titolarioSelezionatoId = titolarioSelezionatoId;
}
public int getUfficioResponsabileId() {
return ufficioResponsabileId;
}
public void setUfficioResponsabileId(int ufficioResponsabileId) {
this.ufficioResponsabileId = ufficioResponsabileId;
}
public int getUtenteResponsabileId() {
return utenteResponsabileId;
}
public void setUtenteResponsabileId(int utenteResponsabileId) {
this.utenteResponsabileId = utenteResponsabileId;
}
public String getUfficioCorrentePath() {
return ufficioCorrentePath;
}
public void setUfficioCorrentePath(String ufficioCorrentePath) {
this.ufficioCorrentePath = ufficioCorrentePath;
}
public int getUfficioSelezionatoId() {
return ufficioSelezionatoId;
}
public void setUfficioSelezionatoId(int ufficioCorrenteId) {
this.ufficioSelezionatoId = ufficioCorrenteId;
}
public int getUtenteSelezionatoId() {
return utenteSelezionatoId;
}
public void setUtenteSelezionatoId(int utenteCorrenteId) {
this.utenteSelezionatoId = utenteCorrenteId;
}
public UfficioVO getUfficioCorrente() {
return ufficioCorrente;
}
public void setUfficioCorrente(UfficioVO ufficioCorrente) {
this.ufficioCorrente = ufficioCorrente;
}
public String getIntestatario() {
Organizzazione org = Organizzazione.getInstance();
Ufficio uff = org.getUfficio(getUfficioCorrenteId());
Utente ute = org.getUtente(getUtenteSelezionatoId());
return uff.getPath() + ute.getValueObject().getFullName();
}
public int getUfficioCorrenteId() {
return ufficioCorrenteId;
}
public void setUfficioCorrenteId(int ufficioCorrenteId) {
this.ufficioCorrenteId = ufficioCorrenteId;
}
public String getDataEvidenzaDa() {
return dataEvidenzaDa;
}
public void setDataEvidenzaDa(String dataEvidenzaDa) {
this.dataEvidenzaDa = dataEvidenzaDa;
}
public String getDataEvidenzaA() {
return dataEvidenzaA;
}
public void setDataEvidenzaA(String dataEvidenzaA) {
this.dataEvidenzaA = dataEvidenzaA;
}
public Collection getUfficiDipendenti() {
return ufficiDipendenti;
}
public void setUfficiDipendenti(Collection ufficiDipendenti) {
this.ufficiDipendenti = ufficiDipendenti;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.utenteCorrente = (Utente) request.getSession().getAttribute(
Constants.UTENTE_KEY);
}
public boolean isTuttiUffici() {
if (getUfficioCorrente() == null)
return false;
boolean tutti = getUfficioCorrente().getParentId() == 0;
if (!tutti) {
tutti = getUfficioCorrente().getId().equals(
utenteCorrente.getUfficioVOInUso().getId());
}
return tutti;
}
public ArrayList getElencoEvidenze() {
return elencoEvidenze;
}
public void setElencoEvidenze(ArrayList elencoEvidenze) {
this.elencoEvidenze = elencoEvidenze;
}
public Collection getEvidenzeProcedimenti() {
return evidenzeProcedimenti;
}
public void setEvidenzeProcedimenti(Collection evidenzeProcedimenti) {
this.evidenzeProcedimenti = evidenzeProcedimenti;
}
public Collection getEvidenzeFascicoli() {
return evidenzeFascicoli;
}
public void setEvidenzeFascicoli(Collection evidenzeFascicoli) {
this.evidenzeFascicoli = evidenzeFascicoli;
}
public String getFascicoliProcedimenti() {
return fascicoliProcedimenti;
}
public void setFascicoliProcedimenti(String fascicoliProcedimenti) {
this.fascicoliProcedimenti = fascicoliProcedimenti;
}
public void reset(ActionMapping arg0, ServletRequest arg1) {
setFascicoliProcedimenti("F");
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
String dataEvidenzaDa = getDataEvidenzaDa();
String dataEvidenzaA = getDataEvidenzaA();
if (dataEvidenzaDa != null && !"".equals(dataEvidenzaDa)) {
if (!DateUtil.isData(dataEvidenzaDa)) {
errors.add("dataEvidenzaDa", new ActionMessage(
"formato.data.errato", "Data Evidenza Da"));
}
}
if (dataEvidenzaA != null && !"".equals(dataEvidenzaA)) {
if (!DateUtil.isData(dataEvidenzaA)) {
errors.add("dataEvidenzaA", new ActionMessage(
"formato.data.errato", "Data Evidenza A"));
}
}
if (dataEvidenzaDa != null && !"".equals(dataEvidenzaDa)
&& dataEvidenzaA != null && !"".equals(dataEvidenzaA)) {
// la data di ricezione non deve essere successiva a quella
// di registrazione
if (DateUtil.toDate(dataEvidenzaA).before(
DateUtil.toDate(dataEvidenzaDa))) {
errors.add("dataEvidenzaDa", new ActionMessage(
"data_1.non.successiva.data_2", "Data Evidenza A",
"Data Evidenza Da"));
}
}
return errors;
}
}
| |
/*
* Copyright (c) 2015 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.spotify.missinglink;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.spotify.missinglink.Conflict.ConflictCategory;
import com.spotify.missinglink.datamodel.AccessedField;
import com.spotify.missinglink.datamodel.Artifact;
import com.spotify.missinglink.datamodel.ArtifactName;
import com.spotify.missinglink.datamodel.CalledMethod;
import com.spotify.missinglink.datamodel.ClassTypeDescriptor;
import com.spotify.missinglink.datamodel.DeclaredClass;
import com.spotify.missinglink.datamodel.DeclaredField;
import com.spotify.missinglink.datamodel.DeclaredFieldBuilder;
import com.spotify.missinglink.datamodel.DeclaredMethod;
import com.spotify.missinglink.datamodel.Dependency;
import com.spotify.missinglink.datamodel.FieldDependencyBuilder;
import com.spotify.missinglink.datamodel.MethodDependencyBuilder;
import com.spotify.missinglink.datamodel.MethodDescriptor;
import com.spotify.missinglink.datamodel.TypeDescriptor;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import static java.util.stream.Collectors.toList;
/**
* Inputs:
* <p>
* 1) The full set of artifact dependencies (D). This can be extracted from the dependency graph.
* The exact structure of the graph is not interesting, only knowing which dependencies are a part
* of it. Note that this means that the same library can appear multiple times (with different
* versions)
* 2) The classpath of artifacts that is actually used (C). Ordering is important here. If a class
* appears
* more than once, the first occurrence will be used.
* <p>
* Assumptions:
* <p>
* 1) Each artifact could be compiled successfully using their own dependencies.
* 2) Each artifact was compiled against the same JDK, or at the very least only using parts of the
* JDK
* that didn't change compatibility. This is not a fully safe assumption, but to catch the
* kind of problems that could occur due to this would need a more broad analysis.
* <p>
* Strategy:
* 1) Identify which classes are a part of D but does not exist in C. This is the missing set (M)
* 2) Identify which classes are a part of D but are replaced in D (or is not the first occurrence)
* This is the suspicious set (S)
* 3) Walk through the class hierarchy graph.
* If something depends on something in M, also add that class to M.
* If something depends on something in S, also add that class to S
* 4) Walk through the method call graph, starting from the main entry point (the primary artifact)
* Whenever a method call is reached, check if the class and method exists.
* If it doesn't exist, also look in parent classes
* (implementations could exist both in superclasses and interfaces).
* <p>
* Note that we only need to try to verify the method if it's made to a class that is in M or S.
* If it is in M: fail.
* If it is in S: check it.
* <p>
* If we don't have access to one of the parents, we could simply assume that the call is safe
* This would however lead to all methods being marked as safe, since everything ultimately
* inherits from Object (or some other jdk class).
* <p>
* The alternative is to mark such calls as failures, which may lead to false positives.
* This might be ok for the MVP.
* <p>
* So we need to have the JDK classes (or some other provided dependencies) as input
* in order to lookup inheritance.
* <p>
* <p>
* <p>
* For now, this is not really in place - we simply just look at all the things in the classpath
*/
public class ConflictChecker {
public static final ArtifactName UNKNOWN_ARTIFACT_NAME = new ArtifactName("<unknown>");
/**
* @param projectArtifact the main artifact of the project we're verifying
* (this is considered the entry point for reachability)
* @param artifactsToCheck all artifacts that are on the runtime classpath
* @param allArtifacts all artifacts, including implicit artifacts (runtime provided
* artifacts)
* @param omitted list of artifacts If it is null, all classes are considered suspect,
* not classes from classes in an omitted artifact
* @return a list of conflicts
*/
public ImmutableList<Conflict> check(Artifact projectArtifact,
List<Artifact> artifactsToCheck,
List<Artifact> allArtifacts,
List<Artifact> omitted) {
final CheckerStateBuilder stateBuilder = new CheckerStateBuilder();
if (omitted != null) {
stateBuilder.potentialConflictClasses(Sets.newHashSet());
}
createCanonicalClassMapping(stateBuilder, allArtifacts, omitted);
CheckerState state = stateBuilder.build();
// brute-force reachability analysis
Set<TypeDescriptor> reachableClasses =
reachableFrom(projectArtifact.classes().values(), state.knownClasses());
final ImmutableList.Builder<Conflict> builder = ImmutableList.builder();
// Then go through everything in the classpath to make sure all the method calls / field references
// are satisfied.
for (Artifact artifact : artifactsToCheck) {
for (DeclaredClass clazz : artifact.classes().values()) {
if (!reachableClasses.contains(clazz.className())) {
continue;
}
for (DeclaredMethod method : clazz.methods().values()) {
checkForBrokenMethodCalls(state, artifact, clazz, method, builder);
checkForBrokenFieldAccess(state, artifact, clazz, method, builder);
}
}
}
return builder.build();
}
/**
* Create a canonical mapping of which classes are kept. First come first serve in the classpath
*
* @param stateBuilder conflict checker state we're populating
* @param allArtifacts maven artifacts to populate checker state with
*/
private void createCanonicalClassMapping(CheckerStateBuilder stateBuilder,
List<Artifact> allArtifacts, List<Artifact> omitted) {
for (Artifact artifact : allArtifacts) {
for (DeclaredClass clazz : artifact.classes().values()) {
if (stateBuilder.knownClasses().putIfAbsent(clazz.className(), clazz) != null) {
stateBuilder.potentialConflictClasses().map(p -> p.add(clazz.className()));
} else {
stateBuilder.putSourceMapping(clazz.className(), artifact.name());
}
}
}
if (omitted != null) {
for (Artifact artifact : omitted) {
for (ClassTypeDescriptor classTypeDescriptor : artifact.classes().keySet()) {
stateBuilder.potentialConflictClasses().get().add(classTypeDescriptor);
stateBuilder.sourceMappings().putIfAbsent(classTypeDescriptor, artifact.name());
}
}
}
}
private void checkForBrokenMethodCalls(CheckerState state, Artifact artifact, DeclaredClass clazz,
DeclaredMethod method,
ImmutableList.Builder<Conflict> builder) {
for (CalledMethod calledMethod : method.methodCalls()) {
final ClassTypeDescriptor owningClass = calledMethod.owner();
final DeclaredClass calledClass = state.knownClasses().get(owningClass);
if (!state.potentialConflictClasses().isPresent() || state.potentialConflictClasses().get()
.contains(owningClass)) {
if (calledClass == null) {
builder.add(conflict(ConflictCategory.CLASS_NOT_FOUND,
"Class not found: " + owningClass,
dependency(clazz, method, calledMethod),
artifact.name(),
state.sourceMappings().get(owningClass)
));
} else if (missingMethod(calledMethod.descriptor(), calledClass, state.knownClasses())) {
builder.add(conflict(ConflictCategory.METHOD_SIGNATURE_NOT_FOUND,
"Method not found: " + calledMethod.pretty(),
dependency(clazz, method, calledMethod),
artifact.name(),
state.sourceMappings().get(owningClass)
));
}
}
}
}
private void checkForBrokenFieldAccess(CheckerState state, Artifact artifact, DeclaredClass clazz,
DeclaredMethod method,
ImmutableList.Builder<Conflict> builder) {
for (AccessedField field : method.fieldAccesses()) {
final ClassTypeDescriptor owningClass = field.owner();
final DeclaredClass calledClass = state.knownClasses().get(owningClass);
if (!state.potentialConflictClasses().isPresent() || state.potentialConflictClasses().get()
.contains(owningClass)) {
DeclaredField declaredField = new DeclaredFieldBuilder()
.descriptor(field.descriptor())
.name(field.name())
.build();
if (calledClass == null) {
builder.add(conflict(ConflictCategory.CLASS_NOT_FOUND,
"Class not found: " + owningClass,
dependency(clazz, method, field),
artifact.name(),
state.sourceMappings().get(owningClass)
));
} else if (missingField(declaredField, calledClass, state.knownClasses())) {
builder.add(conflict(ConflictCategory.FIELD_NOT_FOUND,
"Field not found: " + field.name(),
dependency(clazz, method, field),
artifact.name(),
state.sourceMappings().get(owningClass)
));
}
}
}
}
public static ImmutableSet<TypeDescriptor> reachableFrom(
ImmutableCollection<DeclaredClass> values,
Map<ClassTypeDescriptor, DeclaredClass> knownClasses) {
Queue<DeclaredClass> toCheck = new LinkedList<>(values);
Set<ClassTypeDescriptor> reachable = Sets.newHashSet();
while (!toCheck.isEmpty()) {
DeclaredClass current = toCheck.remove();
if (!reachable.add(current.className())) {
continue;
}
toCheck.addAll(current.parents().stream()
.map(knownClasses::get)
.filter(declaredClass -> declaredClass != null)
.collect(toList()));
toCheck.addAll(current.methods().values()
.stream()
.flatMap(declaredMethod -> declaredMethod.methodCalls().stream())
.map(CalledMethod::owner)
.filter(typeDescriptor -> !reachable.contains(typeDescriptor))
.map(knownClasses::get)
.filter(declaredClass -> declaredClass != null)
.collect(toList()));
toCheck.addAll(current.methods().values()
.stream()
.flatMap(declaredMethod -> declaredMethod.fieldAccesses().stream())
.map(AccessedField::owner)
.filter(typeDescriptor -> !reachable.contains(typeDescriptor))
.map(knownClasses::get)
.filter(declaredClass -> declaredClass != null)
.collect(toList()));
}
return ImmutableSet.copyOf(reachable);
}
private Conflict conflict(ConflictCategory category, String reason,
Dependency dependency,
ArtifactName usedBy,
ArtifactName existsIn) {
if (existsIn == null) {
existsIn = UNKNOWN_ARTIFACT_NAME;
}
return new ConflictBuilder()
.category(category)
.dependency(dependency)
.reason(reason)
.usedBy(usedBy)
.existsIn(existsIn)
.build();
}
private Dependency dependency(DeclaredClass clazz, DeclaredMethod method,
CalledMethod calledMethod) {
return new MethodDependencyBuilder()
.fromClass(clazz.className())
.fromMethod(method.descriptor())
.fromLineNumber(calledMethod.lineNumber())
.targetMethod(calledMethod.descriptor())
.targetClass(calledMethod.owner())
.build();
}
private Dependency dependency(DeclaredClass clazz, DeclaredMethod method,
AccessedField field) {
return new FieldDependencyBuilder()
.fromClass(clazz.className())
.fromMethod(method.descriptor())
.fromLineNumber(field.lineNumber())
.targetClass(field.owner())
.fieldType(field.descriptor())
.fieldName(field.name())
.build();
}
private boolean missingMethod(MethodDescriptor descriptor, DeclaredClass calledClass,
Map<ClassTypeDescriptor, DeclaredClass> classMap) {
final DeclaredMethod method = calledClass.methods().get(descriptor);
if (method != null) {
// TODO: also validate return type
return false;
}
// Might be defined in a super class
for (ClassTypeDescriptor parentClass : calledClass.parents()) {
final DeclaredClass declaredClass = classMap.get(parentClass);
// TODO 6/2/15 mbrown -- treat properly, by flagging as a different type of Conflict
// note that declaredClass can only be null not on the first call to this
// method but on the recursive invocations
if (declaredClass == null) {
System.out.printf("Warning: Cannot find parent %s of class %s\n",
parentClass,
calledClass.className());
} else if (!missingMethod(descriptor, declaredClass, classMap)) {
return false;
}
}
return true;
}
private boolean missingField(DeclaredField field, DeclaredClass calledClass,
Map<ClassTypeDescriptor, DeclaredClass> classMap) {
if (calledClass.fields().contains(field)) {
// TODO: also validate return type
return false;
}
// Might be defined in a super class
for (ClassTypeDescriptor parentClass : calledClass.parents()) {
final DeclaredClass declaredClass = classMap.get(parentClass);
// TODO 6/2/15 mbrown -- treat properly, by flagging as a different type of Conflict
if (declaredClass == null) {
System.out.printf("Warning: Cannot find parent %s of class %s\n",
parentClass,
calledClass.className());
} else if (!missingField(field, declaredClass, classMap)) {
return false;
}
}
return true;
}
}
| |
package com.annimon.stream;
import com.annimon.stream.function.BooleanConsumer;
import com.annimon.stream.function.BooleanFunction;
import com.annimon.stream.function.BooleanPredicate;
import com.annimon.stream.function.BooleanSupplier;
import com.annimon.stream.function.Function;
import com.annimon.stream.function.Supplier;
import java.util.NoSuchElementException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A container object which may or may not contain a {@code boolean} value.
*
* @since 1.1.8
* @see Optional
*/
public final class OptionalBoolean {
private static final OptionalBoolean EMPTY = new OptionalBoolean();
private static final OptionalBoolean TRUE = new OptionalBoolean(true);
private static final OptionalBoolean FALSE = new OptionalBoolean(false);
/**
* Returns an empty {@code OptionalBoolean} instance.
*
* @return an empty {@code OptionalBoolean}
*/
@NotNull
public static OptionalBoolean empty() {
return EMPTY;
}
/**
* Returns an {@code OptionalBoolean} with the specified value present.
*
* @param value the value to be present
* @return an {@code OptionalBoolean} with the value present
*/
@NotNull
public static OptionalBoolean of(boolean value) {
return value ? TRUE : FALSE;
}
/**
* Returns an {@code OptionalBoolean} with the specified value, or empty {@code OptionalBoolean} if value is null.
*
* @param value the value which can be null
* @return an {@code OptionalBoolean}
* @since 1.2.1
*/
@NotNull
public static OptionalBoolean ofNullable(@Nullable Boolean value) {
return value == null ? EMPTY : of(value);
}
private final boolean isPresent;
private final boolean value;
private OptionalBoolean() {
this.isPresent = false;
this.value = false;
}
private OptionalBoolean(boolean value) {
this.isPresent = true;
this.value = value;
}
/**
* Returns an inner value if present, otherwise throws {@code NoSuchElementException}.
*
* Since 1.2.0 prefer {@link #orElseThrow()} method as it has readable name.
*
* @return the inner value of this {@code OptionalBoolean}
* @throws NoSuchElementException if there is no value present
* @see OptionalBoolean#isPresent()
* @see #orElseThrow()
*/
public boolean getAsBoolean() {
return orElseThrow();
}
/**
* Checks value present.
*
* @return {@code true} if a value present, {@code false} otherwise
*/
public boolean isPresent() {
return isPresent;
}
/**
* Checks the value is not present.
*
* @return {@code true} if a value is not present, {@code false} otherwise
* @since 1.2.1
*/
public boolean isEmpty() {
return !isPresent;
}
/**
* Invokes consumer function with value if present, otherwise does nothing.
*
* @param consumer the consumer function to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is null
*/
public void ifPresent(@NotNull BooleanConsumer consumer) {
if (isPresent) {
consumer.accept(value);
}
}
/**
* If a value is present, performs the given action with the value,
* otherwise performs the empty-based action.
*
* @param consumer the consumer function to be executed, if a value is present
* @param emptyAction the empty-based action to be performed, if no value is present
* @throws NullPointerException if a value is present and the given consumer function is null,
* or no value is present and the given empty-based action is null.
*/
public void ifPresentOrElse(@NotNull BooleanConsumer consumer, @NotNull Runnable emptyAction) {
if (isPresent) {
consumer.accept(value);
} else {
emptyAction.run();
}
}
/**
* Invokes consumer function with the value if present.
* This method same as {@code ifPresent}, but does not breaks chaining
*
* @param consumer consumer function
* @return this {@code OptionalBoolean}
* @see #ifPresent(BooleanConsumer)
*/
@NotNull
public OptionalBoolean executeIfPresent(@NotNull BooleanConsumer consumer) {
ifPresent(consumer);
return this;
}
/**
* Invokes action function if value is absent.
*
* @param action action that invokes if value absent
* @return this {@code OptionalBoolean}
*/
@NotNull
public OptionalBoolean executeIfAbsent(@NotNull Runnable action) {
if (!isPresent()) {
action.run();
}
return this;
}
/**
* Applies custom operator on {@code OptionalBoolean}.
*
* @param <R> the type of the result
* @param function a transforming function
* @return a result of the transforming function
* @throws NullPointerException if {@code function} is null
* @since 1.1.9
*/
@Nullable
public <R> R custom(@NotNull Function<OptionalBoolean, R> function) {
Objects.requireNonNull(function);
return function.apply(this);
}
/**
* Performs filtering on inner value if it is present.
*
* @param predicate a predicate function
* @return this {@code OptionalBoolean} if the value is present and matches predicate,
* otherwise an empty {@code OptionalBoolean}
*/
@NotNull
public OptionalBoolean filter(@NotNull BooleanPredicate predicate) {
if (!isPresent()) return this;
return predicate.test(value) ? this : OptionalBoolean.empty();
}
/**
* Performs negated filtering on inner value if it is present.
*
* @param predicate a predicate function
* @return this {@code OptionalBoolean} if the value is present and doesn't matches predicate,
* otherwise an empty {@code OptionalBoolean}
* @since 1.1.9
*/
@NotNull
public OptionalBoolean filterNot(@NotNull BooleanPredicate predicate) {
return filter(BooleanPredicate.Util.negate(predicate));
}
/**
* Invokes the given mapping function on inner value if present.
*
* @param mapper mapping function
* @return an {@code OptionalBoolean} with transformed value if present,
* otherwise an empty {@code OptionalBoolean}
* @throws NullPointerException if value is present and
* {@code mapper} is {@code null}
*/
@NotNull
public OptionalBoolean map(@NotNull BooleanPredicate mapper) {
if (!isPresent()) {
return empty();
}
Objects.requireNonNull(mapper);
return OptionalBoolean.of(mapper.test(value));
}
/**
* Invokes the given mapping function on inner value if present.
*
* @param <U> the type of result value
* @param mapper mapping function
* @return an {@code Optional} with transformed value if present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if value is present and
* {@code mapper} is {@code null}
*/
@NotNull
public <U> Optional<U> mapToObj(@NotNull BooleanFunction<U> mapper) {
if (!isPresent()) {
return Optional.empty();
}
Objects.requireNonNull(mapper);
return Optional.ofNullable(mapper.apply(value));
}
/**
* Returns current {@code OptionalBoolean} if value is present, otherwise
* returns an {@code OptionalBoolean} produced by supplier function.
*
* @param supplier supplier function that produces an {@code OptionalBoolean} to be returned
* @return this {@code OptionalBoolean} if value is present, otherwise
* an {@code OptionalBoolean} produced by supplier function
* @throws NullPointerException if value is not present and
* {@code supplier} or value produced by it is {@code null}
*/
@NotNull
public OptionalBoolean or(@NotNull Supplier<OptionalBoolean> supplier) {
if (isPresent()) return this;
Objects.requireNonNull(supplier);
return Objects.requireNonNull(supplier.get());
}
/**
* Returns inner value if present, otherwise returns {@code other}.
*
* @param other the value to be returned if there is no value present
* @return the value, if present, otherwise {@code other}
*/
public boolean orElse(boolean other) {
return isPresent ? value : other;
}
/**
* Returns the value if present, otherwise returns value produced by supplier function.
*
* @param other supplier function that produces value if inner value is not present
* @return the value if present otherwise the result of {@code other.getAsBoolean()}
* @throws NullPointerException if value is not present and {@code other} is null
*/
public boolean orElseGet(@NotNull BooleanSupplier other) {
return isPresent ? value : other.getAsBoolean();
}
/**
* Returns inner value if present, otherwise throws {@code NoSuchElementException}.
*
* @return inner value if present
* @throws NoSuchElementException if inner value is not present
* @since 1.2.0
*/
public boolean orElseThrow() {
if (!isPresent) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* Returns the value if present, otherwise throws an exception provided by supplier function.
*
* @param <X> the type of exception to be thrown
* @param exceptionSupplier supplier function that produces an exception to be thrown
* @return inner value if present
* @throws X if inner value is not present
*/
public <X extends Throwable> boolean orElseThrow(@NotNull Supplier<X> exceptionSupplier) throws X {
if (isPresent) {
return value;
} else {
throw exceptionSupplier.get();
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof OptionalBoolean)) {
return false;
}
OptionalBoolean other = (OptionalBoolean) obj;
return (isPresent && other.isPresent)
? value == other.value
: isPresent == other.isPresent;
}
@Override
public int hashCode() {
return isPresent ? (value ? 1231 : 1237) : 0;
}
@NotNull
@Override
public String toString() {
return isPresent
? (value ? "OptionalBoolean[true]" : "OptionalBoolean[false]")
: "OptionalBoolean.empty";
}
}
| |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.dogecoin.protocols.channels;
import com.google.dogecoin.core.*;
import com.google.dogecoin.store.WalletProtobufSerializer;
import com.google.dogecoin.utils.TestWithWallet;
import com.google.dogecoin.utils.Threading;
import com.google.dogecoin.wallet.WalletFiles;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
import org.bitcoin.paymentchannel.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.dogecoin.protocols.channels.PaymentChannelCloseException.CloseReason;
import static com.google.dogecoin.utils.TestUtils.createFakeBlock;
import static org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage.MessageType;
import static org.junit.Assert.*;
public class ChannelConnectionTest extends TestWithWallet {
private Wallet serverWallet;
private BlockChain serverChain;
private AtomicBoolean fail;
private BlockingQueue<Transaction> broadcasts;
private TransactionBroadcaster mockBroadcaster;
private Semaphore broadcastTxPause;
private static final TransactionBroadcaster failBroadcaster = new TransactionBroadcaster() {
@Override
public ListenableFuture<Transaction> broadcastTransaction(Transaction tx) {
fail();
return null;
}
};
@Before
public void setUp() throws Exception {
super.setUp();
Utils.setMockClock(); // Use mock clock
sendMoneyToWallet(Utils.COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
sendMoneyToWallet(Utils.COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster));
serverWallet = new Wallet(params);
serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster));
serverWallet.addKey(new ECKey());
serverChain = new BlockChain(params, serverWallet, blockStore);
// Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads
fail = new AtomicBoolean(false);
// Set up a way to monitor broadcast transactions. When you expect a broadcast, you must release a permit
// to the broadcastTxPause semaphore so state can be queried in between.
broadcasts = new LinkedBlockingQueue<Transaction>();
broadcastTxPause = new Semaphore(0);
mockBroadcaster = new TransactionBroadcaster() {
@Override
public ListenableFuture<Transaction> broadcastTransaction(Transaction tx) {
broadcastTxPause.acquireUninterruptibly();
SettableFuture<Transaction> future = SettableFuture.create();
future.set(tx);
broadcasts.add(tx);
return future;
}
};
// Because there are no separate threads in the tests here (we call back into client/server in server/client
// handlers), we have lots of lock cycles. A normal user shouldn't have this issue as they are probably not both
// client+server running in the same thread.
Threading.warnOnLockCycles();
ECKey.FAKE_SIGNATURES = true;
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
ECKey.FAKE_SIGNATURES = false;
}
@After
public void checkFail() {
assertFalse(fail.get());
Threading.throwOnLockCycles();
}
@Test
public void testSimpleChannel() throws Exception {
// Test with network code and without any issues. We'll broadcast two txns: multisig contract and settle transaction.
final SettableFuture<ListenableFuture<PaymentChannelServerState>> serverCloseFuture = SettableFuture.create();
final SettableFuture<Sha256Hash> channelOpenFuture = SettableFuture.create();
final BlockingQueue<BigInteger> q = new LinkedBlockingQueue<BigInteger>();
final PaymentChannelServerListener server = new PaymentChannelServerListener(mockBroadcaster, serverWallet, 30, Utils.COIN,
new PaymentChannelServerListener.HandlerFactory() {
@Nullable
@Override
public ServerConnectionEventHandler onNewConnection(SocketAddress clientAddress) {
return new ServerConnectionEventHandler() {
@Override
public void channelOpen(Sha256Hash channelId) {
channelOpenFuture.set(channelId);
}
@Override
public void paymentIncrease(BigInteger by, BigInteger to) {
q.add(to);
}
@Override
public void channelClosed(CloseReason reason) {
serverCloseFuture.set(null);
}
};
}
});
server.bindAndStart(4243);
PaymentChannelClientConnection client = new PaymentChannelClientConnection(
new InetSocketAddress("localhost", 4243), 30, wallet, myKey, Utils.COIN, "");
// Wait for the multi-sig tx to be transmitted.
broadcastTxPause.release();
Transaction broadcastMultiSig = broadcasts.take();
// Wait for the channel to finish opening.
client.getChannelOpenFuture().get();
assertEquals(broadcastMultiSig.getHash(), channelOpenFuture.get());
assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE, client.state().getValueSpent());
// Set up an autosave listener to make sure the server is saving the wallet after each payment increase.
final CountDownLatch latch = new CountDownLatch(3); // Expect 3 calls.
File tempFile = File.createTempFile("channel_connection_test", ".wallet");
tempFile.deleteOnExit();
serverWallet.autosaveToFile(tempFile, 0, TimeUnit.SECONDS, new WalletFiles.Listener() {
@Override
public void onBeforeAutoSave(File tempFile) {
latch.countDown();
}
@Override
public void onAfterAutoSave(File newlySavedFile) {
}
});
Thread.sleep(1250); // No timeouts once the channel is open
BigInteger amount = client.state().getValueSpent();
assertEquals(amount, q.take());
client.incrementPayment(Utils.CENT).get();
amount = amount.add(Utils.CENT);
assertEquals(amount, q.take());
client.incrementPayment(Utils.CENT).get();
amount = amount.add(Utils.CENT);
assertEquals(amount, q.take());
client.incrementPayment(Utils.CENT).get();
amount = amount.add(Utils.CENT);
assertEquals(amount, q.take());
latch.await();
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)serverWallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
StoredServerChannel storedServerChannel = channels.getChannel(broadcastMultiSig.getHash());
PaymentChannelServerState serverState = storedServerChannel.getOrCreateState(serverWallet, mockBroadcaster);
// Check that you can call settle multiple times with no exceptions.
client.settle();
client.settle();
broadcastTxPause.release();
Transaction settleTx = broadcasts.take();
assertEquals(PaymentChannelServerState.State.CLOSED, serverState.getState());
if (!serverState.getBestValueToMe().equals(amount) || !serverState.getFeePaid().equals(BigInteger.ZERO))
fail();
assertTrue(channels.mapChannels.isEmpty());
// Send the settle TX to the client wallet.
sendMoneyToWallet(settleTx, AbstractBlockChain.NewBlockType.BEST_CHAIN);
assertEquals(PaymentChannelClientState.State.CLOSED, client.state().getState());
server.close();
server.close();
// Now confirm the settle TX and see if the channel deletes itself from the wallet.
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(0, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
@Test
public void testServerErrorHandling() throws Exception {
// Gives the server crap and checks proper error responses are sent.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
PaymentChannelServer server = pair.server;
server.connectionOpen();
client.connectionOpen();
// Make sure we get back a BAD_TRANSACTION if we send a bogus refund transaction.
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.PROVIDE_REFUND)
.setProvideRefund(
Protos.ProvideRefund.newBuilder(msg.getProvideRefund())
.setMultisigKey(ByteString.EMPTY)
.setTx(ByteString.EMPTY)
).build());
final Protos.TwoWayChannelMessage errorMsg = pair.serverRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.BAD_TRANSACTION, errorMsg.getError().getCode());
// Make sure the server closes the socket on CLOSE
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.settle();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.CLIENT_REQUESTED_CLOSE, pair.serverRecorder.q.take());
// Make sure the server closes the socket on ERROR
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.ERROR)
.setError(Protos.Error.newBuilder().setCode(Protos.Error.ErrorCode.TIMEOUT))
.build());
assertEquals(CloseReason.REMOTE_SENT_ERROR, pair.serverRecorder.q.take());
}
@Test
public void testChannelResume() throws Exception {
// Tests various aspects of channel resuming.
Utils.setMockClock();
final Sha256Hash someServerId = Sha256Hash.create(new byte[]{});
// Open up a normal channel.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
final Protos.TwoWayChannelMessage initiateMsg = pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
BigInteger minPayment = BigInteger.valueOf(initiateMsg.getInitiate().getMinPayment());
client.receiveMessage(initiateMsg);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
assertEquals(minPayment, client.state().getValueSpent());
// Send a bitcent.
BigInteger amount = minPayment.add(Utils.CENT);
client.incrementPayment(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
assertEquals(amount, pair.serverRecorder.q.take());
server.close();
server.connectionClosed();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
client.connectionClosed();
assertFalse(client.connectionOpen);
// There is now an inactive open channel worth COIN-CENT + minPayment with id Sha256.create(new byte[] {})
StoredPaymentChannelClientStates clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
assertEquals(1, clientStoredChannels.mapChannels.size());
assertFalse(clientStoredChannels.mapChannels.values().iterator().next().active);
// Check that server-side won't attempt to reopen a nonexistent channel (it will tell the client to re-initiate
// instead).
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
pair.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(Sha256Hash.create(new byte[]{0x03}).getBytes()))
.setMajor(1).setMinor(42))
.build());
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
// Now reopen/resume the channel after round-tripping the wallets.
wallet = roundTripClientWallet(wallet);
serverWallet = roundTripServerWallet(serverWallet);
clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check the contract hash is sent on the wire correctly.
final Protos.TwoWayChannelMessage clientVersionMsg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertTrue(clientVersionMsg.getClientVersion().hasPreviousChannelContractHash());
assertEquals(contractHash, new Sha256Hash(clientVersionMsg.getClientVersion().getPreviousChannelContractHash().toByteArray()));
server.receiveMessage(clientVersionMsg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
assertEquals(contractHash, pair.serverRecorder.q.take());
pair.clientRecorder.checkOpened();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send another bitcent and check 2 were received in total.
client.incrementPayment(Utils.CENT);
amount = amount.add(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.checkTotalPayment(amount);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
PaymentChannelClient openClient = client;
ChannelTestUtils.RecordingPair openPair = pair;
// Now open up a new client with the same id and make sure the server disconnects the previous client.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check that no prev contract hash is sent on the wire the client notices it's already in use by another
// client attached to the same wallet and refuses to resume.
{
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
// Make sure the server allows two simultaneous opens. It will close the first and allow resumption of the second.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Swap out the clients version message for a custom one that tries to resume ...
pair.clientRecorder.getNextMsg();
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(contractHash.getBytes()))
.setMajor(1).setMinor(42))
.build());
// We get the usual resume sequence.
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN);
// Verify the previous one was closed.
openPair.serverRecorder.checkNextMsg(MessageType.CLOSE);
assertTrue(clientStoredChannels.getChannel(someServerId, contractHash).active);
// And finally close the first channel too.
openClient.connectionClosed();
assertFalse(clientStoredChannels.getChannel(someServerId, contractHash).active);
// Now roll the mock clock and recreate the client object so that it removes the channels and announces refunds.
assertEquals(86640, clientStoredChannels.getSecondsUntilExpiry(someServerId));
Utils.rollMockClock(60 * 60 * 24 + 60 * 5); // Client announces refund 5 minutes after expire time
StoredPaymentChannelClientStates newClientStates = new StoredPaymentChannelClientStates(wallet, mockBroadcaster);
newClientStates.deserializeWalletExtension(wallet, clientStoredChannels.serializeWalletExtension());
broadcastTxPause.release();
assertTrue(broadcasts.take().getOutput(0).getScriptPubKey().isSentToMultiSig());
broadcastTxPause.release();
assertEquals(TransactionConfidence.Source.SELF, broadcasts.take().getConfidence().getSource());
assertTrue(broadcasts.isEmpty());
assertTrue(newClientStates.mapChannels.isEmpty());
// Server also knows it's too late.
StoredPaymentChannelServerStates serverStoredChannels = new StoredPaymentChannelServerStates(serverWallet, mockBroadcaster);
Thread.sleep(2000); // TODO: Fix this stupid hack.
assertTrue(serverStoredChannels.mapChannels.isEmpty());
}
private static Wallet roundTripClientWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
Wallet wallet2 = new Wallet(wallet.getParams());
wallet2.addExtension(new StoredPaymentChannelClientStates(wallet2, failBroadcaster));
new WalletProtobufSerializer().readWallet(WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray())), wallet2);
return wallet2;
}
private static Wallet roundTripServerWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
Wallet wallet2 = new Wallet(wallet.getParams());
wallet2.addExtension(new StoredPaymentChannelServerStates(wallet2, failBroadcaster));
new WalletProtobufSerializer().readWallet(WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray())), wallet2);
return wallet2;
}
@Test
public void testBadResumeHash() throws InterruptedException {
// Check that server-side will reject incorrectly formatted hashes. If anything goes wrong with session resume,
// then the server will start the opening of a new channel automatically, so we expect to see INITIATE here.
ChannelTestUtils.RecordingPair srv =
ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
srv.server.connectionOpen();
srv.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(new byte[]{0x00, 0x01}))
.setMajor(1).setMinor(42))
.build());
srv.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
srv.serverRecorder.checkNextMsg(MessageType.INITIATE);
assertTrue(srv.serverRecorder.q.isEmpty());
}
@Test
public void testClientUnknownVersion() throws Exception {
// Tests client rejects unknown version
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setServerVersion(Protos.ServerVersion.newBuilder().setMajor(2))
.setType(MessageType.SERVER_VERSION).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.NO_ACCEPTABLE_VERSION, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(BigInteger.ONE);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testClientTimeWindowTooLarge() throws Exception {
// Tests that clients reject too large time windows
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds() + 60 * 60 * 48)
.setMinAcceptedChannelSize(100)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.longValue()))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.TIME_WINDOW_TOO_LARGE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(BigInteger.ONE);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testValuesAreRespected() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(Utils.COIN.add(BigInteger.ONE).longValue())
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.longValue()))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.SERVER_REQUESTED_TOO_MUCH_VALUE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(BigInteger.ONE);
fail();
} catch (IllegalStateException e) { }
// Now check that if the server has a lower min size than what we are willing to spend, we do actually open
// a channel of that size.
sendMoneyToWallet(Utils.COIN.multiply(BigInteger.TEN), AbstractBlockChain.NewBlockType.BEST_CHAIN);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
server = pair.server;
final BigInteger myValue = Utils.COIN.multiply(BigInteger.TEN);
client = new PaymentChannelClient(wallet, myKey, myValue, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(Utils.COIN.add(BigInteger.ONE).longValue())
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.longValue()))
.setType(MessageType.INITIATE).build());
final Protos.TwoWayChannelMessage provideRefund = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
Transaction refund = new Transaction(params, provideRefund.getProvideRefund().getTx().toByteArray());
assertEquals(myValue, refund.getOutput(0).getValue());
}
@Test
public void testEmptyWallet() throws Exception {
Wallet emptyWallet = new Wallet(params);
emptyWallet.addKey(new ECKey());
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(emptyWallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
try {
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(Utils.CENT.longValue())
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.longValue()))
.setType(MessageType.INITIATE).build());
fail();
} catch (InsufficientMoneyException expected) {
// This should be thrown.
}
}
@Test
public void testClientResumeNothing() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CHANNEL_OPEN).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testClientRandomMessage() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
// Send a CLIENT_VERSION back to the client - ?!?!!
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION).build());
Protos.TwoWayChannelMessage error = pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.SYNTAX_ERROR, error.getError().getCode());
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testDontResumeEmptyChannels() throws Exception {
// Check that if the client has an empty channel that's being kept around in case we need to broadcast the
// refund, we don't accidentally try to resume it).
// Open up a normal channel.
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send the whole channel at once. The server will broadcast the final contract and settle the channel for us.
client.incrementPayment(client.state().getValueRefunded());
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
broadcasts.take();
// The channel is now empty.
assertEquals(BigInteger.ZERO, client.state().getValueRefunded());
pair.serverRecorder.q.take(); // Take the BigInteger.
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.SERVER_REQUESTED_CLOSE, pair.clientRecorder.q.take());
client.connectionClosed();
// Now try opening a new channel with the same server ID and verify the client asks for a new channel.
client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
client.connectionOpen();
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
@Test
public void repeatedChannels() throws Exception {
// Ensures we're selecting channels correctly. Covers a bug in which we'd always try and fail to resume
// the first channel due to lack of proper closing behaviour.
// Open up a normal channel, but don't spend all of it, then settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
ListenableFuture<BigInteger> future = client.incrementPayment(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.q.take();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
assertTrue(future.isDone());
client.incrementPayment(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.q.take();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.incrementPayment(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.q.take();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
// Settle it and verify it's considered to be settled.
broadcastTxPause.release();
client.settle();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
Transaction settlement1 = broadcasts.take();
// Server sends back the settle TX it just broadcast.
final Protos.TwoWayChannelMessage closeMsg = pair.serverRecorder.checkNextMsg(MessageType.CLOSE);
final Transaction settlement2 = new Transaction(params, closeMsg.getSettlement().getTx().toByteArray());
assertEquals(settlement1, settlement2);
client.receiveMessage(closeMsg);
assertNotNull(wallet.getTransaction(settlement2.getHash())); // Close TX entered the wallet.
sendMoneyToWallet(settlement1, AbstractBlockChain.NewBlockType.BEST_CHAIN);
client.connectionClosed();
server.connectionClosed();
}
// Now open a second channel and don't spend all of it/don't settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
final Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
server.receiveMessage(msg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
client.incrementPayment(Utils.CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
client.connectionClosed();
server.connectionClosed();
}
// Now connect again and check we resume the second channel.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, Utils.COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
}
assertEquals(2, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
}
| |
package com.lenox.beyondj.services.hazelcast;
import com.hazelcast.core.EntryEvent;
import com.lenox.beyond.InstallationResponse;
import com.lenox.beyond.LaunchUtil;
import com.lenox.beyond.configuration.Config;
import com.lenox.beyond.launch.ApplicationOptions;
import com.lenox.beyondj.actor.ApplicationConfiguration;
import com.lenox.beyondj.ha.install.HazelcastInstallationDelegate;
import com.lenox.beyondj.ha.install.HazelcastInstallationRequestListener;
import com.lenox.beyondj.ha.install.InstallCallback;
import com.lenox.beyondj.services.ApplicationLaunchService;
import com.lenox.common.IBeyondJInstallationService;
import com.lenox.common.util.ChecksumUtils;
import com.lenox.common.util.IpAddresssUtil;
import com.lenox.platform.DeploymentStatus;
import com.lenox.platform.DeploymentType;
import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
public class BeyondJHazelcastInstallationService implements InstallCallback, IBeyondJInstallationService {
@Autowired
private HazelcastInstallationRequestListener installationRequestListener;
@Autowired
private HazelcastInstallationDelegate installationDelegate;
@Autowired
private ApplicationLaunchService applicationLaunchService;
@Autowired
private Config config;
@PostConstruct
private void decorate() {
installationRequestListener.addInstallCallback(this);
}
@Override
public void install(ApplicationOptions options){
Validate.notNull(options, "options must not be null");
String serversCommaSeparated = options.getServersCommaSeparated();
if (serversCommaSeparated != null && serversCommaSeparated.length() > 0) {
String localAddress = IpAddresssUtil.getLocalHostAddress();
serversCommaSeparated = serversCommaSeparated.trim();
if (!serversCommaSeparated.contains(localAddress)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Skipping installation as local ip address {} is not specified " +
"in 'serversCommaSeparated' in {}", localAddress, options);
return;
}
}
}
InstallationResponse response = new InstallationResponse();
response.setApplicationOptions(options);
response.setNodeIdentifier(installationRequestListener.getLocalEndpoint());
DateTime dateTime = new DateTime();
final GregorianCalendar calendar = new GregorianCalendar(dateTime.getZone().toTimeZone());
calendar.setTimeInMillis(dateTime.getMillis());
response.setInstallTime(new XMLGregorianCalendarImpl(calendar));
//download the files here
downloadDeploymentFile(options);
downloadConfigurationFile(options);
int index = options.getInstallationOriginUriForConfigurationFile().lastIndexOf("/");
String fileName = options.getInstallationOriginUriForConfigurationFile().substring(index + 1);
try {
extractFile(options.getDeploymentFile(), options.getDeploymentType());
List<String> files = new ArrayList<>();
files.add(fileName);
applicationLaunchService.launchApplications(BeyondJHazelcastInstallationService.class, files, installationDelegate.getLocalEndpoint());
response.setDeploymentStatus(DeploymentStatus.COMPLETED);
} catch (Exception e) {
LOG.error("Failed to install", e);
response.setDeploymentStatus(DeploymentStatus.FAILED);
}
installationDelegate.respond(response);
}
@Override
public void entryAdded(Object o) {
theEntryAdded((EntryEvent<String, ApplicationOptions>)o);
}
@Override
public void entryEvicted(Object o) {
}
@Override
public void entryRemoved(Object o) {
}
@Override
public void entryUpdated(Object o) {
theEntryAdded((EntryEvent<String, ApplicationOptions>)o);
}
@Override
public void mapCleared(Object o) {
}
@Override
public void mapEvicted(Object o) {
}
@Override
public String getProviderName() {
return null;
}
private void theEntryAdded(EntryEvent<String, ApplicationOptions> entryEvent) {
ApplicationOptions options = entryEvent.getValue();
install(options);
}
private void extractFile(String fileName, DeploymentType deploymentType) throws Exception {
String path = LaunchUtil.getContainerInstallationDir(config);
if (deploymentType == DeploymentType.SERVLET_CONTAINER) {
if (LOG.isDebugEnabled()) LOG.debug("Extracting web-app resources to install folder");
String webAppsPath = path + File.separator + ApplicationConfiguration.LAUNCHERS + File.separator
+ ApplicationConfiguration.WEB_APP_LAUNCHERS;
String destJName = webAppsPath + File.separator + fileName.replace(".jar", "");
destJName = destJName.replace(".war", "");
LaunchUtil.extractJar(webAppsPath + File.separator + fileName, destJName);
LaunchUtil.extractZip(webAppsPath + File.separator + fileName, webAppsPath + File.separator + fileName.replace(".zip", ""));
LaunchUtil.extractTar(webAppsPath + File.separator + fileName);
}
//----------------------------------------
if (deploymentType == DeploymentType.JAVA_PROCESS_VIA_JAR) {
String jarAppsPath = path + File.separator + ApplicationConfiguration.LAUNCHERS + File.separator
+ ApplicationConfiguration.JAR_APP_LAUNCHERS;
if (LOG.isDebugEnabled()) LOG.debug("Extracting jar-app resources to install folder");
String destJName = jarAppsPath + File.separator + fileName.replace(".jar", "");
destJName = destJName.replace(".tar", "");
LaunchUtil.extractJar(jarAppsPath + File.separator + fileName, destJName);
LaunchUtil.extractZip(jarAppsPath + File.separator + fileName, jarAppsPath + File.separator + fileName.replace(".zip", ""));
LaunchUtil.extractTar(jarAppsPath + File.separator + fileName);
}
//----------------------------------------
if (deploymentType == DeploymentType.JAVA_PROCESS_VIA_SKRIPT) {
String scriptAppsPath = path + File.separator + ApplicationConfiguration.LAUNCHERS + File.separator
+ ApplicationConfiguration.SCRIPT_APP_LAUNCHERS;
if (LOG.isDebugEnabled()) LOG.debug("Extracting script-app resources to install folder");
String destJName = scriptAppsPath + File.separator + fileName.replace(".jar", "");
destJName = destJName.replace(".tar", "");
LaunchUtil.extractJar(scriptAppsPath + File.separator + fileName, destJName);
LaunchUtil.extractZip(scriptAppsPath + File.separator + fileName, scriptAppsPath + File.separator + fileName.replace(".zip", ""));
LaunchUtil.extractTar(scriptAppsPath + File.separator + fileName);
}
}
private void downloadConfigurationFile(ApplicationOptions options) {
String installDirStr = LaunchUtil.getContainerInstallationDir(config) + File.separator + LAUNCHERS
+ File.separator + CONFIG;
if (StringUtils.isNotBlank(options.getInstallationOriginUriForConfigurationFile())) {
int index = options.getInstallationOriginUriForConfigurationFile().lastIndexOf("/");
String fileName = options.getInstallationOriginUriForConfigurationFile().substring(index + 1);
File savedConfigFile = new File(installDirStr + File.separator + fileName);
boolean checksumDiffers = false;
if (savedConfigFile.exists() && options.getDeploymentFileChecksum() != -1) {
try {
long checksum = ChecksumUtils.checksum(new FileInputStream(savedConfigFile));
if (options.getDeploymentFileChecksum() != checksum) {
checksumDiffers = true;
}
} catch (Exception e) {
LOG.error(String.format("Download Failed for : %s", options.getInstallationOriginUriForConfigurationFile()), e);
}
}
if (!savedConfigFile.exists() || checksumDiffers) {
if (LOG.isDebugEnabled())
LOG.debug("Downloading {}", options.getInstallationOriginUriForConfigurationFile());
HttpClient httpClient = new HttpClient();
HttpMethod method = new GetMethod(options.getInstallationOriginUriForConfigurationFile());
int httpCode;
try {
httpCode = httpClient.executeMethod(method);
if (httpCode == 200) {
FileOutputStream fileOutputStream = new FileOutputStream(installDirStr + File.separator + options.getDeploymentFile());
byte[] responseBody = method.getResponseBody();
fileOutputStream.write(responseBody);
fileOutputStream.close();
} else {
LOG.error(String.format("Download Failed for Config File: %s. Response code is %d", options.getInstallationOriginUriForConfigurationFile(), httpCode));
}
} catch (Exception e) {
LOG.error(String.format("Download Failed for Config File: %s", options.getInstallationOriginUriForConfigurationFile()), e);
} finally {
method.releaseConnection();
}
}
}
}
private void downloadDeploymentFile(ApplicationOptions options) {
String installDirStr = null;
if (options.getDeploymentType() == DeploymentType.SERVLET_CONTAINER) {
installDirStr = LaunchUtil.getContainerInstallationDir(config) + File.separator + LAUNCHERS +
File.separator + WEBAPP_LAUNCHERS;
} else if (options.getDeploymentType() == DeploymentType.JAVA_PROCESS_VIA_JAR) {
installDirStr = LaunchUtil.getContainerInstallationDir(config) + File.separator + LAUNCHERS +
File.separator + JAR_LAUNCHERS;
} else if (options.getDeploymentType() == DeploymentType.JAVA_PROCESS_VIA_SKRIPT) {
installDirStr = LaunchUtil.getContainerInstallationDir(config) + File.separator + LAUNCHERS +
File.separator + SCRIPT_LAUNCHERS;
}
File deploymentFile = new File(installDirStr + File.separator + options.getDeploymentFile());
boolean checksumDiffers = false;
if (deploymentFile.exists() && options.getDeploymentFileChecksum() != -1) {
try {
long checksum = ChecksumUtils.checksum(new FileInputStream(deploymentFile));
if (options.getDeploymentFileChecksum() != checksum) {
checksumDiffers = true;
}
} catch (Exception e) {
LOG.error(String.format("Download Failed for Deployment File: %s", options.getInstallationOriginUriForDeploymentFile()), e);
}
}
if (!deploymentFile.exists() || checksumDiffers) {
if (LOG.isDebugEnabled()) LOG.debug("Downloading {}", options.getInstallationOriginUriForDeploymentFile());
HttpClient httpClient = new HttpClient();
HttpMethod method = new GetMethod(options.getInstallationOriginUriForDeploymentFile());
int httpCode;
try {
httpCode = httpClient.executeMethod(method);
if (httpCode == 200) {
FileOutputStream fileOutputStream = new FileOutputStream(installDirStr + File.separator + options.getDeploymentFile());
byte[] responseBody = method.getResponseBody();
fileOutputStream.write(responseBody);
fileOutputStream.close();
} else {
LOG.error(String.format("Download Failed for Deployment File: %s. Response code is %d", options.getInstallationOriginUriForDeploymentFile(), httpCode));
}
} catch (Exception e) {
LOG.error(String.format("Download Failed for Deployment File: %s", options.getInstallationOriginUriForDeploymentFile()), e);
} finally {
method.releaseConnection();
}
}
}
public HazelcastInstallationRequestListener getInstallationRequestListener() {
return installationRequestListener;
}
public HazelcastInstallationDelegate getInstallationDelegate() {
return installationDelegate;
}
public ApplicationLaunchService getApplicationLaunchService() {
return applicationLaunchService;
}
public static final String WEBAPP_LAUNCHERS = "webapp-launchers";
public static final String JAR_LAUNCHERS = "jar-launchers";
public static final String SCRIPT_LAUNCHERS = "script-launchers";
public static final String LAUNCHERS = "launchers";
public static final String CONFIG = "config";
private static final Logger LOG = LoggerFactory.getLogger(BeyondJHazelcastInstallationService.class);
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.controller;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.ServiceManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.google.inject.persist.PersistModule;
import com.google.inject.persist.jpa.AmbariJpaPersistModule;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ambari.server.AmbariService;
import org.apache.ambari.server.EagerSingleton;
import org.apache.ambari.server.StaticallyInject;
import org.apache.ambari.server.actionmanager.*;
import org.apache.ambari.server.checks.AbstractCheckDescriptor;
import org.apache.ambari.server.checks.UpgradeCheckRegistry;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.configuration.Configuration.ConnectionPoolType;
import org.apache.ambari.server.configuration.Configuration.DatabaseType;
import org.apache.ambari.server.controller.internal.*;
import org.apache.ambari.server.controller.spi.ResourceProvider;
import org.apache.ambari.server.controller.utilities.DatabaseChecker;
import org.apache.ambari.server.notifications.DispatchFactory;
import org.apache.ambari.server.notifications.NotificationDispatcher;
import org.apache.ambari.server.orm.DBAccessor;
import org.apache.ambari.server.orm.DBAccessorImpl;
import org.apache.ambari.server.orm.PersistenceType;
import org.apache.ambari.server.scheduler.ExecutionScheduler;
import org.apache.ambari.server.scheduler.ExecutionSchedulerImpl;
import org.apache.ambari.server.security.SecurityHelper;
import org.apache.ambari.server.security.SecurityHelperImpl;
import org.apache.ambari.server.security.encryption.CredentialStoreService;
import org.apache.ambari.server.security.encryption.CredentialStoreServiceImpl;
import org.apache.ambari.server.serveraction.kerberos.KerberosOperationHandlerFactory;
import org.apache.ambari.server.stack.StackManagerFactory;
import org.apache.ambari.server.stageplanner.RoleGraphFactory;
import org.apache.ambari.server.stageplanner.RoleGraphFactoryImpl;
import org.apache.ambari.server.state.*;
import org.apache.ambari.server.state.cluster.ClusterFactory;
import org.apache.ambari.server.state.cluster.ClusterImpl;
import org.apache.ambari.server.state.cluster.ClustersImpl;
import org.apache.ambari.server.state.configgroup.ConfigGroup;
import org.apache.ambari.server.state.configgroup.ConfigGroupFactory;
import org.apache.ambari.server.state.configgroup.ConfigGroupImpl;
import org.apache.ambari.server.state.host.HostFactory;
import org.apache.ambari.server.state.host.HostImpl;
import org.apache.ambari.server.state.kerberos.KerberosDescriptorFactory;
import org.apache.ambari.server.state.kerberos.KerberosServiceDescriptorFactory;
import org.apache.ambari.server.state.scheduler.RequestExecution;
import org.apache.ambari.server.state.scheduler.RequestExecutionFactory;
import org.apache.ambari.server.state.scheduler.RequestExecutionImpl;
import org.apache.ambari.server.state.stack.OsFamily;
import org.apache.ambari.server.state.svccomphost.ServiceComponentHostImpl;
import org.apache.ambari.server.topology.BlueprintFactory;
import org.apache.ambari.server.view.ViewInstanceHandlerList;
import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.SessionManager;
import org.eclipse.jetty.server.session.HashSessionIdManager;
import org.eclipse.jetty.server.session.HashSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.util.ClassUtils;
import org.springframework.web.filter.DelegatingFilterProxy;
import java.beans.PropertyVetoException;
import java.lang.annotation.Annotation;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.*;
import java.util.Map.Entry;
import static org.eclipse.persistence.config.PersistenceUnitProperties.*;
/**
* Used for injection purposes.
*/
public class ControllerModule extends AbstractModule
{
private static Logger LOG = LoggerFactory
.getLogger(ControllerModule.class);
private static final String AMBARI_PACKAGE = "org.apache.ambari.server";
private final Configuration configuration;
private final OsFamily os_family;
private final HostsMap hostsMap;
private boolean dbInitNeeded;
private final Gson prettyGson = new GsonBuilder().serializeNulls()
.setPrettyPrinting()
.create();
// ----- Constructors ------------------------------------------------------
public ControllerModule() throws Exception {
configuration = new Configuration();
hostsMap = new HostsMap(configuration);
os_family = new OsFamily(configuration);
}
public ControllerModule(Properties properties) throws Exception {
configuration = new Configuration(properties);
hostsMap = new HostsMap(configuration);
os_family = new OsFamily(configuration);
}
// ----- ControllerModule --------------------------------------------------
/**
* Get the common persistence related configuration properties.
*
* @return the configuration properties
*/
public static Properties getPersistenceProperties(
Configuration configuration) {
Properties properties = new Properties();
// log what database type has been calculated
DatabaseType databaseType = configuration.getDatabaseType();
LOG.info("Detected {} as the database type from the JDBC URL", databaseType);
// custom jdbc properties
Map<String, String> customProperties = configuration
.getDatabaseCustomProperties();
if (0 != customProperties.size())
{
for (Entry<String, String> entry : customProperties.entrySet())
{
properties.setProperty("eclipselink.jdbc.property." +
entry.getKey(), entry.getValue());
}
}
switch (configuration.getPersistenceType())
{
case IN_MEMORY:
properties
.setProperty(JDBC_URL, Configuration.JDBC_IN_MEMORY_URL);
properties
.setProperty(JDBC_DRIVER, Configuration.JDBC_IN_MEMROY_DRIVER);
properties.setProperty(DDL_GENERATION, DROP_AND_CREATE);
properties.setProperty(THROW_EXCEPTIONS, "true");
case REMOTE:
properties.setProperty(JDBC_URL, configuration
.getDatabaseUrl());
properties.setProperty(JDBC_DRIVER, configuration
.getDatabaseDriver());
break;
case LOCAL:
properties.setProperty(JDBC_URL, configuration
.getLocalDatabaseUrl());
properties
.setProperty(JDBC_DRIVER, Configuration.JDBC_LOCAL_DRIVER);
break;
}
// determine the type of pool to use
boolean isConnectionPoolingExternal = false;
ConnectionPoolType connectionPoolType = configuration
.getConnectionPoolType();
if (connectionPoolType == ConnectionPoolType.C3P0)
{
isConnectionPoolingExternal = true;
}
// force the use of c3p0 with MySQL
if (databaseType == DatabaseType.MYSQL)
{
isConnectionPoolingExternal = true;
}
// use c3p0
if (isConnectionPoolingExternal)
{
LOG.info("Using c3p0 {} as the EclipsLink DataSource", ComboPooledDataSource.class
.getSimpleName());
// Oracle requires a different validity query
String testQuery = "SELECT 1";
if (databaseType == DatabaseType.ORACLE)
{
testQuery = "SELECT 1 FROM DUAL";
}
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// attempt to load the driver; if this fails, warn and move on
try
{
dataSource
.setDriverClass(configuration.getDatabaseDriver());
}
catch (PropertyVetoException pve)
{
LOG.warn("Unable to initialize c3p0", pve);
return properties;
}
// basic configuration stuff
dataSource.setJdbcUrl(configuration.getDatabaseUrl());
dataSource.setUser(configuration.getDatabaseUser());
dataSource.setPassword(configuration.getDatabasePassword());
// pooling
dataSource.setMinPoolSize(configuration
.getConnectionPoolMinimumSize());
dataSource.setInitialPoolSize(configuration
.getConnectionPoolMinimumSize());
dataSource.setMaxPoolSize(configuration
.getConnectionPoolMaximumSize());
dataSource.setAcquireIncrement(configuration
.getConnectionPoolAcquisitionSize());
dataSource.setAcquireRetryAttempts(configuration
.getConnectionPoolAcquisitionRetryAttempts());
dataSource.setAcquireRetryDelay(configuration
.getConnectionPoolAcquisitionRetryDelay());
// validity
dataSource.setMaxConnectionAge(configuration
.getConnectionPoolMaximumAge());
dataSource.setMaxIdleTime(configuration
.getConnectionPoolMaximumIdle());
dataSource.setMaxIdleTimeExcessConnections(configuration
.getConnectionPoolMaximumExcessIdle());
dataSource.setPreferredTestQuery(testQuery);
dataSource.setIdleConnectionTestPeriod(configuration
.getConnectionPoolIdleTestInternval());
properties.put(NON_JTA_DATASOURCE, dataSource);
}
return properties;
}
// ----- AbstractModule ----------------------------------------------------
@Override
protected void configure() {
installFactories();
final SessionIdManager sessionIdManager = new HashSessionIdManager();
final SessionManager sessionManager = new HashSessionManager();
sessionManager.getSessionCookieConfig().setPath("/");
sessionManager.setSessionIdManager(sessionIdManager);
bind(SessionManager.class).toInstance(sessionManager);
bind(SessionIdManager.class).toInstance(sessionIdManager);
bind(KerberosOperationHandlerFactory.class);
bind(KerberosDescriptorFactory.class);
bind(KerberosServiceDescriptorFactory.class);
bind(KerberosHelper.class).to(KerberosHelperImpl.class);
bind(CredentialStoreService.class)
.to(CredentialStoreServiceImpl.class);
bind(Configuration.class).toInstance(configuration);
bind(OsFamily.class).toInstance(os_family);
bind(HostsMap.class).toInstance(hostsMap);
bind(PasswordEncoder.class)
.toInstance(new StandardPasswordEncoder());
bind(DelegatingFilterProxy.class)
.toInstance(new DelegatingFilterProxy()
{
{
setTargetBeanName("springSecurityFilterChain");
}
});
bind(Gson.class).annotatedWith(Names.named("prettyGson"))
.toInstance(prettyGson);
install(buildJpaPersistModule());
bind(Gson.class).in(Scopes.SINGLETON);
bind(SecureRandom.class).in(Scopes.SINGLETON);
bind(Clusters.class).to(ClustersImpl.class);
bind(AmbariCustomCommandExecutionHelper.class);
bind(ActionDBAccessor.class).to(ActionDBAccessorImpl.class);
bindConstant().annotatedWith(Names.named("schedulerSleeptime"))
.to(1000L);
// This time is added to summary timeout time of all tasks in stage
// So it's an "additional time", given to stage to finish execution before
// it is considered as timed out
bindConstant().annotatedWith(Names.named("actionTimeout"))
.to(600000L);
bindConstant().annotatedWith(Names.named("dbInitNeeded"))
.to(dbInitNeeded);
bindConstant().annotatedWith(Names.named("statusCheckInterval"))
.to(5000L);
//ExecutionCommands cache size
bindConstant()
.annotatedWith(Names.named("executionCommandCacheSize")).
to(configuration.getExecutionCommandsCacheSize());
bind(AmbariManagementController.class)
.to(AmbariManagementControllerImpl.class);
bind(AbstractRootServiceResponseFactory.class)
.to(RootServiceResponseFactory.class);
bind(ExecutionScheduler.class).to(ExecutionSchedulerImpl.class);
bind(DBAccessor.class).to(DBAccessorImpl.class);
bind(ViewInstanceHandlerList.class).to(AmbariHandlerList.class);
// bind(TimelineMetricCacheProvider.class);
// bind(TimelineMetricCacheEntryFactory.class);
requestStaticInjection(ExecutionCommandWrapper.class);
requestStaticInjection(DatabaseChecker.class);
bindByAnnotation(null);
bindNotificationDispatchers();
registerUpgradeChecks();
}
// ----- helper methods ----------------------------------------------------
private PersistModule buildJpaPersistModule() {
PersistenceType persistenceType = configuration
.getPersistenceType();
AmbariJpaPersistModule jpaPersistModule = new AmbariJpaPersistModule(Configuration.JDBC_UNIT_NAME);
Properties persistenceProperties = ControllerModule
.getPersistenceProperties(configuration);
if (!persistenceType.equals(PersistenceType.IN_MEMORY))
{
persistenceProperties.setProperty(JDBC_USER, configuration
.getDatabaseUser());
persistenceProperties.setProperty(JDBC_PASSWORD, configuration
.getDatabasePassword());
switch (configuration.getJPATableGenerationStrategy())
{
case CREATE:
persistenceProperties
.setProperty(DDL_GENERATION, CREATE_ONLY);
dbInitNeeded = true;
break;
case DROP_AND_CREATE:
persistenceProperties
.setProperty(DDL_GENERATION, DROP_AND_CREATE);
dbInitNeeded = true;
break;
case CREATE_OR_EXTEND:
persistenceProperties
.setProperty(DDL_GENERATION, CREATE_OR_EXTEND);
break;
default:
break;
}
persistenceProperties
.setProperty(DDL_GENERATION_MODE, DDL_BOTH_GENERATION);
persistenceProperties
.setProperty(CREATE_JDBC_DDL_FILE, "DDL-create.jdbc");
persistenceProperties
.setProperty(DROP_JDBC_DDL_FILE, "DDL-drop.jdbc");
}
jpaPersistModule.properties(persistenceProperties);
return jpaPersistModule;
}
/**
* Bind classes to their Factories, which can be built on-the-fly.
* Often, will also have to edit AgentResourceTest.java
*/
private void installFactories() {
install(new FactoryModuleBuilder()
.implement(Cluster.class, ClusterImpl.class)
.build(ClusterFactory.class));
install(new FactoryModuleBuilder()
.implement(Host.class, HostImpl.class)
.build(HostFactory.class));
install(new FactoryModuleBuilder()
.implement(Service.class, ServiceImpl.class)
.build(ServiceFactory.class));
install(new FactoryModuleBuilder()
.implement(ResourceProvider.class, Names
.named("host"), HostResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("hostComponent"), HostComponentResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("service"), ServiceResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("component"), ComponentResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("member"), MemberResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("repositoryVersion"), RepositoryVersionResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("hostKerberosIdentity"), HostKerberosIdentityResourceProvider.class)
.implement(ResourceProvider.class, Names
.named("credential"), CredentialResourceProvider.class)
.build(ResourceProviderFactory.class));
install(new FactoryModuleBuilder()
.implement(ServiceComponent.class, ServiceComponentImpl.class)
.build(ServiceComponentFactory.class));
install(new FactoryModuleBuilder()
.implement(ServiceComponentHost.class, ServiceComponentHostImpl.class)
.build(ServiceComponentHostFactory.class));
install(new FactoryModuleBuilder()
.implement(Config.class, ConfigImpl.class)
.build(ConfigFactory.class));
install(new FactoryModuleBuilder()
.implement(ConfigGroup.class, ConfigGroupImpl.class)
.build(ConfigGroupFactory.class));
install(new FactoryModuleBuilder()
.implement(RequestExecution.class, RequestExecutionImpl.class)
.build(RequestExecutionFactory.class));
bind(StageFactory.class).to(StageFactoryImpl.class);
bind(RoleGraphFactory.class).to(RoleGraphFactoryImpl.class);
install(new FactoryModuleBuilder().build(RequestFactory.class));
install(new FactoryModuleBuilder()
.build(StackManagerFactory.class));
bind(HostRoleCommandFactory.class)
.to(HostRoleCommandFactoryImpl.class);
bind(SecurityHelper.class)
.toInstance(SecurityHelperImpl.getInstance());
bind(BlueprintFactory.class);
}
/**
* Initializes specially-marked interfaces that require injection.
* <p/>
* An example of where this is needed is with a singleton that is headless; in
* other words, it doesn't have any injections but still needs to be part of
* the Guice framework.
* <p/>
* A second example of where this is needed is when classes require static
* members that are available via injection.
* <p/>
* If {@code beanDefinitions} is empty or null this will scan
* {@code org.apache.ambari.server} (currently) for any {@link EagerSingleton}
* or {@link StaticallyInject} or {@link AmbariService} instances.
*
* @param beanDefinitions the set of bean definitions. If it is empty or
* {@code null} scan will occur.
*
* @return the set of bean definitions that was found during scan if
* {@code beanDefinitions} was null or empty. Else original
* {@code beanDefinitions} will be returned.
*
*/
// Method is protected and returns a set of bean definitions for testing convenience.
@SuppressWarnings("unchecked")
protected Set<BeanDefinition> bindByAnnotation(
Set<BeanDefinition> beanDefinitions) {
List<Class<? extends Annotation>> classes = Arrays
.asList(EagerSingleton.class, StaticallyInject.class, AmbariService.class);
if (null == beanDefinitions || beanDefinitions.size() == 0)
{
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
// match only singletons that are eager listeners
for (Class<? extends Annotation> cls : classes)
{
scanner.addIncludeFilter(new AnnotationTypeFilter(cls));
}
beanDefinitions = scanner
.findCandidateComponents(AMBARI_PACKAGE);
}
if (null == beanDefinitions || beanDefinitions.size() == 0)
{
LOG.warn("No instances of {} found to register", classes);
return beanDefinitions;
}
Set<com.google.common.util.concurrent.Service> services = new HashSet<com.google.common.util.concurrent.Service>();
for (BeanDefinition beanDefinition : beanDefinitions)
{
String className = beanDefinition.getBeanClassName();
Class<?> clazz = ClassUtils
.resolveClassName(className, ClassUtils
.getDefaultClassLoader());
if (null != clazz.getAnnotation(EagerSingleton.class))
{
bind(clazz).asEagerSingleton();
LOG.debug("Binding singleton {} eagerly", clazz);
}
if (null != clazz.getAnnotation(StaticallyInject.class))
{
requestStaticInjection(clazz);
LOG.debug("Statically injecting {} ", clazz);
}
// Ambari services are registered with Guava
if (null != clazz.getAnnotation(AmbariService.class))
{
// safety check to ensure it's actually a Guava service
if (!AbstractScheduledService.class
.isAssignableFrom(clazz))
{
String message = MessageFormat
.format("Unable to register service {0} because it is not an AbstractScheduledService", clazz);
LOG.warn(message);
throw new RuntimeException(message);
}
// instantiate the service, register as singleton via toInstance()
AbstractScheduledService service = null;
try
{
service = (AbstractScheduledService) clazz
.newInstance();
bind((Class<AbstractScheduledService>) clazz)
.toInstance(service);
services.add(service);
LOG.debug("Registering service {} ", clazz);
}
catch (Exception exception)
{
LOG.error("Unable to register {} as a service", clazz, exception);
throw new RuntimeException(exception);
}
}
}
ServiceManager manager = new ServiceManager(services);
bind(ServiceManager.class).toInstance(manager);
return beanDefinitions;
}
/**
* Searches for all instances of {@link NotificationDispatcher} on the
* classpath and registers each as a singleton with the
* {@link DispatchFactory}.
*/
@SuppressWarnings("unchecked")
private void bindNotificationDispatchers() {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
// make the factory a singleton
DispatchFactory dispatchFactory = DispatchFactory.getInstance();
bind(DispatchFactory.class).toInstance(dispatchFactory);
// match all implementations of the dispatcher interface
AssignableTypeFilter filter = new AssignableTypeFilter(NotificationDispatcher.class);
scanner.addIncludeFilter(filter);
Set<BeanDefinition> beanDefinitions = scanner
.findCandidateComponents("org.apache.ambari.server.notifications.dispatchers");
// no dispatchers is a problem
if (null == beanDefinitions || beanDefinitions.size() == 0)
{
LOG.error("No instances of {} found to register", NotificationDispatcher.class);
return;
}
// for every discovered dispatcher, singleton-ize them and register with
// the dispatch factory
for (BeanDefinition beanDefinition : beanDefinitions)
{
String className = beanDefinition.getBeanClassName();
Class<?> clazz = ClassUtils
.resolveClassName(className, ClassUtils
.getDefaultClassLoader());
try
{
NotificationDispatcher dispatcher = (NotificationDispatcher) clazz
.newInstance();
dispatchFactory.register(dispatcher.getType(), dispatcher);
bind((Class<NotificationDispatcher>) clazz)
.toInstance(dispatcher);
LOG.info("Binding and registering notification dispatcher {}", clazz);
}
catch (Exception exception)
{
LOG.error("Unable to bind and register notification dispatcher {}", clazz, exception);
}
}
}
/**
* Searches for all instances of {@link AbstractCheckDescriptor} on the
* classpath and registers each as a singleton with the
* {@link UpgradeCheckRegistry}.
*/
@SuppressWarnings("unchecked")
private void registerUpgradeChecks() {
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
// make the registry a singleton
UpgradeCheckRegistry registry = new UpgradeCheckRegistry();
bind(UpgradeCheckRegistry.class).toInstance(registry);
// match all implementations of the base check class
AssignableTypeFilter filter = new AssignableTypeFilter(AbstractCheckDescriptor.class);
scanner.addIncludeFilter(filter);
Set<BeanDefinition> beanDefinitions = scanner
.findCandidateComponents(AMBARI_PACKAGE);
// no dispatchers is a problem
if (null == beanDefinitions || beanDefinitions.size() == 0)
{
LOG.error("No instances of {} found to register", AbstractCheckDescriptor.class);
return;
}
// for every discovered check, singleton-ize them and register with the
// registry
for (BeanDefinition beanDefinition : beanDefinitions)
{
String className = beanDefinition.getBeanClassName();
Class<?> clazz = ClassUtils
.resolveClassName(className, ClassUtils
.getDefaultClassLoader());
try
{
AbstractCheckDescriptor upgradeCheck = (AbstractCheckDescriptor) clazz
.newInstance();
bind((Class<AbstractCheckDescriptor>) clazz)
.toInstance(upgradeCheck);
registry.register(upgradeCheck);
}
catch (Exception exception)
{
LOG.error("Unable to bind and register upgrade check {}", clazz, exception);
}
}
// log the order of the pre-upgrade checks
List<AbstractCheckDescriptor> upgradeChecks = registry
.getUpgradeChecks();
for (AbstractCheckDescriptor upgradeCheck : upgradeChecks)
{
LOG.debug("Registered pre-upgrade check {}", upgradeCheck
.getClass());
}
}
}
| |
/*******************************************************************************
* Copyright 2012 University of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.er.helper;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.isi.karma.modeling.Uris;
import edu.isi.karma.util.HTTPUtil;
import edu.isi.karma.webserver.KarmaException;
import edu.isi.karma.webserver.ServletContextParameterMap;
public class TripleStoreUtil {
private static Logger logger = LoggerFactory
.getLogger(TripleStoreUtil.class);
public static final String defaultServerUrl;
public static final String defaultModelsRepoUrl;
public static final String defaultDataRepoUrl;
public static final String defaultWorkbenchUrl;
public static final String karma_model_repo = "karma_models";
public static final String karma_data_repo = "karma_data";
static {
String host = ServletContextParameterMap
.getParameterValue(ServletContextParameterMap.ContextParameter.JETTY_HOST);
String port = ServletContextParameterMap
.getParameterValue(ServletContextParameterMap.ContextParameter.JETTY_PORT);
final String baseURL = host + ":" + port + "/openrdf-sesame";
defaultServerUrl = baseURL + "/repositories";
defaultModelsRepoUrl = defaultServerUrl + "/karma_models";
defaultDataRepoUrl = defaultServerUrl + "/karma_data";
defaultWorkbenchUrl = host + ":" + port
+ "/openrdf-workbench/repositories";
}
protected static HashMap<String, String> mime_types;
public enum RDF_Types {
TriG, BinaryRDF, TriX, N_Triples, N_Quads, N3, RDF_XML, RDF_JSON, Turtle
}
static {
initialize();
mime_types = new HashMap<String, String>();
mime_types.put(RDF_Types.TriG.name(), "application/x-trig");
mime_types.put(RDF_Types.BinaryRDF.name(), "application/x-binary-rdf");
mime_types.put(RDF_Types.TriX.name(), "application/trix");
mime_types.put(RDF_Types.N_Triples.name(), "text/plain");
mime_types.put(RDF_Types.N_Quads.name(), "text/x-nquads");
mime_types.put(RDF_Types.N3.name(), "text/rdf+n3");
mime_types.put(RDF_Types.Turtle.name(), "application/x-turtle");
mime_types.put(RDF_Types.RDF_XML.name(), "application/rdf+xml");
mime_types.put(RDF_Types.RDF_JSON.name(), "application/rdf+json");
}
/**
* This method check for the default karma repositories in the local server
* If not, it creates them
* */
public static boolean initialize() {
boolean retVal = false;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
List<String> repositories = new ArrayList<String>();
try {
// query the list of repositories
httpget = new HttpGet(defaultServerUrl);
httpget.setHeader("Accept",
"application/sparql-results+json, */*;q=0.5");
response = httpclient.execute(httpget);
entity = response.getEntity();
if (entity != null) {
BufferedReader buf = new BufferedReader(new InputStreamReader(
entity.getContent()));
String s = buf.readLine();
StringBuffer line = new StringBuffer();
while (s != null) {
line.append(s);
s = buf.readLine();
}
JSONObject data = new JSONObject(line.toString());
JSONArray repoList = data.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < repoList.length()) {
JSONObject obj = repoList.getJSONObject(count++);
repositories
.add(obj.optJSONObject("id").optString("value"));
}
// check for karama_models repo
if (!repositories.contains(karma_model_repo)) {
logger.info("karma_models not found");
if (create_repo(karma_model_repo,
"Karma default model repository", "native")) {
retVal = true;
} else {
logger.error("Could not create repository : "
+ karma_model_repo);
retVal = false;
}
}
// check for karama_data repo
if (!repositories.contains(karma_data_repo)) {
logger.info("karma_data not found");
if (create_repo(karma_data_repo,
"Karma default data repository", "native")) {
retVal = true;
} else {
logger.error("Could not create repository : "
+ karma_data_repo);
retVal = false;
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return retVal;
}
public static boolean checkConnection(String url) {
boolean retval = false;
try {
if (url.charAt(url.length() - 1) != '/') {
url = url + "/";
}
url = url + "size";
logger.info(url);
String response = HTTPUtil.executeHTTPGetRequest(url, null);
try {
int i = Integer.parseInt(response.trim());
logger.debug("Connnection to repo : " + url
+ " Successful.\t Size : " + i);
retval = true;
} catch (Exception e) {
logger.error("Could not parse size of repository query result.");
}
} catch (Exception e) {
e.printStackTrace();
}
return retval;
}
public boolean testURIExists(String tripleStoreURL, String context, String uri)
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
try {
testTripleStoreConnection(tripleStoreURL);
} catch (KarmaException e1) {
return false;
}
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#> ASK ");
injectContext(context, query);
query.append(" { { ");
formatURI(uri,query);
query.append(" ?y ?z .} union { ?x ?y ");
formatURI(uri,query);
query.append(" } } ");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject askResult = new JSONObject(responseString);
return askResult.getBoolean("boolean");
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return false;
}
public Map<String, List<String>> getObjectsForSubjectsAndPredicates(String tripleStoreURL, String context, List<String> subjects, List<String> predicates, List<String> otherClasses, String sameAsProperty) throws KarmaException
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
Map<String, List<String>> results = new HashMap<String,List<String>>();
List<String> resultSubjects = new LinkedList<String>();
List<String> resultPredicates = new LinkedList<String>();
List<String> resultObjects = new LinkedList<String>();
List<String> resultClasses = new LinkedList<String>();
results.put("resultSubjects", resultSubjects);
results.put("resultPredicates", resultPredicates);
results.put("resultObjects", resultObjects);
results.put("resultClasses", resultClasses);
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
query.append("SELECT ?s ?p ?o ?filteredtype\n");
injectContext(context, query);
query.append("{\n");
query.append("VALUES ?s { ");
for(String subject : subjects)
{
formatURI(subject, query);
query.append(" ");
}
query.append("}\n");
Iterator<String> predicateIterator = predicates.iterator();
Iterator<String> otherClassIterator = otherClasses.iterator();
String predicate;
String otherClass;
while(predicateIterator.hasNext() && otherClassIterator.hasNext())
{
query.append("{\n");
predicate = predicateIterator.next();
otherClass = otherClassIterator.next();
if(!otherClass.trim().isEmpty())
{
query.append("BIND ( ");
formatURI(otherClass, query);
query.append(" AS ?filteredtype )\n");
}
query.append("BIND ( ");
formatURI(predicate, query);
query.append(" AS ?p )\n");
query.append("{\n");
query.append("?s ");
formatURI(predicate, query);
query.append(" ?o .\n");
query.append("}\n");
if(sameAsProperty != null && !sameAsProperty.isEmpty())
{
query.append("UNION\n");
query.append("{\n");
query.append("?s ");
formatURI(sameAsProperty, query);
query.append("?sprime .\n");
query.append("?sprime ");
formatURI(predicate, query);
query.append(" ?o .\n");
query.append("}\n");
query.append("UNION\n");
query.append("{\n");
query.append("?sprime ");
formatURI(sameAsProperty, query);
query.append("?s .\n");
query.append("?sprime ");
formatURI(predicate, query);
query.append(" ?o .\n");
query.append("}\n");
}
if(!otherClass.trim().isEmpty())
{
query.append("?o a ?filteredtype .\n");
}
query.append("}\n");
if(predicateIterator.hasNext() && otherClassIterator.hasNext())
{
query.append("UNION \n");
}
}
query.append("}\n");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
resultSubjects.add(o.getJSONObject("s").getString("value"));
resultPredicates.add(o.getJSONObject("p").getString("value"));
resultObjects.add(o.getJSONObject("o").getString("value"));
if(o.has("filteredtype"))
{
resultClasses.add(o.getJSONObject("filteredtype").getString("value"));
}
else
{
resultClasses.add("");
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return results;
}
public Map<String, List<String>> getSubjectsForPredicatesAndObjects(String tripleStoreURL, String context, List<String> subjects, List<String> predicates, List<String> otherClasses, String sameAsPredicate) throws KarmaException
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
Map<String, List<String>> results = new HashMap<String,List<String>>();
List<String> resultSubjects = new LinkedList<String>();
List<String> resultPredicates = new LinkedList<String>();
List<String> resultObjects = new LinkedList<String>();
List<String> resultClasses = new LinkedList<String>();
results.put("resultSubjects", resultSubjects);
results.put("resultPredicates", resultPredicates);
results.put("resultObjects", resultObjects);
results.put("resultClasses", resultClasses);
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
query.append("SELECT ?s ?p ?o ?filteredtype\n");
injectContext(context, query);
query.append("{\n");
query.append("VALUES ?o { ");
for(String subject : subjects)
{
formatURI(subject, query);
query.append(" ");
}
query.append("}\n");
Iterator<String> predicateIterator = predicates.iterator();
Iterator<String> otherClassIterator = otherClasses.iterator();
String predicate;
String otherClass;
while(predicateIterator.hasNext() && otherClassIterator.hasNext())
{
query.append("{\n");
predicate = predicateIterator.next();
otherClass = otherClassIterator.next();
query.append("BIND ( ");
formatURI(predicate, query);
query.append(" AS ?p )\n");
if(!otherClass.trim().isEmpty())
{
query.append("BIND ( ");
formatURI(otherClass, query);
query.append(" AS ?filteredtype )\n");
}
query.append("{\n");
query.append("?s ?p ?o .\n");
query.append("}\n");
if(sameAsPredicate != null && !sameAsPredicate.isEmpty())
{
query.append("UNION \n");
query.append("{\n");
query.append("?oprime ");
query.append(sameAsPredicate);
query.append(" ?o .\n");
query.append("?s ?p ?oprime .\n");
query.append("}\n");
query.append("UNION \n");
query.append("{\n");
query.append("?o ");
query.append(sameAsPredicate);
query.append(" ?oprime .\n");
query.append("?s ?p ?oprime .\n");
query.append("}\n");
}
if(!otherClass.trim().isEmpty())
{
query.append("?s a ?filteredtype .\n");
}
query.append("}\n");
if(predicateIterator.hasNext() && otherClassIterator.hasNext())
{
query.append("UNION \n");
}
}
query.append("}\n");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
resultSubjects.add(o.getJSONObject("s").getString("value"));
resultPredicates.add(o.getJSONObject("p").getString("value"));
resultObjects.add(o.getJSONObject("o").getString("value"));
if(o.has("filteredtype"))
{
resultClasses.add(o.getJSONObject("filteredtype").getString("value"));
}
else
{
resultClasses.add("");
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return results;
}
public void deleteMappingFromTripleStore(String tripleStoreURL, String context, String mappingURI) throws KarmaException
{
testTripleStoreConnection(tripleStoreURL);
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL) + "/statements";
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
if (null != context && !context.trim().isEmpty())
{
query.append("WITH ");
formatURI(context, query);
query.append("\n");
}
query.append("DELETE { ?s ?p ?o } \n");
query.append("WHERE\n");
injectMapping(mappingURI, query);
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("update", queryString);
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, mime_types.get(RDF_Types.N3.name()),
formparams);
System.out.println(responseString);
} catch (Exception e) {
logger.error(e.getMessage());
}
}
protected void injectMapping(String mappingURI, StringBuilder query) {
query.append("{\n");
injectType(mappingURI, query, Uris.RR_TRIPLESMAP_CLASS_URI, Uris.KM_HAS_TRIPLES_MAP_URI);
injectType(mappingURI, query, Uris.RR_SUBJECTMAP_CLASS_URI, Uris.KM_HAS_SUBJECT_MAP_URI);
injectType(mappingURI, query, Uris.RR_PREDICATEOBJECTMAP_CLASS_URI, Uris.KM_HAS_PREDICATE_OBJECT_MAP_URI);
injectType(mappingURI, query, Uris.RR_OBJECTMAP_CLASS_URI, Uris.KM_HAS_OBJECT_MAP_URI);
injectType(mappingURI, query, Uris.RR_LOGICAL_TABLE_CLASS_URI, Uris.KM_HAS_LOGICAL_TABLE_URI);
injectType(mappingURI, query, Uris.RR_TEMPLATE_URI, Uris.RR_CLASS_URI, Uris.KM_HAS_SUBJECT_MAP_URI);
query.append("{\n");
query.append("?s ?p ?o .\n");
query.append("?s owl:sameAs ");
formatURI(mappingURI, query);
query.append(" . \n");
query.append("}\n");
query.append("}\n");
}
protected void injectType(String mappingURI, StringBuilder query,
String type, String hasType) {
query.append("{\n");
query.append("?s a <");
query.append(type);
query.append("> . \n");
query.append("?mapping <");
query.append(hasType);
query.append("> ?s . \n");
query.append("?mapping owl:sameAs ");
formatURI(mappingURI, query);
query.append(" .\n");
query.append("?s ?p ?o . \n");
query.append("}\n");
query.append("UNION\n");
}
protected void injectType(String mappingURI, StringBuilder query,
String type, String hasType, String hasType2) {
query.append("{\n");
query.append("?s <");
query.append(type);
query.append("> ?a . \n");
query.append("?mapping2 <");
query.append(hasType);
query.append("> ?s . \n");
query.append("?mapping <");
query.append(hasType2);
query.append("> ?mapping2 . \n");
query.append("?mapping owl:sameAs ");
formatURI(mappingURI, query);
query.append(" .\n");
query.append("?s ?p ?o . \n");
query.append("}\n");
query.append("UNION\n");
}
public String getMappingFromTripleStore(String tripleStoreURL, String context, String mappingURI) throws KarmaException
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
context = normalizeURI(context);
mappingURI = normalizeURI(mappingURI);
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
query.append("CONSTRUCT { ?s ?p ?o }\n");
injectContext(context, query);
injectMapping(mappingURI, query);
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, mime_types.get(RDF_Types.N3.name()),
formparams);
if (responseString != null) {
return responseString;
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return "";
}
protected void injectContext(String context, StringBuilder query) {
if (null != context && !context.trim().isEmpty())
{
query.append("FROM ");
formatURI(context, query);
query.append("\n");
}
}
protected void formatURI(String uri, StringBuilder query) {
uri = uri.trim();
if(!uri.startsWith("<"))
{
query.append("<");
}
query.append(uri);
if(!uri.endsWith(">"))
{
query.append(">");
}
}
public HashMap<String, List<String>> getPredicatesForParentTriplesMapsWithSameClass(String tripleStoreURL, String context, Collection<String> classesToMatch) throws KarmaException
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
List<String> predicates = new LinkedList<String>();
List<String> matchingRefObjMaps = new LinkedList<String>();
List<String> otherClasses = new LinkedList<String>();
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
query.append("SELECT ?predicate ?otherClass (group_concat(?refObjMap; separator = \",\") as ?refObjMaps )\n");
injectContext(context, query);
query.append("{\n");
query.append("?mapping owl:sameAs ?mappingURI . \n");
// query.append("?mappingURI km-dev:hasData \"true\" .\n");
query.append("?mapping km-dev:hasTriplesMap ?triplesMap .\n");
query.append("?triplesMap rr:subjectMap ?subjectMap .\n");
Iterator<String> itr = classesToMatch.iterator();
while(itr.hasNext()) {
String classToMatch = itr.next();
query.append("{?subjectMap rr:class ");
query.append("<").append(classToMatch.trim()).append(">");
query.append("}");
if (itr.hasNext())
query.append(" UNION \n");
else
query.append(". \n");
}
query.append("?refObjMap rr:parentTriplesMap ?triplesMap .\n");
query.append("?pom rr:objectMap ?refObjMap .\n");
query.append("?otherTriplesMap rr:predicateObjectMap ?pom .\n");
query.append("?otherTriplesMap rr:subjectMap ?otherSubjectMap .\n");
query.append("?otherSubjectMap rr:class ?otherClass .\n");
query.append("FILTER NOT EXISTS { ?otherClass rr:template ?z }\n");
query.append("?pom rr:predicate ?predicate .\n");
query.append("}\n");
query.append("GROUP BY ?predicate ?otherClass\n");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
predicates.add(o.getJSONObject("predicate").getString("value"));
matchingRefObjMaps.add(o.getJSONObject("refObjMaps").getString("value"));
if(o.has("otherClass"))
{
otherClasses.add(o.getJSONObject("otherClass").getString("value"));
}
else
{
otherClasses.add("");
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
HashMap<String, List<String>> values = new HashMap<String, List<String>>();
values.put("predicates", predicates);
values.put("refObjectMaps", matchingRefObjMaps);
values.put("otherClasses", otherClasses);
return values;
}
public HashMap<String, List<String>> getPredicatesForTriplesMapsWithSameClass(String tripleStoreURL, String context, Collection<String> classesToMatch) throws KarmaException
{
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
List<String> predicates = new LinkedList<String>();
List<String> matchingPOMs = new LinkedList<String>();
List<String> otherClasses = new LinkedList<String>();
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("PREFIX rr:<http://www.w3.org/ns/r2rml#>\n");
query.append("SELECT ?predicate ?otherClass (group_concat(?pom; separator = \",\") as ?poms )\n");
injectContext(context, query);
query.append("{\n");
query.append("?mapping owl:sameAs ?mappingURI . \n");
// query.append("?mappingURI km-dev:hasData \"true\" .\n");
query.append("?mapping km-dev:hasTriplesMap ?triplesMap .\n");
query.append("?triplesMap rr:subjectMap ?subjectMap .\n");
Iterator<String> itr = classesToMatch.iterator();
while (itr.hasNext()) {
String classToMatch = itr.next();
query.append("{?subjectMap rr:class ");
query.append("<").append(classToMatch.trim()).append(">");
query.append("}");
if (itr.hasNext())
query.append(" UNION \n");
else
query.append(". \n");
}
query.append("?triplesMap rr:predicateObjectMap ?pom . \n");
query.append("?pom rr:predicate ?predicate . \n");
query.append("OPTIONAL \n");
query.append("{\n");
query.append("?pom rr:objectMap ?objectMap .\n");
query.append("?objectMap rr:parentTriplesMap ?parentTriplesMap .\n");
query.append("?parentTriplesMap rr:subjectMap ?otherSubjectMap .\n");
query.append("?otherSubjectMap rr:class ?otherClass .\n");
query.append("}\n}\n");
query.append("GROUP BY ?predicate ?otherClass\n");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
tripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
predicates.add(o.getJSONObject("predicate").getString("value"));
matchingPOMs.add(o.getJSONObject("poms").getString("value"));
if(o.has("otherClass"))
{
otherClasses.add(o.getJSONObject("otherClass").getString("value"));
}
else
{
otherClasses.add("");
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
HashMap<String, List<String>> values = new HashMap<String, List<String>>();
values.put("predicates", predicates);
values.put("predicateObjectMaps", matchingPOMs);
values.put("otherClasses", otherClasses);
return values;
}
public void testTripleStoreConnection(String tripleStoreURL)
throws KarmaException {
// check the connection first
if (checkConnection(tripleStoreURL)) {
logger.info("Connection Test passed");
} else {
logger.info("Failed connection test : " + tripleStoreURL);
throw new KarmaException("Failed connect test : " + tripleStoreURL);
}
}
protected String normalizeTripleStoreURL(String tripleStoreURL) {
if (tripleStoreURL == null || tripleStoreURL.isEmpty()) {
tripleStoreURL = defaultServerUrl + "/" + karma_model_repo + "/" + "statements";
}
if (tripleStoreURL.charAt(tripleStoreURL.length() - 1) == '/') {
tripleStoreURL = tripleStoreURL.substring(0,
tripleStoreURL.length() - 2);
}
logger.info("Repository URL : " + tripleStoreURL);
return tripleStoreURL;
}
/**
* This method fetches all the source names of the models from the triple
* store
*
* @param TripleStoreURL
* : the triple store URL
* */
public HashMap<String, List<String>> getMappingsWithMetadata(String TripleStoreURL, String context) throws KarmaException {
TripleStoreURL = normalizeTripleStoreURL(TripleStoreURL);
testTripleStoreConnection(TripleStoreURL);
List<String> times = new ArrayList<String>();
List<String> names = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
List<String> inputColumns = new ArrayList<String>();
List<String> contexts = new ArrayList<String>();
try {
StringBuilder query = new StringBuilder();
query.append("PREFIX km-dev:<http://isi.edu/integration/karma/dev#>\n");
query.append("SELECT ?z ?y ?x ?src ?w ?u\n");
injectContext(context, query);
query.append("WHERE \n { \n");
query.append("GRAPH ?src \n { \n");
query.append("?a km-dev:sourceName ?u . \n");
query.append("?a a km-dev:R2RMLMapping . \n");
query.append("?a owl:sameAs ?z . \n");
query.append("?a km-dev:modelPublicationTime ?x \n");
query.append("OPTIONAL \n{?a km-dev:hasInputColumns ?w} \n");
query.append("OPTIONAL \n{?a km-dev:hasModelLabel ?y} \n");
query.append("\n}\n} \nORDER BY ?z ?y ?x ?w ?u ?src");
String queryString = query.toString();
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
TripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
times.add(o.getJSONObject("x").getString("value"));
urls.add(o.getJSONObject("z").getString("value"));
if (o.has("w"))
inputColumns.add(o.getJSONObject("w").getString("value"));
else
inputColumns.add("");
if (o.has("y"))
names.add(o.getJSONObject("y").getString("value"));
else
names.add(o.getJSONObject("u").getString("value"));
contexts.add(o.getJSONObject("src").getString("value"));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
HashMap<String, List<String>> values = new HashMap<String, List<String>>();
values.put("model_publishtimes", times);
values.put("model_names", names);
values.put("model_urls", urls);
values.put("model_contexts", contexts);
values.put("model_inputcolumns", inputColumns);
return values;
}
/**
* This method fetches all the source names of the models from the triple
* store
*
* @param TripleStoreURL
* : the triple store URL
* */
public HashMap<String, List<String>> fetchModelNames(String TripleStoreURL) throws KarmaException {
List<String> names = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
TripleStoreURL = normalizeTripleStoreURL(TripleStoreURL);
testTripleStoreConnection(TripleStoreURL);
try {
String queryString = "PREFIX km-dev:<http://isi.edu/integration/karma/dev#> SELECT ?y ?z where { ?x km-dev:sourceName ?y . ?x km-dev:serviceUrl ?z . } ORDER BY ?y ?z";
logger.debug("query: " + queryString);
Map<String, String> formparams = new HashMap<String, String>();
formparams.put("query", queryString);
formparams.put("queryLn", "SPARQL");
String responseString = HTTPUtil.executeHTTPPostRequest(
TripleStoreURL, null, "application/sparql-results+json",
formparams);
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
names.add(o.getJSONObject("y").getString("value"));
urls.add(o.getJSONObject("z").getString("value"));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
HashMap<String, List<String>> values = new HashMap<String, List<String>>();
values.put("model_names", names);
values.put("model_urls", urls);
return values;
}
/**
* @param filePath
* : the url of the file from where the RDF is read
* @param tripleStoreURL
* : the triple store URL
* @param context
* : The graph context for the RDF
* @param replaceFlag
* : Whether to replace the contents of the graph
* @param deleteSrcFile
* : Whether to delete the source R2RML file or not
* @param rdfType
* : The RDF type based on which the headers for the request are
* set
* @param baseURL
* : Specifies the base URI to resolve any relative URIs found in uploaded data against
*
* */
protected boolean saveToStore(HttpEntity entity, String tripleStoreURL,
String context, boolean replaceFlag,
String rdfType, String baseURL) throws KarmaException {
boolean retVal = false;
HttpResponse response = null;
tripleStoreURL = normalizeTripleStoreURL(tripleStoreURL);
testTripleStoreConnection(tripleStoreURL);
if (tripleStoreURL.charAt(tripleStoreURL.length() - 1) != '/') {
tripleStoreURL += "/";
}
tripleStoreURL += "statements";
try {
URIBuilder builder = new URIBuilder(tripleStoreURL);
// initialize the http entity
HttpClient httpclient = new DefaultHttpClient();
// File file = new File(filePath);
if (mime_types.get(rdfType) == null) {
throw new Exception("Could not find spefied rdf type: "
+ rdfType);
}
// preparing the context for the rdf
if (context == null || context.isEmpty()) {
logger.info("Empty context");
context = "null";
} else {
context = context.trim();
context.replaceAll(">", "");
context.replaceAll("<", "");
builder.setParameter("context", "<" + context + ">");
}
// preapring the base URL
if (baseURL != null && !baseURL.trim().isEmpty()) {
baseURL = baseURL.trim();
baseURL.replaceAll(">", "");
baseURL.replaceAll("<", "");
builder.setParameter("baseURI", "<" + baseURL + ">");
} else {
logger.info("Empty baseURL");
}
// check if we need to specify the context
if (!replaceFlag) {
// we use HttpPost over HttpPut, for put will replace the entire
// repo with an empty graph
logger.info("Using POST to save rdf to triple store");
HttpPost httpPost = new HttpPost(builder.build());
httpPost.setEntity(entity);
// executing the http request
response = httpclient.execute(httpPost);
} else {
// we use HttpPut to replace the context
logger.info("Using PUT to save rdf to triple store");
HttpPut httpput = new HttpPut(builder.build());
httpput.setEntity(entity);
// executing the http request
response = httpclient.execute(httpput);
}
logger.info("request url : " + builder.build().toString());
logger.info("StatusCode: "
+ response.getStatusLine().getStatusCode());
logger.info(response.toString());
int code = response.getStatusLine().getStatusCode();
if (code >= 200 && code < 300) {
retVal = true;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getClass().getName() + " : " + e.getMessage());
}
return retVal;
}
/**
* @param filePath
* : the url of the file from where the RDF is read
* @param tripleStoreURL
* : the triple store URL
* @param context
* : The graph context for the RDF
* @param replaceFlag
* : Whether to replace the contents of the graph deleteSrcFile
* default : false rdfType default: Turtle
* @param baseUri
* : The graph context for the RDF
*
* */
public boolean saveToStoreFromFile(String filePath, String tripleStoreURL,
String context, boolean replaceFlag, String baseUri) throws KarmaException{
File file = new File(filePath);
FileEntity entity = new FileEntity(file, ContentType.create(
mime_types.get(RDF_Types.Turtle.name()), "UTF-8"));
return saveToStore(entity, tripleStoreURL, context, replaceFlag,
RDF_Types.Turtle.name(), baseUri);
}
public boolean saveToStoreFromString(String input, String tripleStoreURL,
String context, Boolean replaceFlag, String baseUri) throws KarmaException{
StringEntity entity = new StringEntity(input, ContentType.create(mime_types.get(RDF_Types.Turtle.name())));
return saveToStore(entity, tripleStoreURL, context, replaceFlag,
RDF_Types.Turtle.name(), baseUri);
}
/**
* Invokes a SPARQL query on the given Triple Store URL and returns the JSON
* object containing the result. The content type of the result is
* application/sparql-results+json.
*
* @param query
* : SPARQL query
* @param tripleStoreUrl
* : SPARQL endpoint address of the triple store
* @param acceptContentType
* : The accept context type in the header
* @param contextType
* :
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws JSONException
*/
public static String invokeSparqlQuery(String query, String tripleStoreUrl,
String acceptContentType, String contextType)
throws ClientProtocolException, IOException, JSONException {
Map<String, String> formParams = new HashMap<String, String>();
formParams.put("query", query);
formParams.put("queryLn", "SPARQL");
String response = HTTPUtil.executeHTTPPostRequest(tripleStoreUrl,
contextType, acceptContentType, formParams);
if (response == null || response.isEmpty())
return null;
return response;
}
public static boolean create_repo(String repo_name, String repo_desc,
String type) {
// TODO : Take the repository type as an enum - native, memory, etc
boolean retVal = false;
if (repo_name == null || repo_name.isEmpty()) {
logger.error("Invalid repo name : " + repo_name);
return retVal;
}
if (repo_desc == null || repo_desc.isEmpty()) {
repo_desc = repo_name;
}
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
HttpPost httppost = new HttpPost(defaultWorkbenchUrl
+ "/NONE/create");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("Repository ID", repo_name));
formparams
.add(new BasicNameValuePair("Repository title", repo_name));
formparams
.add(new BasicNameValuePair("Triple indexes", "spoc,posc"));
formparams.add(new BasicNameValuePair("type", "native"));
httppost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuffer out = new StringBuffer();
BufferedReader buf = new BufferedReader(new InputStreamReader(
entity.getContent()));
String line = buf.readLine();
while (line != null) {
logger.info(line);
out.append(line);
line = buf.readLine();
}
logger.info(out.toString());
}
int status = response.getStatusLine().getStatusCode();
if (status >= 200 || status < 300) {
logger.info("Created repository : " + repo_name);
retVal = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return retVal;
}
/**
* This method fetches all the context from the given triplestore Url
* */
public List<String> getContexts(String url) {
if (url == null || url.isEmpty()) {
url = defaultModelsRepoUrl;
}
url += "/contexts";
List<String> graphs = new ArrayList<String>();
String responseString;
try {
responseString = HTTPUtil.executeHTTPGetRequest(url,
"application/sparql-results+json");
if (responseString != null) {
JSONObject models = new JSONObject(responseString);
JSONArray values = models.getJSONObject("results")
.getJSONArray("bindings");
int count = 0;
while (count < values.length()) {
JSONObject o = values.getJSONObject(count++);
graphs.add(o.getJSONObject("contextID").getString("value"));
}
}
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
graphs = null;
}
return graphs;
}
public boolean isUniqueGraphUri(String tripleStoreUrl, String graphUrl) {
logger.info("Checking for unique graphUri for url : " + graphUrl
+ " at endPoint : " + tripleStoreUrl);
boolean retVal = true;
List<String> urls = this.getContexts(tripleStoreUrl);
if (urls == null) {
return false;
}
// need to compare each url in case-insensitive form
for (String url : urls) {
if (url.equalsIgnoreCase(graphUrl)) {
retVal = false;
break;
}
}
return retVal;
}
/**
* This method clears all the statements from the given context
* */
public static boolean clearContexts(String tripleStoreUrl, String graphUri) {
if (tripleStoreUrl == null || tripleStoreUrl.isEmpty()
|| graphUri == null || graphUri.isEmpty()) {
logger.error("Missing graphUri or tripleStoreUrl");
return false;
}
String responseString;
try {
String url = tripleStoreUrl + "/statements?context="
+ URLEncoder.encode(graphUri, "UTF-8");
logger.info("Deleting from uri : " + url);
responseString = HTTPUtil.executeHTTPDeleteRequest(url);
logger.info("Response=" + responseString);
return true;
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return false;
}
public String normalizeURI(String uri) {
UriBuilder builder = UriBuilder.fromPath(uri);
return builder.build().toString();
}
}
| |
/*
* Copyright 2017 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.census;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static io.grpc.census.CensusStatsModule.CallAttemptsTracerFactory.RETRIES_PER_CALL;
import static io.grpc.census.CensusStatsModule.CallAttemptsTracerFactory.RETRY_DELAY_PER_CALL;
import static io.grpc.census.CensusStatsModule.CallAttemptsTracerFactory.TRANSPARENT_RETRIES_PER_CALL;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import io.grpc.Attributes;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ClientInterceptors;
import io.grpc.ClientStreamTracer;
import io.grpc.Context;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerServiceDefinition;
import io.grpc.ServerStreamTracer;
import io.grpc.ServerStreamTracer.ServerCallInfo;
import io.grpc.Status;
import io.grpc.census.CensusTracingModule.CallAttemptsTracerFactory;
import io.grpc.census.internal.DeprecatedCensusConstants;
import io.grpc.internal.FakeClock;
import io.grpc.internal.testing.StatsTestUtils;
import io.grpc.internal.testing.StatsTestUtils.FakeStatsRecorder;
import io.grpc.internal.testing.StatsTestUtils.FakeTagContextBinarySerializer;
import io.grpc.internal.testing.StatsTestUtils.FakeTagger;
import io.grpc.internal.testing.StatsTestUtils.MockableSpan;
import io.grpc.testing.GrpcServerRule;
import io.opencensus.common.Function;
import io.opencensus.common.Functions;
import io.opencensus.contrib.grpc.metrics.RpcMeasureConstants;
import io.opencensus.contrib.grpc.metrics.RpcViewConstants;
import io.opencensus.impl.stats.StatsComponentImpl;
import io.opencensus.stats.AggregationData;
import io.opencensus.stats.AggregationData.CountData;
import io.opencensus.stats.AggregationData.LastValueDataDouble;
import io.opencensus.stats.AggregationData.LastValueDataLong;
import io.opencensus.stats.AggregationData.SumDataDouble;
import io.opencensus.stats.Measure;
import io.opencensus.stats.StatsComponent;
import io.opencensus.stats.View;
import io.opencensus.tags.TagContext;
import io.opencensus.tags.TagValue;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.BlankSpan;
import io.opencensus.trace.EndSpanOptions;
import io.opencensus.trace.MessageEvent;
import io.opencensus.trace.Span;
import io.opencensus.trace.SpanBuilder;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.propagation.BinaryFormat;
import io.opencensus.trace.propagation.SpanContextParseException;
import io.opencensus.trace.unsafe.ContextUtils;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
/**
* Test for {@link CensusStatsModule} and {@link CensusTracingModule}.
*/
@RunWith(JUnit4.class)
public class CensusModulesTest {
private static final CallOptions.Key<String> CUSTOM_OPTION =
CallOptions.Key.createWithDefault("option1", "default");
private static final CallOptions CALL_OPTIONS =
CallOptions.DEFAULT.withOption(CUSTOM_OPTION, "customvalue");
private static final ClientStreamTracer.StreamInfo STREAM_INFO =
ClientStreamTracer.StreamInfo.newBuilder().build();
private static class StringInputStream extends InputStream {
final String string;
StringInputStream(String string) {
this.string = string;
}
@Override
public int read() {
// InProcessTransport doesn't actually read bytes from the InputStream. The InputStream is
// passed to the InProcess server and consumed by MARSHALLER.parse().
throw new UnsupportedOperationException("Should not be called");
}
}
private static final MethodDescriptor.Marshaller<String> MARSHALLER =
new MethodDescriptor.Marshaller<String>() {
@Override
public InputStream stream(String value) {
return new StringInputStream(value);
}
@Override
public String parse(InputStream stream) {
return ((StringInputStream) stream).string;
}
};
@Rule
public final MockitoRule mocks = MockitoJUnit.rule();
private final MethodDescriptor<String, String> method =
MethodDescriptor.<String, String>newBuilder()
.setType(MethodDescriptor.MethodType.UNKNOWN)
.setRequestMarshaller(MARSHALLER)
.setResponseMarshaller(MARSHALLER)
.setFullMethodName("package1.service2/method3")
.build();
private final MethodDescriptor<String, String> sampledMethod =
method.toBuilder().setSampledToLocalTracing(true).build();
private final FakeClock fakeClock = new FakeClock();
private final FakeTagger tagger = new FakeTagger();
private final FakeTagContextBinarySerializer tagCtxSerializer =
new FakeTagContextBinarySerializer();
private final FakeStatsRecorder statsRecorder = new FakeStatsRecorder();
private final Random random = new Random(1234);
private final Span fakeClientParentSpan = MockableSpan.generateRandomSpan(random);
private final Span spyClientSpan = spy(MockableSpan.generateRandomSpan(random));
private final Span spyAttemptSpan = spy(MockableSpan.generateRandomSpan(random));
private final SpanContext fakeAttemptSpanContext = spyAttemptSpan.getContext();
private final Span spyServerSpan = spy(MockableSpan.generateRandomSpan(random));
private final byte[] binarySpanContext = new byte[]{3, 1, 5};
private final SpanBuilder spyClientSpanBuilder = spy(new MockableSpan.Builder());
private final SpanBuilder spyAttemptSpanBuilder = spy(new MockableSpan.Builder());
private final SpanBuilder spyServerSpanBuilder = spy(new MockableSpan.Builder());
@Rule
public final GrpcServerRule grpcServerRule = new GrpcServerRule().directExecutor();
@Mock
private Tracer tracer;
@Mock
private BinaryFormat mockTracingPropagationHandler;
@Mock
private ClientCall.Listener<String> mockClientCallListener;
@Mock
private ServerCall.Listener<String> mockServerCallListener;
@Captor
private ArgumentCaptor<Status> statusCaptor;
@Captor
private ArgumentCaptor<MessageEvent> messageEventCaptor;
private CensusStatsModule censusStats;
private CensusTracingModule censusTracing;
@Before
public void setUp() throws Exception {
when(spyClientSpanBuilder.startSpan()).thenReturn(spyClientSpan);
when(spyAttemptSpanBuilder.startSpan()).thenReturn(spyAttemptSpan);
when(tracer.spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), ArgumentMatchers.<Span>any()))
.thenReturn(spyClientSpanBuilder);
when(tracer.spanBuilderWithExplicitParent(
eq("Attempt.package1.service2.method3"), ArgumentMatchers.<Span>any()))
.thenReturn(spyAttemptSpanBuilder);
when(spyServerSpanBuilder.startSpan()).thenReturn(spyServerSpan);
when(tracer.spanBuilderWithRemoteParent(anyString(), ArgumentMatchers.<SpanContext>any()))
.thenReturn(spyServerSpanBuilder);
when(mockTracingPropagationHandler.toByteArray(any(SpanContext.class)))
.thenReturn(binarySpanContext);
when(mockTracingPropagationHandler.fromByteArray(any(byte[].class)))
.thenReturn(fakeAttemptSpanContext);
censusStats =
new CensusStatsModule(
tagger, tagCtxSerializer, statsRecorder, fakeClock.getStopwatchSupplier(),
true, true, true, false /* real-time */, true);
censusTracing = new CensusTracingModule(tracer, mockTracingPropagationHandler);
}
@After
public void wrapUp() {
assertNull(statsRecorder.pollRecord());
}
@Test
public void clientInterceptorNoCustomTag() {
testClientInterceptors(false);
}
@Test
public void clientInterceptorCustomTag() {
testClientInterceptors(true);
}
// Test that Census ClientInterceptors uses the TagContext and Span out of the current Context
// to create the ClientCallTracer, and that it intercepts ClientCall.Listener.onClose() to call
// ClientCallTracer.callEnded().
private void testClientInterceptors(boolean nonDefaultContext) {
grpcServerRule.getServiceRegistry().addService(
ServerServiceDefinition.builder("package1.service2").addMethod(
method, new ServerCallHandler<String, String>() {
@Override
public ServerCall.Listener<String> startCall(
ServerCall<String, String> call, Metadata headers) {
call.sendHeaders(new Metadata());
call.sendMessage("Hello");
call.close(
Status.PERMISSION_DENIED.withDescription("No you don't"), new Metadata());
return mockServerCallListener;
}
}).build());
final AtomicReference<CallOptions> capturedCallOptions = new AtomicReference<>();
ClientInterceptor callOptionsCaptureInterceptor = new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
capturedCallOptions.set(callOptions);
return next.newCall(method, callOptions);
}
};
Channel interceptedChannel =
ClientInterceptors.intercept(
grpcServerRule.getChannel(), callOptionsCaptureInterceptor,
censusStats.getClientInterceptor(), censusTracing.getClientInterceptor());
ClientCall<String, String> call;
if (nonDefaultContext) {
Context ctx =
io.opencensus.tags.unsafe.ContextUtils.withValue(
Context.ROOT,
tagger
.emptyBuilder()
.putLocal(StatsTestUtils.EXTRA_TAG, TagValue.create("extra value"))
.build());
ctx = ContextUtils.withValue(ctx, fakeClientParentSpan);
Context origCtx = ctx.attach();
try {
call = interceptedChannel.newCall(method, CALL_OPTIONS);
} finally {
ctx.detach(origCtx);
}
} else {
assertEquals(
io.opencensus.tags.unsafe.ContextUtils.getValue(Context.ROOT),
io.opencensus.tags.unsafe.ContextUtils.getValue(Context.current()));
assertEquals(ContextUtils.getValue(Context.current()), BlankSpan.INSTANCE);
call = interceptedChannel.newCall(method, CALL_OPTIONS);
}
// The interceptor adds tracer factory to CallOptions
assertEquals("customvalue", capturedCallOptions.get().getOption(CUSTOM_OPTION));
assertEquals(2, capturedCallOptions.get().getStreamTracerFactories().size());
assertTrue(
capturedCallOptions.get().getStreamTracerFactories().get(0)
instanceof CallAttemptsTracerFactory);
assertTrue(
capturedCallOptions.get().getStreamTracerFactories().get(1)
instanceof CensusStatsModule.CallAttemptsTracerFactory);
// Make the call
Metadata headers = new Metadata();
call.start(mockClientCallListener, headers);
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
if (nonDefaultContext) {
TagValue extraTag = record.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra value", extraTag.asString());
assertEquals(2, record.tags.size());
} else {
assertNull(record.tags.get(StatsTestUtils.EXTRA_TAG));
assertEquals(1, record.tags.size());
}
if (nonDefaultContext) {
verify(tracer).spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), same(fakeClientParentSpan));
verify(spyClientSpanBuilder).setRecordEvents(eq(true));
} else {
verify(tracer).spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), ArgumentMatchers.<Span>isNotNull());
verify(spyClientSpanBuilder).setRecordEvents(eq(true));
}
verify(spyClientSpan, never()).end(any(EndSpanOptions.class));
// End the call
call.halfClose();
call.request(1);
verify(mockClientCallListener).onClose(statusCaptor.capture(), any(Metadata.class));
Status status = statusCaptor.getValue();
assertEquals(Status.Code.PERMISSION_DENIED, status.getCode());
assertEquals("No you don't", status.getDescription());
// The intercepting listener calls callEnded() on ClientCallTracer, which records to Census.
record = statsRecorder.pollRecord();
assertNotNull(record);
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.PERMISSION_DENIED.toString(), statusTag.asString());
if (nonDefaultContext) {
TagValue extraTag = record.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra value", extraTag.asString());
} else {
assertNull(record.tags.get(StatsTestUtils.EXTRA_TAG));
}
verify(spyClientSpan).end(
EndSpanOptions.builder()
.setStatus(
io.opencensus.trace.Status.PERMISSION_DENIED
.withDescription("No you don't"))
.setSampleToLocalSpanStore(false)
.build());
verify(spyClientSpan, never()).end();
assertZeroRetryRecorded();
}
@Test
public void clientBasicStatsDefaultContext_starts_finishes_noRealTime() {
subtestClientBasicStatsDefaultContext(true, true, false);
}
@Test
public void clientBasicStatsDefaultContext_starts_noFinishes_noRealTime() {
subtestClientBasicStatsDefaultContext(true, false, false);
}
@Test
public void clientBasicStatsDefaultContext_noStarts_finishes_noRealTime() {
subtestClientBasicStatsDefaultContext(false, true, false);
}
@Test
public void clientBasicStatsDefaultContext_noStarts_noFinishes_noRealTime() {
subtestClientBasicStatsDefaultContext(false, false, false);
}
@Test
public void clientBasicStatsDefaultContext_starts_finishes_realTime() {
subtestClientBasicStatsDefaultContext(true, true, true);
}
private void subtestClientBasicStatsDefaultContext(
boolean recordStarts, boolean recordFinishes, boolean recordRealTime) {
CensusStatsModule localCensusStats =
new CensusStatsModule(
tagger, tagCtxSerializer, statsRecorder, fakeClock.getStopwatchSupplier(),
true, recordStarts, recordFinishes, recordRealTime, true);
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
localCensusStats, tagger.empty(), method.getFullMethodName());
Metadata headers = new Metadata();
ClientStreamTracer tracer =
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, headers);
if (recordStarts) {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoServerContent(record);
assertEquals(1, record.tags.size());
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
} else {
assertNull(statsRecorder.pollRecord());
}
fakeClock.forwardTime(30, MILLISECONDS);
tracer.outboundHeaders();
fakeClock.forwardTime(100, MILLISECONDS);
tracer.outboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, true);
tracer.outboundWireSize(1028);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 1028, recordRealTime, true);
tracer.outboundUncompressedSize(1128);
fakeClock.forwardTime(16, MILLISECONDS);
tracer.inboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, true);
tracer.inboundWireSize(33);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, 33, recordRealTime, true);
tracer.inboundUncompressedSize(67);
tracer.outboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, true);
tracer.outboundWireSize(99);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 99, recordRealTime, true);
tracer.outboundUncompressedSize(865);
fakeClock.forwardTime(24, MILLISECONDS);
tracer.inboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, true);
tracer.inboundWireSize(154);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, 154, recordRealTime, true);
tracer.inboundUncompressedSize(552);
tracer.streamClosed(Status.OK);
callAttemptsTracerFactory.callEnded(Status.OK);
if (recordFinishes) {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoServerContent(record);
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.OK.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
1028 + 99,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertEquals(
1128 + 865,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
assertEquals(
33 + 154,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
assertEquals(
67 + 552,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
assertEquals(30 + 100 + 16 + 24,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
assertZeroRetryRecorded();
} else {
assertNull(statsRecorder.pollRecord());
}
}
// This test is only unit-testing the stat recording logic. The retry behavior is faked.
@Test
public void recordRetryStats() {
CensusStatsModule localCensusStats =
new CensusStatsModule(
tagger, tagCtxSerializer, statsRecorder, fakeClock.getStopwatchSupplier(),
true, true, true, true, true);
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
localCensusStats, tagger.empty(), method.getFullMethodName());
ClientStreamTracer tracer =
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, new Metadata());
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertEquals(1, record.tags.size());
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
fakeClock.forwardTime(30, MILLISECONDS);
tracer.outboundHeaders();
fakeClock.forwardTime(100, MILLISECONDS);
tracer.outboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundWireSize(1028);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 1028, true, true);
tracer.outboundUncompressedSize(1128);
fakeClock.forwardTime(24, MILLISECONDS);
tracer.streamClosed(Status.UNAVAILABLE);
record = statsRecorder.pollRecord();
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.UNAVAILABLE.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertEquals(1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
1028, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertEquals(
1128,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
30 + 100 + 24,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
// faking retry
fakeClock.forwardTime(1000, MILLISECONDS);
tracer = callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, new Metadata());
record = statsRecorder.pollRecord();
assertEquals(1, record.tags.size());
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
tracer.outboundHeaders();
tracer.outboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundWireSize(1028);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 1028, true, true);
tracer.outboundUncompressedSize(1128);
fakeClock.forwardTime(100, MILLISECONDS);
tracer.streamClosed(Status.NOT_FOUND);
record = statsRecorder.pollRecord();
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.NOT_FOUND.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertEquals(1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
1028, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertEquals(
1128,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
100 ,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
// fake transparent retry
fakeClock.forwardTime(10, MILLISECONDS);
tracer = callAttemptsTracerFactory.newClientStreamTracer(
STREAM_INFO.toBuilder().setIsTransparentRetry(true).build(), new Metadata());
record = statsRecorder.pollRecord();
assertEquals(1, record.tags.size());
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
tracer.streamClosed(Status.UNAVAILABLE);
record = statsRecorder.pollRecord();
statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.UNAVAILABLE.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertEquals(1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
// fake another transparent retry
fakeClock.forwardTime(10, MILLISECONDS);
tracer = callAttemptsTracerFactory.newClientStreamTracer(
STREAM_INFO.toBuilder().setIsTransparentRetry(true).build(), new Metadata());
record = statsRecorder.pollRecord();
assertEquals(1, record.tags.size());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
tracer.outboundHeaders();
tracer.outboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_METHOD, 1, true, true);
tracer.outboundWireSize(1028);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_METHOD, 1028, true, true);
tracer.outboundUncompressedSize(1128);
fakeClock.forwardTime(16, MILLISECONDS);
tracer.inboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_METHOD, 1, true, true);
tracer.inboundWireSize(33);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_METHOD, 33, true, true);
tracer.inboundUncompressedSize(67);
fakeClock.forwardTime(24, MILLISECONDS);
// RPC succeeded
tracer.streamClosed(Status.OK);
callAttemptsTracerFactory.callEnded(Status.OK);
record = statsRecorder.pollRecord();
statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.OK.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertThat(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT)).isNull();
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
1028, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertEquals(
1128,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
assertEquals(
33,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
assertEquals(
67,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
assertEquals(
16 + 24 ,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
record = statsRecorder.pollRecord();
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.OK.toString(), statusTag.asString());
assertThat(record.getMetric(RETRIES_PER_CALL)).isEqualTo(1);
assertThat(record.getMetric(TRANSPARENT_RETRIES_PER_CALL)).isEqualTo(2);
assertThat(record.getMetric(RETRY_DELAY_PER_CALL)).isEqualTo(1000D + 10 + 10);
}
private void assertRealTimeMetric(
Measure measure, long expectedValue, boolean recordRealTimeMetrics, boolean clientSide) {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
if (!recordRealTimeMetrics) {
assertNull(record);
return;
}
assertNotNull(record);
if (clientSide) {
assertNoServerContent(record);
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
} else {
assertNoClientContent(record);
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_SERVER_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
}
assertEquals(expectedValue, record.getMetricAsLongOrFail(measure));
}
private void assertZeroRetryRecorded() {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertThat(record.getMetric(RETRIES_PER_CALL)).isEqualTo(0);
assertThat(record.getMetric(TRANSPARENT_RETRIES_PER_CALL)).isEqualTo(0);
assertThat(record.getMetric(RETRY_DELAY_PER_CALL)).isEqualTo(0D);
}
@Test
public void clientBasicTracingDefaultSpan() {
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(null, method);
Metadata headers = new Metadata();
ClientStreamTracer clientStreamTracer = callTracer.newClientStreamTracer(STREAM_INFO, headers);
clientStreamTracer.streamCreated(Attributes.EMPTY, headers);
verify(tracer).spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), ArgumentMatchers.<Span>isNull());
verify(tracer).spanBuilderWithExplicitParent(
eq("Attempt.package1.service2.method3"), eq(spyClientSpan));
verify(spyClientSpan, never()).end(any(EndSpanOptions.class));
verify(spyAttemptSpan, never()).end(any(EndSpanOptions.class));
clientStreamTracer.outboundMessage(0);
clientStreamTracer.outboundMessageSent(0, 882, -1);
clientStreamTracer.inboundMessage(0);
clientStreamTracer.outboundMessage(1);
clientStreamTracer.outboundMessageSent(1, -1, 27);
clientStreamTracer.inboundMessageRead(0, 255, 90);
clientStreamTracer.streamClosed(Status.OK);
callTracer.callEnded(Status.OK);
InOrder inOrder = inOrder(spyClientSpan, spyAttemptSpan);
inOrder.verify(spyAttemptSpan)
.putAttribute("previous-rpc-attempts", AttributeValue.longAttributeValue(0));
inOrder.verify(spyAttemptSpan)
.putAttribute("transparent-retry", AttributeValue.booleanAttributeValue(false));
inOrder.verify(spyAttemptSpan, times(3)).addMessageEvent(messageEventCaptor.capture());
List<MessageEvent> events = messageEventCaptor.getAllValues();
assertEquals(
MessageEvent.builder(MessageEvent.Type.SENT, 0).setCompressedMessageSize(882).build(),
events.get(0));
assertEquals(
MessageEvent.builder(MessageEvent.Type.SENT, 1).setUncompressedMessageSize(27).build(),
events.get(1));
assertEquals(
MessageEvent.builder(MessageEvent.Type.RECEIVED, 0)
.setCompressedMessageSize(255)
.setUncompressedMessageSize(90)
.build(),
events.get(2));
inOrder.verify(spyAttemptSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.OK)
.setSampleToLocalSpanStore(false)
.build());
inOrder.verify(spyClientSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.OK)
.setSampleToLocalSpanStore(false)
.build());
inOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(tracer);
}
@Test
public void clientTracingSampledToLocalSpanStore() {
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(null, sampledMethod);
callTracer.callEnded(Status.OK);
verify(spyClientSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.OK)
.setSampleToLocalSpanStore(true)
.build());
}
@Test
public void clientStreamNeverCreatedStillRecordStats() {
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
censusStats, tagger.empty(), method.getFullMethodName());
ClientStreamTracer streamTracer =
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, new Metadata());
fakeClock.forwardTime(3000, MILLISECONDS);
Status status = Status.DEADLINE_EXCEEDED.withDescription("3 seconds");
streamTracer.streamClosed(status);
callAttemptsTracerFactory.callEnded(status);
// Upstart record
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoServerContent(record);
assertEquals(1, record.tags.size());
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT));
// Completion record
record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoServerContent(record);
methodTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.DEADLINE_EXCEEDED.toString(), statusTag.asString());
assertEquals(
1,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_FINISHED_COUNT));
assertEquals(
1,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertEquals(
0,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
assertEquals(
0, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
assertEquals(0,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
assertEquals(
3000,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_SERVER_ELAPSED_TIME));
assertZeroRetryRecorded();
}
@Test
public void clientStreamNeverCreatedStillRecordTracing() {
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(fakeClientParentSpan, method);
verify(tracer).spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), same(fakeClientParentSpan));
verify(spyClientSpanBuilder).setRecordEvents(eq(true));
callTracer.callEnded(Status.DEADLINE_EXCEEDED.withDescription("3 seconds"));
verify(spyClientSpan).end(
EndSpanOptions.builder()
.setStatus(
io.opencensus.trace.Status.DEADLINE_EXCEEDED
.withDescription("3 seconds"))
.setSampleToLocalSpanStore(false)
.build());
verifyNoMoreInteractions(spyClientSpan);
}
@Test
public void statsHeadersPropagateTags_record() {
subtestStatsHeadersPropagateTags(true, true);
}
@Test
public void statsHeadersPropagateTags_notRecord() {
subtestStatsHeadersPropagateTags(true, false);
}
@Test
public void statsHeadersNotPropagateTags_record() {
subtestStatsHeadersPropagateTags(false, true);
}
@Test
public void statsHeadersNotPropagateTags_notRecord() {
subtestStatsHeadersPropagateTags(false, false);
}
private void subtestStatsHeadersPropagateTags(boolean propagate, boolean recordStats) {
// EXTRA_TAG is propagated by the FakeStatsContextFactory. Note that not all tags are
// propagated. The StatsContextFactory decides which tags are to propagated. gRPC facilitates
// the propagation by putting them in the headers.
TagContext clientCtx = tagger.emptyBuilder().putLocal(
StatsTestUtils.EXTRA_TAG, TagValue.create("extra-tag-value-897")).build();
CensusStatsModule census =
new CensusStatsModule(
tagger,
tagCtxSerializer,
statsRecorder,
fakeClock.getStopwatchSupplier(),
propagate, recordStats, recordStats, recordStats, recordStats);
Metadata headers = new Metadata();
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
census, clientCtx, method.getFullMethodName());
// This propagates clientCtx to headers if propagates==true
ClientStreamTracer streamTracer =
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, headers);
streamTracer.streamCreated(Attributes.EMPTY, headers);
if (recordStats) {
// Client upstart record
StatsTestUtils.MetricsRecord clientRecord = statsRecorder.pollRecord();
assertNotNull(clientRecord);
assertNoServerContent(clientRecord);
assertEquals(2, clientRecord.tags.size());
TagValue clientMethodTag = clientRecord.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), clientMethodTag.asString());
TagValue clientPropagatedTag = clientRecord.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra-tag-value-897", clientPropagatedTag.asString());
}
if (propagate) {
assertTrue(headers.containsKey(census.statsHeader));
} else {
assertFalse(headers.containsKey(census.statsHeader));
return;
}
ServerStreamTracer serverTracer =
census.getServerTracerFactory().newServerStreamTracer(method.getFullMethodName(), headers);
// Server tracer deserializes clientCtx from the headers, so that it records stats with the
// propagated tags.
Context serverContext = serverTracer.filterContext(Context.ROOT);
// It also put clientCtx in the Context seen by the call handler
assertEquals(
tagger.toBuilder(clientCtx)
.putLocal(
RpcMeasureConstants.GRPC_SERVER_METHOD,
TagValue.create(method.getFullMethodName()))
.build(),
io.opencensus.tags.unsafe.ContextUtils.getValue(serverContext));
// Verifies that the server tracer records the status with the propagated tag
serverTracer.streamClosed(Status.OK);
if (recordStats) {
// Server upstart record
StatsTestUtils.MetricsRecord serverRecord = statsRecorder.pollRecord();
assertNotNull(serverRecord);
assertNoClientContent(serverRecord);
assertEquals(2, serverRecord.tags.size());
TagValue serverMethodTag = serverRecord.tags.get(RpcMeasureConstants.GRPC_SERVER_METHOD);
assertEquals(method.getFullMethodName(), serverMethodTag.asString());
TagValue serverPropagatedTag = serverRecord.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra-tag-value-897", serverPropagatedTag.asString());
// Server completion record
serverRecord = statsRecorder.pollRecord();
assertNotNull(serverRecord);
assertNoClientContent(serverRecord);
serverMethodTag = serverRecord.tags.get(RpcMeasureConstants.GRPC_SERVER_METHOD);
assertEquals(method.getFullMethodName(), serverMethodTag.asString());
TagValue serverStatusTag = serverRecord.tags.get(RpcMeasureConstants.GRPC_SERVER_STATUS);
assertEquals(Status.Code.OK.toString(), serverStatusTag.asString());
assertNull(serverRecord.getMetric(DeprecatedCensusConstants.RPC_SERVER_ERROR_COUNT));
serverPropagatedTag = serverRecord.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra-tag-value-897", serverPropagatedTag.asString());
}
// Verifies that the client tracer factory uses clientCtx, which includes the custom tags, to
// record stats.
streamTracer.streamClosed(Status.OK);
callAttemptsTracerFactory.callEnded(Status.OK);
if (recordStats) {
// Client completion record
StatsTestUtils.MetricsRecord clientRecord = statsRecorder.pollRecord();
assertNotNull(clientRecord);
assertNoServerContent(clientRecord);
TagValue clientMethodTag = clientRecord.tags.get(RpcMeasureConstants.GRPC_CLIENT_METHOD);
assertEquals(method.getFullMethodName(), clientMethodTag.asString());
TagValue clientStatusTag = clientRecord.tags.get(RpcMeasureConstants.GRPC_CLIENT_STATUS);
assertEquals(Status.Code.OK.toString(), clientStatusTag.asString());
assertNull(clientRecord.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
TagValue clientPropagatedTag = clientRecord.tags.get(StatsTestUtils.EXTRA_TAG);
assertEquals("extra-tag-value-897", clientPropagatedTag.asString());
assertZeroRetryRecorded();
}
if (!recordStats) {
assertNull(statsRecorder.pollRecord());
}
}
@Test
public void statsHeadersNotPropagateDefaultContext() {
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
censusStats, tagger.empty(), method.getFullMethodName());
Metadata headers = new Metadata();
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, headers)
.streamCreated(Attributes.EMPTY, headers);
assertFalse(headers.containsKey(censusStats.statsHeader));
// Clear recorded stats to satisfy the assertions in wrapUp()
statsRecorder.rolloverRecords();
}
@Test
public void statsHeaderMalformed() {
// Construct a malformed header and make sure parsing it will throw
byte[] statsHeaderValue = new byte[]{1};
Metadata.Key<byte[]> arbitraryStatsHeader =
Metadata.Key.of("grpc-tags-bin", Metadata.BINARY_BYTE_MARSHALLER);
try {
tagCtxSerializer.fromByteArray(statsHeaderValue);
fail("Should have thrown");
} catch (Exception e) {
// Expected
}
// But the header key will return a default context for it
Metadata headers = new Metadata();
assertNull(headers.get(censusStats.statsHeader));
headers.put(arbitraryStatsHeader, statsHeaderValue);
assertSame(tagger.empty(), headers.get(censusStats.statsHeader));
}
@Test
public void traceHeadersPropagateSpanContext() throws Exception {
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(fakeClientParentSpan, method);
Metadata headers = new Metadata();
ClientStreamTracer streamTracer = callTracer.newClientStreamTracer(STREAM_INFO, headers);
streamTracer.streamCreated(Attributes.EMPTY, headers);
verify(mockTracingPropagationHandler).toByteArray(same(fakeAttemptSpanContext));
verifyNoMoreInteractions(mockTracingPropagationHandler);
verify(tracer).spanBuilderWithExplicitParent(
eq("Sent.package1.service2.method3"), same(fakeClientParentSpan));
verify(tracer).spanBuilderWithExplicitParent(
eq("Attempt.package1.service2.method3"), same(spyClientSpan));
verify(spyClientSpanBuilder).setRecordEvents(eq(true));
verifyNoMoreInteractions(tracer);
assertTrue(headers.containsKey(censusTracing.tracingHeader));
ServerStreamTracer serverTracer =
censusTracing.getServerTracerFactory().newServerStreamTracer(
method.getFullMethodName(), headers);
verify(mockTracingPropagationHandler).fromByteArray(same(binarySpanContext));
verify(tracer).spanBuilderWithRemoteParent(
eq("Recv.package1.service2.method3"), same(spyAttemptSpan.getContext()));
verify(spyServerSpanBuilder).setRecordEvents(eq(true));
Context filteredContext = serverTracer.filterContext(Context.ROOT);
assertSame(spyServerSpan, ContextUtils.getValue(filteredContext));
}
@Test
public void traceHeaders_propagateSpanContext() throws Exception {
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(fakeClientParentSpan, method);
Metadata headers = new Metadata();
ClientStreamTracer streamTracer = callTracer.newClientStreamTracer(STREAM_INFO, headers);
streamTracer.streamCreated(Attributes.EMPTY, headers);
assertThat(headers.keys()).isNotEmpty();
}
@Test
public void traceHeaders_missingCensusImpl_notPropagateSpanContext()
throws Exception {
reset(spyClientSpanBuilder);
reset(spyAttemptSpanBuilder);
when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
when(spyAttemptSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
Metadata headers = new Metadata();
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
callTracer.newClientStreamTracer(STREAM_INFO, headers).streamCreated(Attributes.EMPTY, headers);
assertThat(headers.keys()).isEmpty();
}
@Test
public void traceHeaders_clientMissingCensusImpl_preservingHeaders() throws Exception {
reset(spyClientSpanBuilder);
reset(spyAttemptSpanBuilder);
when(spyClientSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
when(spyAttemptSpanBuilder.startSpan()).thenReturn(BlankSpan.INSTANCE);
Metadata headers = new Metadata();
headers.put(
Metadata.Key.of("never-used-key-bin", Metadata.BINARY_BYTE_MARSHALLER),
new byte[] {});
Set<String> originalHeaderKeys = new HashSet<>(headers.keys());
CallAttemptsTracerFactory callTracer =
censusTracing.newClientCallTracer(BlankSpan.INSTANCE, method);
callTracer.newClientStreamTracer(STREAM_INFO, headers).streamCreated(Attributes.EMPTY, headers);
assertThat(headers.keys()).containsExactlyElementsIn(originalHeaderKeys);
}
@Test
public void traceHeaderMalformed() throws Exception {
// As comparison, normal header parsing
Metadata headers = new Metadata();
headers.put(censusTracing.tracingHeader, fakeAttemptSpanContext);
// mockTracingPropagationHandler was stubbed to always return fakeServerParentSpanContext
assertSame(spyAttemptSpan.getContext(), headers.get(censusTracing.tracingHeader));
// Make BinaryPropagationHandler always throw when parsing the header
when(mockTracingPropagationHandler.fromByteArray(any(byte[].class)))
.thenThrow(new SpanContextParseException("Malformed header"));
headers = new Metadata();
assertNull(headers.get(censusTracing.tracingHeader));
headers.put(censusTracing.tracingHeader, fakeAttemptSpanContext);
assertSame(SpanContext.INVALID, headers.get(censusTracing.tracingHeader));
assertNotSame(spyClientSpan.getContext(), SpanContext.INVALID);
// A null Span is used as the parent in this case
censusTracing.getServerTracerFactory().newServerStreamTracer(
method.getFullMethodName(), headers);
verify(tracer).spanBuilderWithRemoteParent(
eq("Recv.package1.service2.method3"), ArgumentMatchers.<SpanContext>isNull());
verify(spyServerSpanBuilder).setRecordEvents(eq(true));
}
@Test
public void serverBasicStatsNoHeaders_starts_finishes_noRealTime() {
subtestServerBasicStatsNoHeaders(true, true, false);
}
@Test
public void serverBasicStatsNoHeaders_starts_noFinishes_noRealTime() {
subtestServerBasicStatsNoHeaders(true, false, false);
}
@Test
public void serverBasicStatsNoHeaders_noStarts_finishes_noRealTime() {
subtestServerBasicStatsNoHeaders(false, true, false);
}
@Test
public void serverBasicStatsNoHeaders_noStarts_noFinishes_noRealTime() {
subtestServerBasicStatsNoHeaders(false, false, false);
}
@Test
public void serverBasicStatsNoHeaders_starts_finishes_realTime() {
subtestServerBasicStatsNoHeaders(true, true, true);
}
private void subtestServerBasicStatsNoHeaders(
boolean recordStarts, boolean recordFinishes, boolean recordRealTime) {
CensusStatsModule localCensusStats =
new CensusStatsModule(
tagger, tagCtxSerializer, statsRecorder, fakeClock.getStopwatchSupplier(),
true, recordStarts, recordFinishes, recordRealTime, true);
ServerStreamTracer.Factory tracerFactory = localCensusStats.getServerTracerFactory();
ServerStreamTracer tracer =
tracerFactory.newServerStreamTracer(method.getFullMethodName(), new Metadata());
if (recordStarts) {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoClientContent(record);
assertEquals(1, record.tags.size());
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_SERVER_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
assertEquals(
1,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_STARTED_COUNT));
} else {
assertNull(statsRecorder.pollRecord());
}
Context filteredContext = tracer.filterContext(Context.ROOT);
TagContext statsCtx = io.opencensus.tags.unsafe.ContextUtils.getValue(filteredContext);
assertEquals(
tagger
.emptyBuilder()
.putLocal(
RpcMeasureConstants.GRPC_SERVER_METHOD,
TagValue.create(method.getFullMethodName()))
.build(),
statsCtx);
tracer.inboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, false);
tracer.inboundWireSize(34);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_RECEIVED_BYTES_PER_METHOD, 34, recordRealTime, false);
tracer.inboundUncompressedSize(67);
fakeClock.forwardTime(100, MILLISECONDS);
tracer.outboundMessage(0);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, false);
tracer.outboundWireSize(1028);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_SENT_BYTES_PER_METHOD, 1028, recordRealTime, false);
tracer.outboundUncompressedSize(1128);
fakeClock.forwardTime(16, MILLISECONDS);
tracer.inboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_RECEIVED_MESSAGES_PER_METHOD, 1, recordRealTime, false);
tracer.inboundWireSize(154);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_RECEIVED_BYTES_PER_METHOD, 154, recordRealTime, false);
tracer.inboundUncompressedSize(552);
tracer.outboundMessage(1);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_SENT_MESSAGES_PER_METHOD, 1, recordRealTime, false);
tracer.outboundWireSize(99);
assertRealTimeMetric(
RpcMeasureConstants.GRPC_SERVER_SENT_BYTES_PER_METHOD, 99, recordRealTime, false);
tracer.outboundUncompressedSize(865);
fakeClock.forwardTime(24, MILLISECONDS);
tracer.streamClosed(Status.CANCELLED);
if (recordFinishes) {
StatsTestUtils.MetricsRecord record = statsRecorder.pollRecord();
assertNotNull(record);
assertNoClientContent(record);
TagValue methodTag = record.tags.get(RpcMeasureConstants.GRPC_SERVER_METHOD);
assertEquals(method.getFullMethodName(), methodTag.asString());
TagValue statusTag = record.tags.get(RpcMeasureConstants.GRPC_SERVER_STATUS);
assertEquals(Status.Code.CANCELLED.toString(), statusTag.asString());
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_FINISHED_COUNT));
assertEquals(
1, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_ERROR_COUNT));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_COUNT));
assertEquals(
1028 + 99,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_BYTES));
assertEquals(
1128 + 865,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
assertEquals(
2, record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_REQUEST_COUNT));
assertEquals(
34 + 154,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_REQUEST_BYTES));
assertEquals(67 + 552,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(100 + 16 + 24,
record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_SERVER_LATENCY));
} else {
assertNull(statsRecorder.pollRecord());
}
}
@Test
public void serverBasicTracingNoHeaders() {
ServerStreamTracer.Factory tracerFactory = censusTracing.getServerTracerFactory();
ServerStreamTracer serverStreamTracer =
tracerFactory.newServerStreamTracer(method.getFullMethodName(), new Metadata());
verifyNoInteractions(mockTracingPropagationHandler);
verify(tracer).spanBuilderWithRemoteParent(
eq("Recv.package1.service2.method3"), ArgumentMatchers.<SpanContext>isNull());
verify(spyServerSpanBuilder).setRecordEvents(eq(true));
Context filteredContext = serverStreamTracer.filterContext(Context.ROOT);
assertSame(spyServerSpan, ContextUtils.getValue(filteredContext));
serverStreamTracer.serverCallStarted(
new CallInfo<>(method, Attributes.EMPTY, null));
verify(spyServerSpan, never()).end(any(EndSpanOptions.class));
serverStreamTracer.outboundMessage(0);
serverStreamTracer.outboundMessageSent(0, 882, -1);
serverStreamTracer.inboundMessage(0);
serverStreamTracer.outboundMessage(1);
serverStreamTracer.outboundMessageSent(1, -1, 27);
serverStreamTracer.inboundMessageRead(0, 255, 90);
serverStreamTracer.streamClosed(Status.CANCELLED);
InOrder inOrder = inOrder(spyServerSpan);
inOrder.verify(spyServerSpan, times(3)).addMessageEvent(messageEventCaptor.capture());
List<MessageEvent> events = messageEventCaptor.getAllValues();
assertEquals(
MessageEvent.builder(MessageEvent.Type.SENT, 0).setCompressedMessageSize(882).build(),
events.get(0));
assertEquals(
MessageEvent.builder(MessageEvent.Type.SENT, 1).setUncompressedMessageSize(27).build(),
events.get(1));
assertEquals(
MessageEvent.builder(MessageEvent.Type.RECEIVED, 0)
.setCompressedMessageSize(255)
.setUncompressedMessageSize(90)
.build(),
events.get(2));
inOrder.verify(spyServerSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.CANCELLED)
.setSampleToLocalSpanStore(false)
.build());
verifyNoMoreInteractions(spyServerSpan);
}
@Test
public void serverTracingSampledToLocalSpanStore() {
ServerStreamTracer.Factory tracerFactory = censusTracing.getServerTracerFactory();
ServerStreamTracer serverStreamTracer =
tracerFactory.newServerStreamTracer(sampledMethod.getFullMethodName(), new Metadata());
serverStreamTracer.filterContext(Context.ROOT);
serverStreamTracer.serverCallStarted(
new CallInfo<>(sampledMethod, Attributes.EMPTY, null));
serverStreamTracer.streamClosed(Status.CANCELLED);
verify(spyServerSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.CANCELLED)
.setSampleToLocalSpanStore(true)
.build());
}
@Test
public void serverTracingNotSampledToLocalSpanStore_whenServerCallNotCreated() {
ServerStreamTracer.Factory tracerFactory = censusTracing.getServerTracerFactory();
ServerStreamTracer serverStreamTracer =
tracerFactory.newServerStreamTracer(sampledMethod.getFullMethodName(), new Metadata());
serverStreamTracer.streamClosed(Status.CANCELLED);
verify(spyServerSpan).end(
EndSpanOptions.builder()
.setStatus(io.opencensus.trace.Status.CANCELLED)
.setSampleToLocalSpanStore(false)
.build());
}
@Test
public void convertToTracingStatus() {
// Without description
for (Status.Code grpcCode : Status.Code.values()) {
Status grpcStatus = Status.fromCode(grpcCode);
io.opencensus.trace.Status tracingStatus =
CensusTracingModule.convertStatus(grpcStatus);
assertEquals(grpcCode.toString(), tracingStatus.getCanonicalCode().toString());
assertNull(tracingStatus.getDescription());
}
// With description
for (Status.Code grpcCode : Status.Code.values()) {
Status grpcStatus = Status.fromCode(grpcCode).withDescription("This is my description");
io.opencensus.trace.Status tracingStatus =
CensusTracingModule.convertStatus(grpcStatus);
assertEquals(grpcCode.toString(), tracingStatus.getCanonicalCode().toString());
assertEquals(grpcStatus.getDescription(), tracingStatus.getDescription());
}
}
@Test
public void generateTraceSpanName() {
assertEquals(
"Sent.io.grpc.Foo", CensusTracingModule.generateTraceSpanName(false, "io.grpc/Foo"));
assertEquals(
"Recv.io.grpc.Bar", CensusTracingModule.generateTraceSpanName(true, "io.grpc/Bar"));
}
private static void assertNoServerContent(StatsTestUtils.MetricsRecord record) {
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_ERROR_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_REQUEST_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_REQUEST_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_SERVER_ELAPSED_TIME));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_SERVER_LATENCY));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
}
private static void assertNoClientContent(StatsTestUtils.MetricsRecord record) {
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ERROR_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_SERVER_ELAPSED_TIME));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
}
@Deprecated
@Test
public void newTagsPopulateOldViews() throws InterruptedException {
StatsComponent localStats = new StatsComponentImpl();
// Test views that contain both of the remap tags: method & status.
localStats.getViewManager().registerView(RpcViewConstants.RPC_CLIENT_ERROR_COUNT_VIEW);
localStats.getViewManager().registerView(RpcViewConstants.GRPC_CLIENT_COMPLETED_RPC_VIEW);
CensusStatsModule localCensusStats = new CensusStatsModule(
tagger, tagCtxSerializer, localStats.getStatsRecorder(), fakeClock.getStopwatchSupplier(),
false, false, true, false /* real-time */, true);
CensusStatsModule.CallAttemptsTracerFactory callAttemptsTracerFactory =
new CensusStatsModule.CallAttemptsTracerFactory(
localCensusStats, tagger.empty(), method.getFullMethodName());
Metadata headers = new Metadata();
ClientStreamTracer tracer =
callAttemptsTracerFactory.newClientStreamTracer(STREAM_INFO, headers);
tracer.streamCreated(Attributes.EMPTY, headers);
fakeClock.forwardTime(30, MILLISECONDS);
Status status = Status.PERMISSION_DENIED.withDescription("No you don't");
tracer.streamClosed(status);
callAttemptsTracerFactory.callEnded(status);
// Give OpenCensus a chance to update the views asynchronously.
Thread.sleep(100);
assertWithMessage("Legacy error count view had unexpected count")
.that(
getAggregationValueAsLong(
localStats,
RpcViewConstants.RPC_CLIENT_ERROR_COUNT_VIEW,
ImmutableList.of(
TagValue.create("PERMISSION_DENIED"),
TagValue.create(method.getFullMethodName()))))
.isEqualTo(1);
assertWithMessage("New error count view had unexpected count")
.that(
getAggregationValueAsLong(
localStats,
RpcViewConstants.GRPC_CLIENT_COMPLETED_RPC_VIEW,
ImmutableList.of(
TagValue.create(method.getFullMethodName()),
TagValue.create("PERMISSION_DENIED"))))
.isEqualTo(1);
}
@Deprecated
private long getAggregationValueAsLong(StatsComponent localStats, View view,
List<TagValue> dimension) {
AggregationData aggregationData = localStats.getViewManager()
.getView(view.getName())
.getAggregationMap()
.get(dimension);
return aggregationData.match(
new Function<SumDataDouble, Long>() {
@Override
public Long apply(SumDataDouble arg) {
return (long) arg.getSum();
}
},
Functions.<Long>throwAssertionError(),
new Function<CountData, Long>() {
@Override
public Long apply(CountData arg) {
return arg.getCount();
}
},
Functions.<Long>throwAssertionError(),
new Function<LastValueDataDouble, Long>() {
@Override
public Long apply(LastValueDataDouble arg) {
return (long) arg.getLastValue();
}
},
new Function<LastValueDataLong, Long>() {
@Override
public Long apply(LastValueDataLong arg) {
return arg.getLastValue();
}
},
new Function<AggregationData, Long>() {
@Override
public Long apply(AggregationData arg) {
return ((AggregationData.MeanData) arg).getCount();
}
});
}
private static class CallInfo<ReqT, RespT> extends ServerCallInfo<ReqT, RespT> {
private final MethodDescriptor<ReqT, RespT> methodDescriptor;
private final Attributes attributes;
private final String authority;
CallInfo(
MethodDescriptor<ReqT, RespT> methodDescriptor,
Attributes attributes,
@Nullable String authority) {
this.methodDescriptor = methodDescriptor;
this.attributes = attributes;
this.authority = authority;
}
@Override
public MethodDescriptor<ReqT, RespT> getMethodDescriptor() {
return methodDescriptor;
}
@Override
public Attributes getAttributes() {
return attributes;
}
@Nullable
@Override
public String getAuthority() {
return authority;
}
}
}
| |
package com.github.simonpercic.oklog.core;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import okio.Buffer;
import okio.BufferedSource;
/**
* Base log data interceptor util. Inspired by: https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public abstract class BaseLogDataInterceptor<Chain, Request, Response, Headers, MediaType> {
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String IDENTITY = "identity";
// region Abstract methods
protected abstract Request request(Chain chain);
protected abstract String protocol(Chain chain);
protected abstract String requestMethod(Request request);
protected abstract String requestUrl(Request request);
protected abstract String requestUrlPath(Request request);
protected abstract String responseUrl(Response response);
protected abstract Headers requestHeaders(Request request);
protected abstract Headers responseHeaders(Response response);
protected abstract int headersCount(Headers headers);
protected abstract String headerName(Headers headers, int index);
protected abstract String headerValue(Headers headers, int index);
protected abstract String headerValue(Headers headers, String name);
protected abstract boolean hasRequestBody(Request request);
protected abstract boolean hasResponseBody(Response response);
protected abstract int responseCode(Response response);
protected abstract String responseMessage(Response response);
protected abstract long requestContentLength(Request request) throws IOException;
protected abstract long responseContentLength(Response response) throws IOException;
protected abstract MediaType requestContentType(Request request);
protected abstract MediaType responseContentType(Response response);
protected abstract String contentTypeString(MediaType mediaType);
protected abstract Charset contentTypeCharset(MediaType mediaType, Charset charset);
@Nullable protected abstract Charset responseContentTypeCharset(MediaType contentType, Charset charset);
protected abstract void writeRequestBody(Request request, Buffer buffer) throws IOException;
protected abstract BufferedSource responseBodySource(Response response) throws IOException;
// endregion Abstract methods
@NotNull
public RequestLogData<Request> processRequest(Chain chain) throws IOException {
LogDataBuilder logDataBuilder = new LogDataBuilder();
Request request = request(chain);
boolean hasRequestBody = hasRequestBody(request);
logDataBuilder
.requestMethod(requestMethod(request))
.requestUrl(requestUrl(request))
.requestUrlPath(requestUrlPath(request))
.protocol(protocol(chain));
if (hasRequestBody) {
// Request body headers are only present when installed as a network interceptor.
// Explicitly include content type and content length.
MediaType mediaType = requestContentType(request);
if (mediaType != null) {
logDataBuilder.requestContentType(contentTypeString(mediaType));
}
long contentLength = requestContentLength(request);
logDataBuilder.requestContentLength(contentLength);
}
Headers headers = requestHeaders(request);
for (int i = 0, count = headersCount(headers); i < count; i++) {
String name = headerName(headers, i);
// Skip headers from the request body as they are explicitly logged above.
if (!CONTENT_TYPE.equalsIgnoreCase(name) && !CONTENT_LENGTH.equalsIgnoreCase(name)) {
logDataBuilder.addRequestHeader(name, headerValue(headers, i));
}
}
if (!hasRequestBody) {
logDataBuilder.requestBodyState(LogDataBuilder.BodyState.NO_BODY);
} else if (bodyEncoded(headers)) {
logDataBuilder.requestBodyState(LogDataBuilder.BodyState.ENCODED_BODY);
} else {
Buffer buffer = new Buffer();
writeRequestBody(request, buffer);
Charset charset = Constants.CHARSET_UTF8;
MediaType contentType = requestContentType(request);
if (contentType != null) {
charset = contentTypeCharset(contentType, Constants.CHARSET_UTF8);
}
if (isPlaintext(buffer)) {
logDataBuilder.requestBody(buffer.readString(charset));
} else {
logDataBuilder.requestBodyState(LogDataBuilder.BodyState.BINARY_BODY);
}
}
return new RequestLogData<>(request, logDataBuilder);
}
@NotNull
public ResponseLogData<Response> processResponse(LogDataBuilder logDataBuilder,
Response response) throws IOException {
long contentLength = responseContentLength(response);
logDataBuilder
.responseCode(responseCode(response))
.responseMessage(responseMessage(response))
.responseContentLength(contentLength)
.responseUrl(responseUrl(response));
Headers responseHeaders = responseHeaders(response);
for (int i = 0, count = headersCount(responseHeaders); i < count; i++) {
String name = headerName(responseHeaders, i);
// skip content-length, since it's already logged above
if (!CONTENT_LENGTH.equalsIgnoreCase(name) && !skipResponseHeader(name)) {
logDataBuilder.addResponseHeader(name, headerValue(responseHeaders, i));
}
}
if (!hasResponseBody(response)) {
logDataBuilder.responseBodyState(LogDataBuilder.BodyState.NO_BODY);
} else if (bodyEncoded(responseHeaders)) {
logDataBuilder.responseBodyState(LogDataBuilder.BodyState.ENCODED_BODY);
} else {
BufferedSource source = responseBodySource(response);
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = Constants.CHARSET_UTF8;
MediaType contentType = responseContentType(response);
if (contentType != null) {
charset = responseContentTypeCharset(contentType, Constants.CHARSET_UTF8);
if (charset == null) {
logDataBuilder.responseBodyState(LogDataBuilder.BodyState.CHARSET_MALFORMED);
return new ResponseLogData<>(response, logDataBuilder);
}
}
if (!isPlaintext(buffer)) {
logDataBuilder.responseBodyState(LogDataBuilder.BodyState.BINARY_BODY);
logDataBuilder.responseBodySize(buffer.size());
return new ResponseLogData<>(response, logDataBuilder);
}
if (contentLength != 0) {
logDataBuilder.responseBody(buffer.clone().readString(charset));
}
logDataBuilder.responseBodySize(buffer.size());
}
return new ResponseLogData<>(response, logDataBuilder);
}
protected boolean skipResponseHeader(String headerName) {
return false;
}
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
static boolean isPlaintext(Buffer buffer) throws EOFException {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headerValue(headers, CONTENT_ENCODING);
return contentEncoding != null && !contentEncoding.equalsIgnoreCase(IDENTITY);
}
public static final class RequestLogData<Request> {
private final Request request;
private final LogDataBuilder logData;
private RequestLogData(Request request, LogDataBuilder logData) {
this.request = request;
this.logData = logData;
}
public Request getRequest() {
return request;
}
public LogDataBuilder getLogData() {
return logData;
}
}
public static final class ResponseLogData<Response> {
private final Response response;
private final LogDataBuilder logData;
private ResponseLogData(Response response, LogDataBuilder logData) {
this.response = response;
this.logData = logData;
}
public Response getResponse() {
return response;
}
public LogDataBuilder getLogData() {
return logData;
}
}
}
| |
/*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.keyvalue.cassandra;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.common.annotation.Idempotent;
import com.palantir.common.base.Throwables;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import com.palantir.util.Pair;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.CqlResult;
import org.apache.thrift.TException;
import org.immutables.value.Value;
public class CassandraTimestampBackupRunner {
private static final SafeLogger log = SafeLoggerFactory.get(CassandraTimestampBackupRunner.class);
private final CassandraKeyValueService cassandraKeyValueService;
public CassandraTimestampBackupRunner(CassandraKeyValueService cassandraKeyValueService) {
this.cassandraKeyValueService = cassandraKeyValueService;
}
/**
* Creates the timestamp table, if it doesn't already exist.
*/
@Idempotent
public void ensureTimestampTableExists() {
cassandraKeyValueService.createTable(
AtlasDbConstants.TIMESTAMP_TABLE,
CassandraTimestampBoundStore.TIMESTAMP_TABLE_METADATA.persistToBytes());
}
/**
* Writes a backup of the existing timestamp to the database, if none exists. After this backup, this timestamp
* service can no longer be used until a restore. Note that the value returned is the value that was backed up;
* multiple calls to this method are safe, and will return the backed up value.
*
* This method assumes that the timestamp table exists.
*
* @return value of the timestamp that was backed up, if applicable
*/
public synchronized long backupExistingTimestamp() {
return clientPool().runWithRetry(client -> {
BoundData boundData = getCurrentBoundData(client);
byte[] currentBound = boundData.bound();
byte[] currentBackupBound = boundData.backupBound();
BoundReadability boundReadability = checkReadability(boundData);
if (boundReadability == BoundReadability.BACKUP) {
log.info(
"[BACKUP] Didn't backup, because there is already a valid backup of {}.",
SafeArg.of("currentBackupBound", PtBytes.toLong(currentBackupBound)));
return PtBytes.toLong(currentBackupBound);
}
byte[] backupValue =
MoreObjects.firstNonNull(currentBound, PtBytes.toBytes(CassandraTimestampUtils.INITIAL_VALUE));
Map<String, Pair<byte[], byte[]>> casMap = ImmutableMap.of(
CassandraTimestampUtils.ROW_AND_COLUMN_NAME,
Pair.create(currentBound, CassandraTimestampUtils.INVALIDATED_VALUE.toByteArray()),
CassandraTimestampUtils.BACKUP_COLUMN_NAME,
Pair.create(currentBackupBound, backupValue));
executeAndVerifyCas(client, casMap);
log.info("[BACKUP] Backed up the value {}", SafeArg.of("backupValue", PtBytes.toLong(backupValue)));
return PtBytes.toLong(backupValue);
});
}
/**
* Restores a backup of an existing timestamp, if possible.
*
* This method assumes that the timestamp table exists.
*/
public synchronized void restoreFromBackup() {
clientPool().runWithRetry(client -> {
BoundData boundData = getCurrentBoundData(client);
byte[] currentBound = boundData.bound();
byte[] currentBackupBound = boundData.backupBound();
BoundReadability boundReadability = checkReadability(boundData);
if (boundReadability == BoundReadability.BOUND) {
if (currentBound == null) {
log.info("[RESTORE] Didn't restore, because the current bound is empty (and thus readable).");
} else {
log.info(
"[RESTORE] Didn't restore, because the current bound is readable with the value {}.",
SafeArg.of("currentBound", PtBytes.toLong(currentBound)));
}
return null;
}
Map<String, Pair<byte[], byte[]>> casMap = ImmutableMap.of(
CassandraTimestampUtils.ROW_AND_COLUMN_NAME,
Pair.create(CassandraTimestampUtils.INVALIDATED_VALUE.toByteArray(), currentBackupBound),
CassandraTimestampUtils.BACKUP_COLUMN_NAME,
Pair.create(currentBackupBound, PtBytes.EMPTY_BYTE_ARRAY));
executeAndVerifyCas(client, casMap);
log.info(
"[RESTORE] Restored the value {}",
SafeArg.of("currentBackupBound", PtBytes.toLong(currentBackupBound)));
return null;
});
}
private BoundReadability checkReadability(BoundData boundData) {
BoundReadability boundReadability = getReadability(boundData);
Preconditions.checkState(
boundReadability != BoundReadability.BOTH,
"We had both backup and active timestamp bounds readable! This is unexpected. Please contact support.");
Preconditions.checkState(
boundReadability != BoundReadability.NEITHER,
"We had an unreadable active timestamp bound with no backup! This is unexpected. Please contact "
+ "support.");
return boundReadability;
}
private BoundReadability getReadability(BoundData boundData) {
boolean boundReadable =
boundData.bound() == null || CassandraTimestampUtils.isValidTimestampData(boundData.bound());
boolean backupBoundReadable = CassandraTimestampUtils.isValidTimestampData(boundData.backupBound());
if (boundReadable) {
return backupBoundReadable ? BoundReadability.BOTH : BoundReadability.BOUND;
}
return backupBoundReadable ? BoundReadability.BACKUP : BoundReadability.NEITHER;
}
private BoundData getCurrentBoundData(CassandraClient client) {
checkTimestampTableExists();
CqlQuery selectQuery = CassandraTimestampUtils.constructSelectFromTimestampTableQuery();
CqlResult existingData = executeQueryUnchecked(client, selectQuery);
Map<String, byte[]> columnarResults = CassandraTimestampUtils.getValuesFromSelectionResult(existingData);
return ImmutableBoundData.builder()
.bound(columnarResults.get(CassandraTimestampUtils.ROW_AND_COLUMN_NAME))
.backupBound(columnarResults.get(CassandraTimestampUtils.BACKUP_COLUMN_NAME))
.build();
}
private void checkTimestampTableExists() {
CassandraTables cassandraTables = cassandraKeyValueService.getCassandraTables();
Preconditions.checkState(
cassandraTables.getExisting().contains(AtlasDbConstants.TIMESTAMP_TABLE.getQualifiedName()),
"[BACKUP/RESTORE] Tried to get timestamp bound data when the timestamp table didn't exist!");
}
private void executeAndVerifyCas(CassandraClient client, Map<String, Pair<byte[], byte[]>> casMap) {
CqlQuery casQueryBuffer = CassandraTimestampUtils.constructCheckAndSetMultipleQuery(casMap);
CqlResult casResult = executeQueryUnchecked(client, casQueryBuffer);
CassandraTimestampUtils.verifyCompatible(casResult, casMap);
}
private CqlResult executeQueryUnchecked(CassandraClient client, CqlQuery query) {
try {
return queryRunner()
.run(
client,
AtlasDbConstants.TIMESTAMP_TABLE,
() -> client.execute_cql3_query(query, Compression.NONE, ConsistencyLevel.QUORUM));
} catch (TException e) {
throw Throwables.rewrapAndThrowUncheckedException(e);
}
}
private CassandraClientPool clientPool() {
return cassandraKeyValueService.getClientPool();
}
private TracingQueryRunner queryRunner() {
return cassandraKeyValueService.getTracingQueryRunner();
}
@Value.Immutable
interface BoundData {
@Nullable
byte[] bound();
@Nullable
byte[] backupBound();
}
private enum BoundReadability {
BOUND,
BACKUP,
BOTH,
NEITHER
}
}
| |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import android.graphics.Rect;
import android.widget.OverScroller;
import com.google.common.annotations.VisibleForTesting;
import org.chromium.base.CalledByNative;
/**
* Takes care of syncing the scroll offset between the Android View system and the
* InProcessViewRenderer.
*
* Unless otherwise values (sizes, scroll offsets) are in physical pixels.
*/
@VisibleForTesting
public class AwScrollOffsetManager {
// Values taken from WebViewClassic.
// The amount of content to overlap between two screens when using pageUp/pageDown methiods.
private static final int PAGE_SCROLL_OVERLAP = 24;
// Standard animated scroll speed.
private static final int STD_SCROLL_ANIMATION_SPEED_PIX_PER_SEC = 480;
// Time for the longest scroll animation.
private static final int MAX_SCROLL_ANIMATION_DURATION_MILLISEC = 750;
// The unit of all the values in this delegate are physical pixels.
public interface Delegate {
// Call View#overScrollBy on the containerView.
void overScrollContainerViewBy(int deltaX, int deltaY, int scrollX, int scrollY,
int scrollRangeX, int scrollRangeY, boolean isTouchEvent);
// Call View#scrollTo on the containerView.
void scrollContainerViewTo(int x, int y);
// Store the scroll offset in the native side. This should really be a simple store
// operation, the native side shouldn't synchronously alter the scroll offset from within
// this call.
void scrollNativeTo(int x, int y);
int getContainerViewScrollX();
int getContainerViewScrollY();
void invalidate();
}
private final Delegate mDelegate;
// Scroll offset as seen by the native side.
private int mNativeScrollX;
private int mNativeScrollY;
// Content size.
private int mContentWidth;
private int mContentHeight;
// Size of the container view.
private int mContainerViewWidth;
private int mContainerViewHeight;
// Whether we're in the middle of processing a touch event.
private boolean mProcessingTouchEvent;
// Whether (and to what value) to update the native side scroll offset after we've finished
// provessing a touch event.
private boolean mApplyDeferredNativeScroll;
private int mDeferredNativeScrollX;
private int mDeferredNativeScrollY;
// Whether (and to what value) to update the container view scroll offset after we've received
// a valid content size.
private boolean mApplyDeferredContainerScrollOnValidContentSize;
private int mDeferredContainerScrollX;
private int mDeferredContainerScrollY;
// The velocity of the last recorded fling,
private int mLastFlingVelocityX;
private int mLastFlingVelocityY;
private OverScroller mScroller;
public AwScrollOffsetManager(Delegate delegate, OverScroller overScroller) {
mDelegate = delegate;
mScroller = overScroller;
}
//----- Scroll range and extent calculation methods -------------------------------------------
public int computeHorizontalScrollRange() {
return Math.max(mContainerViewWidth, mContentWidth);
}
public int computeMaximumHorizontalScrollOffset() {
return computeHorizontalScrollRange() - mContainerViewWidth;
}
public int computeHorizontalScrollOffset() {
return mDelegate.getContainerViewScrollX();
}
public int computeVerticalScrollRange() {
return Math.max(mContainerViewHeight, mContentHeight);
}
public int computeMaximumVerticalScrollOffset() {
return computeVerticalScrollRange() - mContainerViewHeight;
}
public int computeVerticalScrollOffset() {
return mDelegate.getContainerViewScrollY();
}
public int computeVerticalScrollExtent() {
return mContainerViewHeight;
}
//---------------------------------------------------------------------------------------------
// Called when the content size changes. This needs to be the size of the on-screen content and
// therefore we can't use the WebContentsDelegate preferred size.
public void setContentSize(int width, int height) {
mContentWidth = width;
mContentHeight = height;
if (mApplyDeferredContainerScrollOnValidContentSize &&
mContentWidth != 0 && mContentHeight != 0) {
mApplyDeferredContainerScrollOnValidContentSize = false;
scrollContainerViewTo(mDeferredContainerScrollX, mDeferredContainerScrollY);
}
}
// Called when the physical size of the view changes.
public void setContainerViewSize(int width, int height) {
mContainerViewWidth = width;
mContainerViewHeight = height;
}
public void syncScrollOffsetFromOnDraw() {
// Unfortunately apps override onScrollChanged without calling super which is why we need
// to sync the scroll offset on every onDraw.
onContainerViewScrollChanged(mDelegate.getContainerViewScrollX(),
mDelegate.getContainerViewScrollY());
}
public void setProcessingTouchEvent(boolean processingTouchEvent) {
assert mProcessingTouchEvent != processingTouchEvent;
mProcessingTouchEvent = processingTouchEvent;
if (!mProcessingTouchEvent && mApplyDeferredNativeScroll) {
mApplyDeferredNativeScroll = false;
scrollNativeTo(mDeferredNativeScrollX, mDeferredNativeScrollY);
}
}
// Called by the native side to attempt to scroll the container view.
public void scrollContainerViewTo(int x, int y) {
if (mContentWidth == 0 && mContentHeight == 0) {
mApplyDeferredContainerScrollOnValidContentSize = true;
mDeferredContainerScrollX = x;
mDeferredContainerScrollY = y;
return;
}
mApplyDeferredContainerScrollOnValidContentSize = false;
mNativeScrollX = x;
mNativeScrollY = y;
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
final int deltaX = x - scrollX;
final int deltaY = y - scrollY;
final int scrollRangeX = computeMaximumHorizontalScrollOffset();
final int scrollRangeY = computeMaximumVerticalScrollOffset();
// We use overScrollContainerViewBy to be compatible with WebViewClassic which used this
// method for handling both over-scroll as well as in-bounds scroll.
mDelegate.overScrollContainerViewBy(deltaX, deltaY, scrollX, scrollY,
scrollRangeX, scrollRangeY, mProcessingTouchEvent);
}
// Called by the native side to over-scroll the container view.
public void overScrollBy(int deltaX, int deltaY) {
// TODO(mkosiba): Once http://crbug.com/260663 and http://crbug.com/261239 are fixed it
// should be possible to uncomment the following asserts:
// if (deltaX < 0) assert mDelegate.getContainerViewScrollX() == 0;
// if (deltaX > 0) assert mDelegate.getContainerViewScrollX() ==
// computeMaximumHorizontalScrollOffset();
scrollBy(deltaX, deltaY);
}
private void scrollBy(int deltaX, int deltaY) {
if (deltaX == 0 && deltaY == 0) return;
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
final int scrollRangeX = computeMaximumHorizontalScrollOffset();
final int scrollRangeY = computeMaximumVerticalScrollOffset();
// The android.view.View.overScrollBy method is used for both scrolling and over-scrolling
// which is why we use it here.
mDelegate.overScrollContainerViewBy(deltaX, deltaY, scrollX, scrollY,
scrollRangeX, scrollRangeY, mProcessingTouchEvent);
}
private int clampHorizontalScroll(int scrollX) {
scrollX = Math.max(0, scrollX);
scrollX = Math.min(computeMaximumHorizontalScrollOffset(), scrollX);
return scrollX;
}
private int clampVerticalScroll(int scrollY) {
scrollY = Math.max(0, scrollY);
scrollY = Math.min(computeMaximumVerticalScrollOffset(), scrollY);
return scrollY;
}
// Called by the View system as a response to the mDelegate.overScrollContainerViewBy call.
public void onContainerViewOverScrolled(int scrollX, int scrollY, boolean clampedX,
boolean clampedY) {
// Clamp the scroll offset at (0, max).
scrollX = clampHorizontalScroll(scrollX);
scrollY = clampVerticalScroll(scrollY);
mDelegate.scrollContainerViewTo(scrollX, scrollY);
// This is only necessary if the containerView scroll offset ends up being different
// than the one set from native in which case we want the value stored on the native side
// to reflect the value stored in the containerView (and not the other way around).
scrollNativeTo(mDelegate.getContainerViewScrollX(), mDelegate.getContainerViewScrollY());
}
// Called by the View system when the scroll offset had changed. This might not get called if
// the embedder overrides WebView#onScrollChanged without calling super.onScrollChanged. If
// this method does get called it is called both as a response to the embedder scrolling the
// view as well as a response to mDelegate.scrollContainerViewTo.
public void onContainerViewScrollChanged(int x, int y) {
scrollNativeTo(x, y);
}
private void scrollNativeTo(int x, int y) {
x = clampHorizontalScroll(x);
y = clampVerticalScroll(y);
// We shouldn't do the store to native while processing a touch event since that confuses
// the gesture processing logic.
if (mProcessingTouchEvent) {
mDeferredNativeScrollX = x;
mDeferredNativeScrollY = y;
mApplyDeferredNativeScroll = true;
return;
}
if (x == mNativeScrollX && y == mNativeScrollY)
return;
// Updating the native scroll will override any pending scroll originally sent from native.
mApplyDeferredContainerScrollOnValidContentSize = false;
// The scrollNativeTo call should be a simple store, so it's OK to assume it always
// succeeds.
mNativeScrollX = x;
mNativeScrollY = y;
mDelegate.scrollNativeTo(x, y);
}
// Called at the beginning of every fling gesture.
public void onFlingStartGesture(int velocityX, int velocityY) {
mLastFlingVelocityX = velocityX;
mLastFlingVelocityY = velocityY;
}
// Called whenever some other touch interaction requires the fling gesture to be canceled.
public void onFlingCancelGesture() {
// TODO(mkosiba): Support speeding up a fling by flinging again.
// http://crbug.com/265841
mScroller.forceFinished(true);
}
// Called when a fling gesture is not handled by the renderer.
// We explicitly ask the renderer not to handle fling gestures targeted at the root
// scroll layer.
public void onUnhandledFlingStartEvent() {
flingScroll(-mLastFlingVelocityX, -mLastFlingVelocityY);
}
// Starts the fling animation. Called both as a response to a fling gesture and as via the
// public WebView#flingScroll(int, int) API.
public void flingScroll(int velocityX, int velocityY) {
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
final int rangeX = computeMaximumHorizontalScrollOffset();
final int rangeY = computeMaximumVerticalScrollOffset();
mScroller.fling(scrollX, scrollY, velocityX, velocityY,
0, rangeX, 0, rangeY);
mDelegate.invalidate();
}
// Called immediately before the draw to update the scroll offset.
public void computeScrollAndAbsorbGlow(OverScrollGlow overScrollGlow) {
final boolean stillAnimating = mScroller.computeScrollOffset();
if (!stillAnimating) return;
final int oldX = mDelegate.getContainerViewScrollX();
final int oldY = mDelegate.getContainerViewScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
int rangeX = computeMaximumHorizontalScrollOffset();
int rangeY = computeMaximumVerticalScrollOffset();
if (overScrollGlow != null) {
overScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY,
mScroller.getCurrVelocity());
}
// The mScroller is configured not to go outside of the scrollable range, so this call
// should never result in attempting to scroll outside of the scrollable region.
scrollBy(x - oldX, y - oldY);
mDelegate.invalidate();
}
private static int computeDurationInMilliSec(int dx, int dy) {
int distance = Math.max(Math.abs(dx), Math.abs(dy));
int duration = distance * 1000 / STD_SCROLL_ANIMATION_SPEED_PIX_PER_SEC;
return Math.min(duration, MAX_SCROLL_ANIMATION_DURATION_MILLISEC);
}
private boolean animateScrollTo(int x, int y) {
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
x = clampHorizontalScroll(x);
y = clampVerticalScroll(y);
int dx = x - scrollX;
int dy = y - scrollY;
if (dx == 0 && dy == 0)
return false;
mScroller.startScroll(scrollX, scrollY, dx, dy, computeDurationInMilliSec(dx, dy));
mDelegate.invalidate();
return true;
}
/**
* See {@link WebView#pageUp(boolean)}
*/
public boolean pageUp(boolean top) {
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
if (top) {
// go to the top of the document
return animateScrollTo(scrollX, 0);
}
int dy = -mContainerViewHeight / 2;
if (mContainerViewHeight > 2 * PAGE_SCROLL_OVERLAP) {
dy = -mContainerViewHeight + PAGE_SCROLL_OVERLAP;
}
// animateScrollTo clamps the argument to the scrollable range so using (scrollY + dy) is
// fine.
return animateScrollTo(scrollX, scrollY + dy);
}
/**
* See {@link WebView#pageDown(boolean)}
*/
public boolean pageDown(boolean bottom) {
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
if (bottom) {
return animateScrollTo(scrollX, computeVerticalScrollRange());
}
int dy = mContainerViewHeight / 2;
if (mContainerViewHeight > 2 * PAGE_SCROLL_OVERLAP) {
dy = mContainerViewHeight - PAGE_SCROLL_OVERLAP;
}
// animateScrollTo clamps the argument to the scrollable range so using (scrollY + dy) is
// fine.
return animateScrollTo(scrollX, scrollY + dy);
}
/**
* See {@link WebView#requestChildRectangleOnScreen(View, Rect, boolean)}
*/
public boolean requestChildRectangleOnScreen(int childOffsetX, int childOffsetY, Rect rect,
boolean immediate) {
// TODO(mkosiba): WebViewClassic immediately returns false if a zoom animation is
// in progress. We currently can't tell if one is happening.. should we instead cancel any
// scroll animation when the size/pageScaleFactor changes?
// TODO(mkosiba): Take scrollbar width into account in the screenRight/screenBotton
// calculations. http://crbug.com/269032
final int scrollX = mDelegate.getContainerViewScrollX();
final int scrollY = mDelegate.getContainerViewScrollY();
rect.offset(childOffsetX, childOffsetY);
int screenTop = scrollY;
int screenBottom = scrollY + mContainerViewHeight;
int scrollYDelta = 0;
if (rect.bottom > screenBottom) {
int oneThirdOfScreenHeight = mContainerViewHeight / 3;
if (rect.width() > 2 * oneThirdOfScreenHeight) {
// If the rectangle is too tall to fit in the bottom two thirds
// of the screen, place it at the top.
scrollYDelta = rect.top - screenTop;
} else {
// If the rectangle will still fit on screen, we want its
// top to be in the top third of the screen.
scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
}
} else if (rect.top < screenTop) {
scrollYDelta = rect.top - screenTop;
}
int screenLeft = scrollX;
int screenRight = scrollX + mContainerViewWidth;
int scrollXDelta = 0;
if (rect.right > screenRight && rect.left > screenLeft) {
if (rect.width() > mContainerViewWidth) {
scrollXDelta += (rect.left - screenLeft);
} else {
scrollXDelta += (rect.right - screenRight);
}
} else if (rect.left < screenLeft) {
scrollXDelta -= (screenLeft - rect.left);
}
if (scrollYDelta == 0 && scrollXDelta == 0) {
return false;
}
if (immediate) {
scrollBy(scrollXDelta, scrollYDelta);
return true;
} else {
return animateScrollTo(scrollX + scrollXDelta, scrollY + scrollYDelta);
}
}
}
| |
package org.leguan.language.gradle;
import org.apache.commons.io.FileUtils;
import org.leguan.language.file.GenericFile;
import org.leguan.language.file.structured.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
public class GradleFile extends AbstractStructuredFile {
/**
* configuration how to read/write the gradle file
*/
private GradleFileStrategies gradlefileStrategies;
/**
* constructor to create gradle file from file
* @param gradleFileStrategies configuration
* @param genericFile file to read from
*/
public GradleFile (final GradleFileStrategies gradleFileStrategies, GenericFile genericFile) {
super (genericFile);
this.gradlefileStrategies = gradleFileStrategies;
read(genericFile.getContent());
}
/**
* constructor to create gradle file from file with default configuration
* @param genericFile file to read from
*/
public GradleFile(final GenericFile genericFile) {
this (new GradleFileStrategies(), genericFile);
}
/**
* constructor to create an empty gradlefile with default configuration
*/
public GradleFile () {
this (new GradleFileStrategies(), "");
}
/**
* constructor to create an empty gradlefile
* @param gradleFileStrategies configuration which contains info how the file is read / written
*/
public GradleFile (final GradleFileStrategies gradleFileStrategies) {
this (gradleFileStrategies, "");
}
/**
* constructor to create gradlefile from string with default configuration
* @param content content as string
*/
public GradleFile(String content) {
this (new GradleFileStrategies(), content);
}
/**
* constructor to create gradlefile from string
* @param gradleFileStrategies configuration
* @param content content as string
*/
public GradleFile(final GradleFileStrategies gradleFileStrategies, String content) {
this.gradlefileStrategies = gradleFileStrategies;
read(content);
}
/**
* getter
* @return the configuration to read the gradle file
*/
public GradleFileStrategies getGradleFileStrategies() {
return gradlefileStrategies;
}
@Override
protected boolean trimEmptyBlocks() {
return gradlefileStrategies.isOptimizeEmptyClosures();
}
@Override
protected String getOpeningToken() {
return "{";
}
@Override
protected String getClosingToken() {
return "}";
}
@Override
protected String getNextToken() {
return "\n";
}
@Override
protected String getBlockName(String text) {
String [] nameTokens = text.trim().split("\n");
if (nameTokens.length == 0)
return null;
else
return nameTokens [nameTokens.length - 1];
}
@Override
protected String getOneLineCommentToken() {
return "//";
}
@Override
protected String getMultiLineCommentOpeningToken() {
return "/*";
}
@Override
protected String getMultiLineCommentClosingToken() {
return "*/";
}
@Override
protected String getSingleQuotedStringToken() {
return "'";
}
@Override
protected String getDoubleQuotedStringToken() {
return "\"";
}
/**
* getter
* @return spring dependency management block, if available
*/
public ContentNodeHolder getSpringDependencyManagement () {
List<ContentNodeHolder> closures = getContentNodeHolder().createNodeHolderContainer().filterByName("dependencyManagement").getAllItems();
if (closures.size() == 1)
return closures.get(0);
else
return null;
}
/**
* getter
* @return dependencies block, if available
*/
public ContentNodeHolder getDependencies () {
return findContentNodeHolder("dependencies");
}
/**
* getter
* @return buildscript block, if available
*/
public ContentNodeHolder getBuildscriptDependencies () {
return findContentNodeHolder("buildscript.dependencies");
}
/**
* get list of applied plugins of the gradle file
* @return list of plugin names
*/
public List<String> getAppliedPlugins () {
List<String> plugins = new ArrayList<>();
ContentNodeHolder extension = getContentNodeHolder().findContentNodeHolder("apply");
if (extension == null)
return Collections.EMPTY_LIST;
for (String nextLine: extension.getDirectContent()) {
if (nextLine.contains("plugin")) {
nextLine = nextLine.replace("plugin", "");
nextLine = nextLine.replaceAll("[^A-Za-z.\\-_]+", "");
plugins.add(nextLine);
}
}
return plugins;
}
public String toString () {
return getContentNodeHolder().toString();
}
/**
* saves the gradle file
*/
public void save() {
try {
FileUtils.writeStringToFile(getGenericFile().getFile(), toString(), Charset.defaultCharset());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* gets the ordering mechanism for the content holders to sort the content holders
* @return ordering mechanism for the content holders
*/
public ContentNodeHolderSorter getContentNodeHolderSorter() {
if (gradlefileStrategies.getOrderedHolders() == null || gradlefileStrategies.getOrderedHolders().isEmpty())
return null;
else
return new ContentNodeHolderSorterByName(gradlefileStrategies.getOrderedHolders());
}
/**
* gets the ordering mechanism of the node content itself
* @return ordering mechanism for the content of the node holders
*/
public ContentNodeTextSorter getContentNodeTextSorter () {
return new ContentNodeTextSorterAlphabetical(gradlefileStrategies.getContentOfHoldersOrdered());
}
}
| |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package rr.org.objectweb.asm.commons;
import java.util.HashMap;
import java.util.Map;
import rr.org.objectweb.asm.Type;
import rr.org.objectweb.asm.commons.Method;
/**
* A named method descriptor.
*
* @author Juozas Baliuka
* @author Chris Nokleberg
* @author Eric Bruneton
*/
public class Method {
/**
* The method name.
*/
private final String name;
/**
* The method descriptor.
*/
private final String desc;
/**
* Maps primitive Java type names to their descriptors.
*/
private static final Map<String, String> DESCRIPTORS;
static {
DESCRIPTORS = new HashMap<String, String>();
DESCRIPTORS.put("void", "V");
DESCRIPTORS.put("byte", "B");
DESCRIPTORS.put("char", "C");
DESCRIPTORS.put("double", "D");
DESCRIPTORS.put("float", "F");
DESCRIPTORS.put("int", "I");
DESCRIPTORS.put("long", "J");
DESCRIPTORS.put("short", "S");
DESCRIPTORS.put("boolean", "Z");
}
/**
* Creates a new {@link Method}.
*
* @param name
* the method's name.
* @param desc
* the method's descriptor.
*/
public Method(final String name, final String desc) {
this.name = name;
this.desc = desc;
}
/**
* Creates a new {@link Method}.
*
* @param name
* the method's name.
* @param returnType
* the method's return type.
* @param argumentTypes
* the method's argument types.
*/
public Method(final String name, final Type returnType,
final Type[] argumentTypes) {
this(name, Type.getMethodDescriptor(returnType, argumentTypes));
}
/**
* Creates a new {@link Method}.
*
* @param m
* a java.lang.reflect method descriptor
* @return a {@link Method} corresponding to the given Java method
* declaration.
*/
public static Method getMethod(java.lang.reflect.Method m) {
return new Method(m.getName(), Type.getMethodDescriptor(m));
}
/**
* Creates a new {@link Method}.
*
* @param c
* a java.lang.reflect constructor descriptor
* @return a {@link Method} corresponding to the given Java constructor
* declaration.
*/
public static Method getMethod(java.lang.reflect.Constructor<?> c) {
return new Method("<init>", Type.getConstructorDescriptor(c));
}
/**
* Returns a {@link Method} corresponding to the given Java method
* declaration.
*
* @param method
* a Java method declaration, without argument names, of the form
* "returnType name (argumentType1, ... argumentTypeN)", where
* the types are in plain Java (e.g. "int", "float",
* "java.util.List", ...). Classes of the java.lang package can
* be specified by their unqualified name; all other classes
* names must be fully qualified.
* @return a {@link Method} corresponding to the given Java method
* declaration.
* @throws IllegalArgumentException
* if <code>method</code> could not get parsed.
*/
public static Method getMethod(final String method)
throws IllegalArgumentException {
return getMethod(method, false);
}
/**
* Returns a {@link Method} corresponding to the given Java method
* declaration.
*
* @param method
* a Java method declaration, without argument names, of the form
* "returnType name (argumentType1, ... argumentTypeN)", where
* the types are in plain Java (e.g. "int", "float",
* "java.util.List", ...). Classes of the java.lang package may
* be specified by their unqualified name, depending on the
* defaultPackage argument; all other classes names must be fully
* qualified.
* @param defaultPackage
* true if unqualified class names belong to the default package,
* or false if they correspond to java.lang classes. For instance
* "Object" means "Object" if this option is true, or
* "java.lang.Object" otherwise.
* @return a {@link Method} corresponding to the given Java method
* declaration.
* @throws IllegalArgumentException
* if <code>method</code> could not get parsed.
*/
public static Method getMethod(final String method,
final boolean defaultPackage) throws IllegalArgumentException {
int space = method.indexOf(' ');
int start = method.indexOf('(', space) + 1;
int end = method.indexOf(')', start);
if (space == -1 || start == -1 || end == -1) {
throw new IllegalArgumentException();
}
String returnType = method.substring(0, space);
String methodName = method.substring(space + 1, start - 1).trim();
StringBuilder sb = new StringBuilder();
sb.append('(');
int p;
do {
String s;
p = method.indexOf(',', start);
if (p == -1) {
s = map(method.substring(start, end).trim(), defaultPackage);
} else {
s = map(method.substring(start, p).trim(), defaultPackage);
start = p + 1;
}
sb.append(s);
} while (p != -1);
sb.append(')');
sb.append(map(returnType, defaultPackage));
return new Method(methodName, sb.toString());
}
private static String map(final String type, final boolean defaultPackage) {
if ("".equals(type)) {
return type;
}
StringBuilder sb = new StringBuilder();
int index = 0;
while ((index = type.indexOf("[]", index) + 1) > 0) {
sb.append('[');
}
String t = type.substring(0, type.length() - sb.length() * 2);
String desc = DESCRIPTORS.get(t);
if (desc != null) {
sb.append(desc);
} else {
sb.append('L');
if (t.indexOf('.') < 0) {
if (!defaultPackage) {
sb.append("java/lang/");
}
sb.append(t);
} else {
sb.append(t.replace('.', '/'));
}
sb.append(';');
}
return sb.toString();
}
/**
* Returns the name of the method described by this object.
*
* @return the name of the method described by this object.
*/
public String getName() {
return name;
}
/**
* Returns the descriptor of the method described by this object.
*
* @return the descriptor of the method described by this object.
*/
public String getDescriptor() {
return desc;
}
/**
* Returns the return type of the method described by this object.
*
* @return the return type of the method described by this object.
*/
public Type getReturnType() {
return Type.getReturnType(desc);
}
/**
* Returns the argument types of the method described by this object.
*
* @return the argument types of the method described by this object.
*/
public Type[] getArgumentTypes() {
return Type.getArgumentTypes(desc);
}
@Override
public String toString() {
return name + desc;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof Method)) {
return false;
}
Method other = (Method) o;
return name.equals(other.name) && desc.equals(other.desc);
}
@Override
public int hashCode() {
return name.hashCode() ^ desc.hashCode();
}
}
| |
package hyweb.jo.org.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from
* it. It is used by the JSONObject and JSONArray constructors to parse
* JSON source strings.
* @author JSON.org
* @version 2014-05-03
*/
public class JSONTokener {
private long character;
private boolean eof;
private long index;
private long line;
private char previous;
private Reader reader;
private boolean usePrevious;
/**
* Construct a JSONTokener from a Reader.
*
* @param reader A reader.
*/
public JSONTokener(Reader reader) {
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.line = 1;
}
/**
* Construct a JSONTokener from an InputStream.
* @param inputStream The source.
*/
public JSONTokener(InputStream inputStream) throws JSONException {
this(new InputStreamReader(inputStream));
}
/**
* Construct a JSONTokener from a string.
*
* @param s A source string.
*/
public JSONTokener(String s) {
this(new StringReader(s));
}
/**
* Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse
* the next number or identifier.
*/
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
}
/**
* Get the hex value of a character (base16).
* @param c A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
public boolean end() {
return this.eof && !this.usePrevious;
}
/**
* Determine if the source string still contains characters that next()
* can consume.
* @return true if not yet at the end of the source.
*/
public boolean more() throws JSONException {
this.next();
if (this.end()) {
return false;
}
this.back();
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
*/
public char next() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (IOException exception) {
throw new JSONException(exception);
}
if (c <= 0) { // End of stream
this.eof = true;
c = 0;
}
}
this.index += 1;
if (this.previous == '\r') {
this.line += 1;
this.character = c == '\n' ? 0 : 1;
} else if (c == '\n') {
this.line += 1;
this.character = 0;
} else {
this.character += 1;
}
this.previous = (char) c;
return this.previous;
}
/**
* Consume the next character, and check that it matches a specified
* character.
* @param c The character to match.
* @return The character.
* @throws JSONException if the character does not match.
*/
public char next(char c) throws JSONException {
char n = this.next();
if (n != c) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" +
n + "'");
}
return n;
}
/**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @throws JSONException
* Substring bounds error if there are not
* n characters remaining in the source string.
*/
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
* @throws JSONException
* @return A character, or 0 if there are no more characters.
*/
public char nextClean() throws JSONException {
for (;;) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
}
/**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
* allow strings in single quotes, but an implementation is allowed to
* accept them.
* @param quote The quoting character, either
* <code>"</code> <small>(double quote)</small> or
* <code>'</code> <small>(single quote)</small>.
* @return A String.
* @throws JSONException Unterminated string.
*/
public String nextString(char quote) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
c = this.next();
switch (c) {
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
case '\\':
c = this.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
String hex = this.next(4);
System.out.println(hex);
sb.append((char)Integer.parseInt(hex, 16));
break;
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
}
break;
default:
if (c == quote) {
return sb.toString();
}
sb.append(c);
}
}
}
/**
* Get the text up but not including the specified character or the
* end of line, whichever comes first.
* @param delimiter A delimiter character.
* @return A string.
*/
public String nextTo(char delimiter) throws JSONException {
StringBuilder sb = new StringBuilder();
for (;;) {
char c = this.next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) {
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the text up but not including one of the specified delimiter
* characters or the end of line, whichever comes first.
* @param delimiters A set of delimiter characters.
* @return A string, trimmed.
*/
public String nextTo(String delimiters) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
c = this.next();
if (delimiters.indexOf(c) >= 0 || c == 0 ||
c == '\n' || c == '\r') {
if (c != 0) {
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the next value. The value can be a Boolean, Double, Integer,
* JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
* @throws JSONException If syntax error.
*
* @return An object.
*/
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
// return JSONObject.check_date_or_string(this.nextString(c));
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
/**
* Skip characters until the next character is the requested character.
* If the requested character is not found, no characters are skipped.
* @param to A character to skip to.
* @return The requested character, or zero if the requested character
* is not found.
*/
public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exception) {
throw new JSONException(exception);
}
this.back();
return c;
}
/**
* Make a JSONException to signal a syntax error.
*
* @param message The error message.
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(String message) {
return new JSONException(message + this.toString());
}
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
public String toString() {
return " at " + this.index + " [character " + this.character + " line " +
this.line + "]";
}
}
| |
package firestream.chat.realtime;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.Query;
import com.google.firebase.database.ServerValue;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import firestream.chat.chat.User;
import firestream.chat.events.ListData;
import firestream.chat.firebase.service.FirebaseCoreHandler;
import firestream.chat.firebase.service.Keys;
import firestream.chat.firebase.service.Path;
import firestream.chat.message.Body;
import firestream.chat.message.Sendable;
import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.MaybeSource;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import sdk.guru.common.Event;
import sdk.guru.common.Optional;
import sdk.guru.common.RX;
import sdk.guru.realtime.DocumentChange;
import sdk.guru.realtime.Generic;
import sdk.guru.realtime.RXRealtime;
public class RealtimeCoreHandler extends FirebaseCoreHandler {
@Override
public Observable<Event<ListData>> listChangeOn(Path path) {
return new RXRealtime().childOn(Ref.get(path)).flatMapMaybe((Function<DocumentChange, MaybeSource<Event<ListData>>>) change -> {
DataSnapshot snapshot = change.getSnapshot();
Map<String, Object> data = snapshot.getValue(Generic.hashMapStringObject());
if (data != null) {
return Maybe.just(new Event<>(new ListData(change.getSnapshot().getKey(), data), change.getType()));
}
return Maybe.empty();
});
}
@Override
public Completable deleteSendable(Path messagesPath) {
return new RXRealtime().delete(Ref.get(messagesPath));
}
@Override
public Completable send(Path messagesPath, Sendable sendable, Consumer<String> newId) {
return new RXRealtime().add(Ref.get(messagesPath), sendable.toData(), timestamp(), newId).ignoreElement();
}
@Override
public Completable addUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return addBatch(path, idsForUsers(users), dataForUsers(users, dataProvider));
}
@Override
public Completable removeUsers(Path path, List<? extends User> users) {
return removeBatch(path, idsForUsers(users));
}
@Override
public Completable updateUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return updateBatch(path, idsForUsers(users), dataForUsers(users, dataProvider));
}
@Override
public Single<List<Sendable>> loadMoreMessages(Path messagesPath, @Nullable Date fromDate, @Nullable Date toDate, @Nullable Integer limit) {
return Single.create((SingleOnSubscribe<Query>) emitter -> {
Query query = Ref.get(messagesPath);
query = query.orderByChild(Keys.Date);
if (fromDate != null) {
query = query.startAt(fromDate.getTime(), Keys.Date);
}
if(toDate != null) {
query = query.endAt(toDate.getTime(), Keys.Date);
}
if (limit != null) {
if (fromDate != null) {
query = query.limitToFirst(limit);
}
if (toDate != null) {
query = query.limitToLast(limit);
}
}
emitter.onSuccess(query);
}).flatMap(query -> new RXRealtime().get(query)).map(optional -> {
List<Sendable> sendables = new ArrayList<>();
if (!optional.isEmpty()) {
DataSnapshot snapshot = optional.get();
if (snapshot.exists()) {
for (DataSnapshot child: snapshot.getChildren()) {
Sendable sendable = sendableFromSnapshot(child);
if (sendable != null) {
sendables.add(sendable);
}
}
}
}
return sendables;
});
}
@Override
public Single<Optional<Sendable>> lastMessage(Path messagesPath) {
return Single.defer(() -> {
Query query = Ref.get(messagesPath);
query = query.orderByChild(Keys.Date);
query = query.limitToLast(1);
return new RXRealtime().get(query).map(optional -> {
if (!optional.isEmpty()) {
for (DataSnapshot snapshot: optional.get().getChildren()) {
Sendable sendable = sendableFromSnapshot(snapshot);
return Optional.with(sendable);
}
}
return Optional.empty();
});
});
}
public Sendable sendableFromSnapshot(DataSnapshot snapshot) {
Sendable sendable = new Sendable();
sendable.setId(snapshot.getKey());
if (snapshot.hasChild(Keys.From)) {
sendable.setFrom(snapshot.child(Keys.From).getValue(String.class));
}
if (snapshot.hasChild(Keys.Date)) {
Long timestamp = snapshot.child(Keys.Date).getValue(Long.class);
if (timestamp != null) {
sendable.setDate(new Date(timestamp));
}
}
if (snapshot.hasChild(Keys.Type)) {
sendable.setType(snapshot.child(Keys.Type).getValue(String.class));
}
if (snapshot.hasChild(Keys.Body)) {
Map<String, Object> body = snapshot.child(Keys.Body).getValue(Generic.hashMapStringObject());
if (body != null) {
sendable.setBody(new Body(body));
}
}
return sendable;
}
@Override
public Observable<Event<Sendable>> messagesOn(Path messagesPath, Date newerThan) {
return Single.create((SingleOnSubscribe<Query>) emitter -> {
Query query = Ref.get(messagesPath);
query = query.orderByChild(Keys.Date);
if (newerThan != null) {
query = query.startAt(newerThan.getTime(), Keys.Date);
}
emitter.onSuccess(query);
}).flatMapObservable(query -> new RXRealtime().childOn(query).flatMapMaybe(change -> {
Sendable sendable = sendableFromSnapshot(change.getSnapshot());
if (sendable != null) {
return Maybe.just(new Event<>(sendable, change.getType()));
}
return Maybe.empty();
}));
}
@Override
public Object timestamp() {
return ServerValue.TIMESTAMP;
}
protected Completable removeBatch(Path path, List<String> keys) {
return updateBatch(path, keys, null);
}
protected Completable addBatch(Path path, List<String> keys, @Nullable List<Map<String, Object>> values) {
return updateBatch(path, keys, values);
}
protected Completable updateBatch(Path path, List<String> keys, @Nullable List<Map<String, Object>> values) {
return Completable.create(emitter -> {
Map<String, Object> data = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
Map<String, Object> value = values != null ? values.get(i) : null;
data.put(path.toString() + "/" + key, value);
}
Task<Void> task = Ref.db().getReference().updateChildren(data);
task.addOnSuccessListener(aVoid -> emitter.onComplete()).addOnFailureListener(emitter::onError);
}).subscribeOn(RX.io());
}
protected List<String> idsForUsers(List<? extends User> users) {
List<String> ids = new ArrayList<>();
for (User u: users) {
ids.add(u.getId());
}
return ids;
}
protected List<Map<String, Object>> dataForUsers(List<? extends User> users, User.DataProvider provider) {
List<Map<String, Object>> data = new ArrayList<>();
for (User u: users) {
data.add(provider.data(u));
}
return data;
}
public Completable mute(Path path, Map<String, Object> data) {
return new RXRealtime().set(Ref.get(path), data);
}
public Completable unmute(Path path) {
return new RXRealtime().delete(Ref.get(path));
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.hhs.fha.nhinc.adaptercomponentmpi;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.hl7.v3.*;
import java.io.Serializable;
import java.util.Iterator;
import static org.junit.Assert.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Jon Hoppesch
*/
public class TestHelper {
private static Log log = LogFactory.getLog(TestHelper.class);
public static void AssertPatientIdsAreSame(PRPAIN201306UV02 expected, PRPAIN201306UV02 result) {
AssertPatientNotNull(expected);
AssertPatientNotNull(result);
AssertPatientIdsEqual(expected.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient(),
result.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient());
}
public static void AssertPatientNamesAreSame(PRPAIN201306UV02 expected, PRPAIN201306UV02 result) {
AssertPatientPersonNotNull(expected);
AssertPatientPersonNotNull(result);
AssertPatientNamesEqual(expected.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue(),
result.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue());
}
public static void AssertPatientGendersAreSame(PRPAIN201306UV02 expected, PRPAIN201306UV02 result) {
AssertPatientPersonNotNull(expected);
AssertPatientPersonNotNull(result);
AssertPatientGendersEqual(expected.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue(),
result.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue());
}
public static void AssertPatientBdaysAreSame(PRPAIN201306UV02 expected, PRPAIN201306UV02 result) {
AssertPatientPersonNotNull(expected);
AssertPatientPersonNotNull(result);
AssertPatientBdaysEqual(expected.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue(),
result.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue());
}
public static void AssertPatientNamesEqual(PRPAMT201310UV02Person patient1, PRPAMT201310UV02Person patient2) {
assertNotNull(patient1.getName());
assertNotNull(patient1.getName().get(0));
assertNotNull(patient1.getName().get(0).getContent());
assertNotNull(patient2.getName());
assertNotNull(patient2.getName().get(0));
assertNotNull(patient2.getName().get(0).getContent());
String pat1Name = extractName (patient1.getName().get(0));
log.info("Patient 1 name:" + pat1Name);
String pat2Name = extractName (patient2.getName().get(0));
log.info("Patient 2 name:" + pat2Name);
assertEquals(pat1Name, pat2Name);
}
private static String extractName (PNExplicit name) {
String nameString = "";
Boolean hasName = false;
List<Serializable> choice = name.getContent();
Iterator<Serializable> iterSerialObjects = choice.iterator();
EnExplicitFamily familyName = new EnExplicitFamily();
EnExplicitGiven givenName = new EnExplicitGiven();
while (iterSerialObjects.hasNext()) {
Serializable contentItem = iterSerialObjects.next();
if (contentItem instanceof JAXBElement) {
JAXBElement oJAXBElement = (JAXBElement) contentItem;
if (oJAXBElement.getValue() instanceof EnExplicitFamily) {
familyName = (EnExplicitFamily) oJAXBElement.getValue();
hasName = true;
} else if (oJAXBElement.getValue() instanceof EnExplicitGiven) {
givenName = (EnExplicitGiven) oJAXBElement.getValue();
hasName = true;
}
}
}
if (hasName == true) {
nameString = familyName.getContent() + " " + givenName.getContent();
System.out.println(nameString);
}
return nameString;
}
public static void AssertPatientGendersEqual(PRPAMT201310UV02Person patient1, PRPAMT201310UV02Person patient2) {
assertNotNull(patient1.getAdministrativeGenderCode());
assertNotNull(patient1.getAdministrativeGenderCode().getCode());
assertNotNull(patient2.getAdministrativeGenderCode());
assertNotNull(patient1.getAdministrativeGenderCode().getCode());
assertEquals(patient1.getAdministrativeGenderCode().getCode(), patient1.getAdministrativeGenderCode().getCode());
}
public static void AssertPatientBdaysEqual(PRPAMT201310UV02Person patient1, PRPAMT201310UV02Person patient2) {
assertNotNull(patient1.getBirthTime());
assertNotNull(patient1.getBirthTime().getValue());
assertNotNull(patient2.getBirthTime());
assertNotNull(patient2.getBirthTime().getValue());
assertEquals(patient1.getBirthTime().getValue(), patient2.getBirthTime().getValue());
}
public static void AssertPatientIdsEqual(PRPAMT201310UV02Patient patient1, PRPAMT201310UV02Patient patient2) {
AssertPatientIdNotNull(patient1);
AssertPatientIdNotNull(patient2);
assertEquals(patient1.getId().get(0).getRoot(), patient1.getId().get(0).getRoot());
assertEquals(patient1.getId().get(0).getExtension(), patient1.getId().get(0).getExtension());
}
public static void AssertPatientIdNotNull(PRPAMT201310UV02Patient patient) {
assertNotNull(patient.getId());
assertNotNull(patient.getId().get(0));
assertNotNull(patient.getId().get(0).getRoot());
assertNotNull(patient.getId().get(0).getExtension());
}
public static void AssertPatientPersonNotNull(PRPAIN201306UV02 queryResp) {
AssertPatientNotNull(queryResp);
assertNotNull(queryResp.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson());
assertNotNull(queryResp.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient().getPatientPerson().getValue());
}
public static void AssertPatientNotNull(PRPAIN201306UV02 queryResp) {
assertNotNull(queryResp);
assertNotNull(queryResp.getControlActProcess());
assertNotNull(queryResp.getControlActProcess().getSubject());
assertNotNull(queryResp.getControlActProcess().getSubject().get(0));
assertNotNull(queryResp.getControlActProcess().getSubject().get(0).getRegistrationEvent());
assertNotNull(queryResp.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1());
assertNotNull(queryResp.getControlActProcess().getSubject().get(0).getRegistrationEvent().getSubject1().getPatient());
}
public static PRPAIN201305UV02 build201305(String firstName, String lastName, String gender, String birthTime, II subjectId) {
PRPAIN201305UV02 msg = new PRPAIN201305UV02();
// Set up message header fields
msg.setITSVersion("XML_1.0");
II id = new II();
id.setRoot("1.1");
msg.setId(id);
TSExplicit creationTime = new TSExplicit();
creationTime.setValue("20090202000000");
msg.setCreationTime(creationTime);
II interactionId = new II();
interactionId.setRoot("2.16.840.1.113883.1.6");
interactionId.setExtension("PRPA_IN201305UV02");
msg.setInteractionId(id);
CS processingCode = new CS();
processingCode.setCode("P");
msg.setProcessingCode(processingCode);
CS processingModeCode = new CS();
processingModeCode.setCode("R");
msg.setProcessingModeCode(processingModeCode);
CS ackCode = new CS();
ackCode.setCode("AL");
msg.setAcceptAckCode(ackCode);
// Set the receiver and sender
msg.getReceiver().add(createReceiver());
msg.setSender(createSender());
msg.setControlActProcess(createControlActProcess(firstName, lastName, gender, birthTime, subjectId));
return msg;
}
private static PRPAIN201305UV02QUQIMT021001UV01ControlActProcess createControlActProcess(String firstName, String lastName, String gender, String birthTime, II subjectId) {
PRPAIN201305UV02QUQIMT021001UV01ControlActProcess controlActProcess = new PRPAIN201305UV02QUQIMT021001UV01ControlActProcess();
controlActProcess.setMoodCode(XActMoodIntentEvent.EVN);
CD code = new CD();
code.setCode("PRPA_TE201305UV0202");
code.setCodeSystem("2.16.840.1.113883.1.6");
controlActProcess.setCode(code);
controlActProcess.setQueryByParameter(createQueryParams(firstName, lastName, gender, birthTime, subjectId));
return controlActProcess;
}
private static JAXBElement<PRPAMT201306UV02QueryByParameter> createQueryParams(String firstName, String lastName, String gender, String birthTime, II subjectId) {
PRPAMT201306UV02QueryByParameter params = new PRPAMT201306UV02QueryByParameter();
II id = new II();
id.setRoot("12345");
params.setQueryId(id);
CS statusCode = new CS();
statusCode.setCode("new");
params.setStatusCode(statusCode);
params.setParameterList(createParamList(firstName, lastName, gender, birthTime, subjectId));
javax.xml.namespace.QName xmlqname = new javax.xml.namespace.QName("urn:hl7-org:v3", "queryByParameter");
JAXBElement<PRPAMT201306UV02QueryByParameter> queryParams = new JAXBElement<PRPAMT201306UV02QueryByParameter>(xmlqname, PRPAMT201306UV02QueryByParameter.class, params);
return queryParams;
}
private static PRPAMT201306UV02ParameterList createParamList(String firstName, String lastName, String gender, String birthTime, II subjectId) {
PRPAMT201306UV02ParameterList paramList = new PRPAMT201306UV02ParameterList();
// Set the Subject Gender Code
paramList.getLivingSubjectAdministrativeGender().add(createGender(gender));
// Set the Subject Birth Time
paramList.getLivingSubjectBirthTime().add(createBirthTime(birthTime));
// Set the Subject Name
paramList.getLivingSubjectName().add(createName(firstName, lastName));
// Set the subject Id
paramList.getLivingSubjectId().add(createSubjectId(subjectId));
return paramList;
}
private static PRPAMT201306UV02LivingSubjectId createSubjectId(II subjectId) {
PRPAMT201306UV02LivingSubjectId id = new PRPAMT201306UV02LivingSubjectId();
if (subjectId != null) {
id.getValue().add(subjectId);
}
return id;
}
private static PRPAMT201306UV02LivingSubjectName createName(String firstName, String lastName) {
PRPAMT201306UV02LivingSubjectName subjectName = new PRPAMT201306UV02LivingSubjectName();
org.hl7.v3.ObjectFactory factory = new org.hl7.v3.ObjectFactory();
ENExplicit name = (ENExplicit) (factory.createENExplicit());
List namelist = name.getContent();
if (lastName != null &&
lastName.length() > 0) {
EnExplicitFamily familyName = new EnExplicitFamily();
familyName.setPartType("FAM");
familyName.setContent(lastName);
namelist.add(factory.createENExplicitFamily(familyName));
}
if (firstName != null &&
firstName.length() > 0) {
EnExplicitGiven givenName = new EnExplicitGiven();
givenName.setPartType("GIV");
givenName.setContent(firstName);
namelist.add(factory.createENExplicitGiven(givenName));
}
subjectName.getValue().add(name);
return subjectName;
}
private static PRPAMT201306UV02LivingSubjectBirthTime createBirthTime(String birthTime) {
PRPAMT201306UV02LivingSubjectBirthTime subjectBirthTime = new PRPAMT201306UV02LivingSubjectBirthTime();
IVLTSExplicit bday = new IVLTSExplicit();
if (birthTime != null &&
birthTime.length() > 0) {
bday.setValue(birthTime);
subjectBirthTime.getValue().add(bday);
}
return subjectBirthTime;
}
private static PRPAMT201306UV02LivingSubjectAdministrativeGender createGender(String gender) {
PRPAMT201306UV02LivingSubjectAdministrativeGender adminGender = new PRPAMT201306UV02LivingSubjectAdministrativeGender();
CE genderCode = new CE();
if (gender != null &&
gender.length() > 0) {
genderCode.setCode(gender);
adminGender.getValue().add(genderCode);
}
return adminGender;
}
private static MCCIMT000100UV01Receiver createReceiver() {
MCCIMT000100UV01Receiver receiver = new MCCIMT000100UV01Receiver();
receiver.setTypeCode(CommunicationFunctionType.RCV);
MCCIMT000100UV01Device device = new MCCIMT000100UV01Device();
device.setDeterminerCode("INSTANCE");
II id = new II();
id.setRoot("2.16.840.1.113883.3.200");
device.getId().add(id);
TELExplicit url = new TELExplicit();
url.setValue("http://localhost:9080/NhinConnect/AdapterComponentMpiService");
device.getTelecom().add(url);
receiver.setDevice(device);
return receiver;
}
private static MCCIMT000100UV01Sender createSender() {
MCCIMT000100UV01Sender sender = new MCCIMT000100UV01Sender();
sender.setTypeCode(CommunicationFunctionType.SND);
MCCIMT000100UV01Device device = new MCCIMT000100UV01Device();
device.setDeterminerCode("INSTANCE");
II id = new II();
id.setRoot("2.16.840.1.113883.3.200");
device.getId().add(id);
sender.setDevice(device);
return sender;
}
public static PRPAMT201310UV02Patient createMpiPatient(String firstName, String lastName, String gender, String birthTime, II subjectId) {
PRPAMT201310UV02Patient result = new PRPAMT201310UV02Patient();
// TODO Set the patient name
// TODO Set the patient gender
// TODO Set the patient birth time
// TODO Set the patient Id
return result;
}
}
| |
package com.brogrammers.agora.views;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.PorterDuff;
import java.util.Date;
import com.brogrammers.agora.Agora;
import com.brogrammers.agora.R;
import com.brogrammers.agora.data.QuestionController;
import com.brogrammers.agora.model.Answer;
import com.brogrammers.agora.model.Question;
/**
* Adapter required to format answers from a question to the answerActivity of the question.
* @author Group02
*/
public class AnswerAdapter extends BaseAdapter {
private Question question;
private LayoutInflater inflater;
private List<Question> qList;
private Activity activity;
private List<Answer> answers;
AnswerAdapter(Question q, Activity activity){
this.question = q;
this.activity = activity;
this.inflater = (LayoutInflater)Agora.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.answers = null;
}
AnswerAdapter(List<Answer> answers, Activity activity) {
this.question = null;
this.activity = activity;
this.answers = answers;
this.inflater = (LayoutInflater)Agora.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
if (question != null) {
return question.countAnswers();
} else if (answers != null) {
return answers.size();
} else {
return 0;
}
}
@Override
public Object getItem(int position) {
if (question != null) {
return question.getAnswers().get(position);
} else if (answers != null) {
return answers.get(position);
} else {
return 0;
}
}
@Override
public long getItemId(int position) {
if (question != null) {
return question.getAnswers().get(position).getID();
} else if (answers != null) {
return answers.get(position).getID();
} else {
return 0;
}
}
/**
* Helper method to convert milliseconds into a date
* @param milliseconds Input the java built in time as milliseconds
* @return newDate Output a date format that interprets time from milliseconds
*/
public String datetostring(long milliseconds){
Date date = new Date();
date.setTime(milliseconds);
String newDate=new SimpleDateFormat("MMM d yyyy").format(date);
return newDate;
}
/**
* sets view for author, score, date, body.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.answer_object, parent, false);
}
//inflate each listview item with "answer_object"
Answer answer = (Answer)getItem(position);
Button comment = (Button) convertView.findViewById(R.id.aComment);
ImageView upvote = (ImageView) convertView.findViewById(R.id.aUpvote);
((TextView)convertView.findViewById(R.id.aLocationText)).setText(answer.getLocationName());
//set text on each TextView & Buttons\
comment.setText("Comments ("+Integer.toString(answer.getComments().size())+")");
// Handles the empty string case to display a blank instead of hint text
if (!TextUtils.isEmpty(answer.getBody())) {
((TextView)convertView.findViewById(R.id.aBody)).setText(answer.getBody().trim());
} else {
((TextView)convertView.findViewById(R.id.aBody)).setText(" ");
}
TextView aScore = (TextView)convertView.findViewById(R.id.aScore);
aScore.setText(Integer.toString(answer.getRating()));
((TextView)convertView.findViewById(R.id.aAuthourDate)).setText("Submitted by: " +answer.getAuthor()+", "+ datetostring(answer.getDate()));
if (!TextUtils.isEmpty(answer.getLocationName())) {
((TextView)convertView.findViewById(R.id.aLocationText)).setText(answer.getLocationName());
} else {
((TextView)convertView.findViewById(R.id.aLocationText)).setVisibility(View.GONE);
}
comment.setOnClickListener(new CommentOnClickListener(position));
upvote.setOnClickListener(new UpVoteOnClickListener(position, aScore));
ImageView thumbView = (ImageView) convertView.findViewById(R.id.AnswerImage);
if (answer.hasImage() && answer.getImage() != null) {
thumbView.setVisibility(View.VISIBLE);
final Bitmap imageBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(answer.getImage()));
Bitmap thumbImage = ThumbnailUtils.extractThumbnail(imageBitmap, 150, 100);
thumbView.setImageBitmap(thumbImage);
thumbView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
(new SimpleImagePopup(imageBitmap, activity)).show();
}
});
} else {
thumbView.setVisibility(View.GONE);
}
return convertView;
}
public void setQuestion(Question q) {
this.question = q;
notifyDataSetChanged();
}
/**
* onclick listener when clicking on comment button. Passes question answerID/questionID to commentActivity
* @author Team 02
*
*/
private class CommentOnClickListener implements OnClickListener {
private int position;
CommentOnClickListener(int position) {
this.position = position;
}
public void onClick(View view) {
Long aid = getItemId(position);
Intent intent = new Intent(activity, CommentActivity.class);
intent.putExtra("aid", aid);
intent.putExtra("qid", question.getID());
activity.startActivity(intent);
}
}
/**
* onClick listener for notifying when the upvote button is clicked.
* @author Team 2
*
*/
private class UpVoteOnClickListener implements OnClickListener {
private int position;
private View aScoreTextView;
UpVoteOnClickListener(int position, View aScoreTextView) {
this.aScoreTextView = aScoreTextView;
this.position = position;
}
public void onClick(View view) {
try {
QuestionController.getController().upvote(question.getID(), getItemId(position));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Update the rating display
Answer a = (Answer)getItem(position);
((TextView)aScoreTextView).setText(Integer.toString(a.getRating()));
}
}
}
| |
/*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.photon.uictrls.datatables;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.string.StringHelper;
import com.helger.html.jquery.JQuery;
import com.helger.html.jscode.IJSExpression;
import com.helger.html.jscode.JSAnonymousFunction;
import com.helger.html.jscode.JSAssocArray;
import com.helger.html.jscode.JSBlock;
import com.helger.html.jscode.JSExpr;
import com.helger.html.jscode.JSGlobal;
import com.helger.html.jscode.JSInvocation;
import com.helger.html.jscode.JSOp;
import com.helger.html.jscode.JSVar;
/**
* Some sanity functionality for {@link DataTables} objects.
*
* @author Philip Helger
*/
@Immutable
public final class DataTablesHelper
{
private DataTablesHelper ()
{}
/**
* Create the JS conversion routine from object to number.
*
* @return Never <code>null</code>.
*/
@Nonnull
public static JSAnonymousFunction createFunctionIntVal ()
{
return createFunctionIntVal ((JSAnonymousFunction) null);
}
@Nonnull
public static JSAnonymousFunction createFunctionIntVal (@Nullable final JSAnonymousFunction aValueCleanupFunc)
{
final JSAnonymousFunction aFuncIntVal = new JSAnonymousFunction ();
final JSVar aVal = aFuncIntVal.param ("v");
// If string
final JSBlock aIfString = aFuncIntVal.body ()._if (aVal.typeof ().eeq ("string"))._then ();
if (aValueCleanupFunc != null)
aIfString.assign (aVal, aValueCleanupFunc.invoke ().arg (aVal));
aIfString._return (JSGlobal.parseFloat (aVal));
// If number
aFuncIntVal.body ()._if (aVal.typeof ().eeq ("number"))._then ()._return (aVal);
// Assume 0
aFuncIntVal.body ()._return (0);
return aFuncIntVal;
}
/**
* Create the JS function to print the sum in the footer
*
* @param sPrefix
* The prefix to be prepended. May be <code>null</code> or empty.
* @param sSuffix
* The string suffix to be appended. May be <code>null</code> or empty.
* @param sBothPrefix
* The prefix to be printed if page total and overall total are
* displayed. May be <code>null</code>.
* @param sBothSep
* The separator to be printed if page total and overall total are
* displayed. May be <code>null</code>.
* @param sBothSuffix
* The suffix to be printed if page total and overall total are
* displayed. May be <code>null</code>.
* @return Never <code>null</code>.
*/
@Nonnull
public static JSAnonymousFunction createFunctionPrintSum (@Nullable final String sPrefix,
@Nullable final String sSuffix,
@Nullable final String sBothPrefix,
@Nullable final String sBothSep,
@Nullable final String sBothSuffix)
{
final JSAnonymousFunction aFuncPrintSum = new JSAnonymousFunction ();
IJSExpression aTotal = aFuncPrintSum.param ("t");
IJSExpression aPageTotal = aFuncPrintSum.param ("pt");
if (StringHelper.hasText (sPrefix))
{
aTotal = JSExpr.lit (sPrefix).plus (aTotal);
aPageTotal = JSExpr.lit (sPrefix).plus (aPageTotal);
}
if (StringHelper.hasText (sSuffix))
{
aTotal = aTotal.plus (sSuffix);
aPageTotal = aPageTotal.plus (sSuffix);
}
IJSExpression aBoth;
if (StringHelper.hasText (sBothPrefix))
aBoth = JSExpr.lit (sBothPrefix).plus (aPageTotal);
else
aBoth = aPageTotal;
if (StringHelper.hasText (sBothSep))
aBoth = aBoth.plus (sBothSep);
aBoth = aBoth.plus (aTotal);
if (StringHelper.hasText (sBothSuffix))
aBoth = aBoth.plus (sBothSuffix);
aFuncPrintSum.body ()._return (JSOp.cond (aTotal.eq (aPageTotal), aTotal, aBoth));
return aFuncPrintSum;
}
/**
* Create a dynamic callback for calculated footer values (like sums etc.)
*
* @param aColumns
* The columns to be added. May neither be <code>null</code> nor empty.
* @return A JS function to be used as the dataTables footer callback.
*/
@Nonnull
public static JSAnonymousFunction createFooterCallbackColumnSum (@Nonnull FooterCallbackSumColumn... aColumns)
{
ValueEnforcer.notEmpty (aColumns, "Columns");
final JSAnonymousFunction ret = new JSAnonymousFunction ();
ret.param ("tfoot");
ret.param ("data");
ret.param ("start");
ret.param ("end");
ret.param ("display");
final JSVar aAPI = ret.body ().var ("api", JSExpr.THIS.invoke ("api"));
for (final FooterCallbackSumColumn aColumn : aColumns)
{
final String sSuffix = Integer.toString (aColumn.getPrintColumn ());
final JSVar aIntVal = ret.body ().var ("funcIntVal" + sSuffix, aColumn.getJSFuncIntVal ());
final JSVar aPrintSum = ret.body ().var ("funcPrintSum" + sSuffix, aColumn.getJSFuncPrintSum ());
// The reduce function: plus
final JSAnonymousFunction aFuncReduce = new JSAnonymousFunction ();
{
final JSVar aParam1 = aFuncReduce.param ("a");
final JSVar aParam2 = aFuncReduce.param ("b");
aFuncReduce.body ()._return (JSExpr.invoke (aIntVal).arg (aParam1).plus (JSExpr.invoke (aIntVal).arg (aParam2)));
}
final JSVar aReduce = ret.body ().var ("funcReduce" + sSuffix, aFuncReduce);
// Calc overall total
final JSVar aTotal = ret.body ()
.var ("total" + sSuffix,
aAPI.invoke ("column")
.arg (aColumn.getCalcColumn ())
.invoke ("data")
.invoke ("reduce")
.arg (aReduce)
.arg (0));
// Calc visible total
final JSVar aPageTotal = ret.body ()
.var ("pagetotal" + sSuffix,
aAPI.invoke ("column")
.arg (aColumn.getCalcColumn ())
.arg (new JSAssocArray ().add ("page", "current"))
.invoke ("data")
.invoke ("reduce")
.arg (aReduce)
.arg (0));
// Update the respective footer
ret.body ()
.add (JQuery.jQuery (aAPI.invoke ("column").arg (aColumn.getPrintColumn ()).invoke ("footer"))
.html (JSExpr.invoke (aPrintSum).arg (aTotal).arg (aPageTotal)));
}
return ret;
}
/**
* Remove all filters and redraw the data table
*
* @param aDTSelect
* JS expression that selects 1-n datatables
* @return The invocation to clear the filter. Never <code>null</code>.
*/
@Nonnull
public static JSInvocation createClearFilterCode (@Nonnull final IJSExpression aDTSelect)
{
return aDTSelect.invoke ("DataTable").invoke ("search").arg ("").invoke ("columns").invoke ("search").arg ("").invoke ("draw");
}
}
| |
//
// Philosopher.java -- Java class Philosopher
// Project OrcSites
//
// Copyright (c) 2016 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//
package orc.lib.simanim;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/**
* @author Joseph Cooper
*/
public class Philosopher extends JPanel {
private static final long serialVersionUID = 1L;
private static final double rTable = 200;
private static final double buffer = 0.05 * rTable;
private static final int winWidth = (int) (4 * rTable);
public static Image forkImg = Toolkit.getDefaultToolkit().getImage(Philosopher.class.getResource("fork.png"));
public static Image plateImg = Toolkit.getDefaultToolkit().getImage(Philosopher.class.getResource("plate.png"));
public static Image headImg = Toolkit.getDefaultToolkit().getImage(Philosopher.class.getResource("head.png"));
public static Image thoughtImg = Toolkit.getDefaultToolkit().getImage(Philosopher.class.getResource("thought.png"));
public static Image sauceImg = Toolkit.getDefaultToolkit().getImage(Philosopher.class.getResource("sauce.png"));
private final int nPhil;
private final double theta;
private final double rPlateCenter;
private final double rPlate;
private final double rFace;
private final double rFaceCenter;
public int armState[][];
public int thinkState[];
public int eatState[];
public BufferedImage bImage;
public int frameNo;
public Philosopher() {
this(5);
}
/**
* Create the table and invite all the philosophers to dinner. Initially,
* none are eating, thinking, or reaching for their forks.
*
* @param n How many philosophers are coming.
*/
public Philosopher(final int n) {
nPhil = n;
theta = 2.0 * Math.PI / nPhil;
rPlateCenter = rTable / (1 + Math.sin(theta / 2.0));
rPlate = rPlateCenter * Math.sin(theta / 2.0) - buffer;
rFace = rPlate + buffer;
rFaceCenter = rTable + rPlate + 2 * buffer;
armState = new int[2][nPhil];
thinkState = new int[nPhil];
eatState = new int[nPhil];
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gd = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create an image that supports transparent pixels
bImage = gc.createCompatibleImage(winWidth, winWidth);
frameNo = 0;
// armState[0][0]=1;
// armState[1][0]=7;
// thinkState[3]=5;
// eatState[2]=9;
}
public int setFork(final int phil, final int side, final int s) {
armState[side][phil] = s;
return phil;
}
public int setThink(final int phil, final int s) {
thinkState[phil] = s;
return phil;
}
public int setEat(final int phil, final int s) {
eatState[phil] = s;
return phil;
}
public int open() {
WindowUtilities.openInJFrame(this, winWidth, winWidth);
return 0;
}
public int redraw() {
update(this.getGraphics());
/*
* paintComponent(bImage.getGraphics()); try {
* javax.imageio.ImageIO.write(bImage, "jpeg", new
* File("c:/Temp/pics/frame"+frameNo+".jpeg")); } catch (IOException e)
* { e.printStackTrace(); } ++frameNo;
*/
return 0;
}
@Override
public void paintComponent(final Graphics g) {
clear(g);
final Graphics2D g2d = (Graphics2D) g;
AffineTransform saveTrans;
final double fWidth = forkImg.getWidth(this) * buffer / forkImg.getHeight(this);
g2d.setColor(Color.darkGray);
g2d.fillOval((int) (winWidth / 2.0 - rTable), (int) (winWidth / 2.0 - rTable), (int) (2 * rTable), (int) (2 * rTable));
g2d.translate(winWidth / 2.0, winWidth / 2.0);
for (int ii = 0; ii < nPhil; ++ii) {
// Draw forks
g2d.drawImage(forkImg, (int) (rTable - fWidth), (int) (-buffer / 2), (int) fWidth, (int) buffer, this);
// Draw plates
g2d.rotate(theta / 2);
saveTrans = g2d.getTransform();
g2d.setColor(Color.white);
g2d.translate((int) rPlateCenter, 0);
g2d.drawImage(plateImg, (int) -rPlate, (int) -rPlate, (int) (2 * rPlate), (int) (2 * rPlate), this);
// Eating
if (eatState[ii] != 0) {
final float shrink = eatState[ii] / 10.0f;
g2d.drawImage(sauceImg, (int) (-shrink * rPlate), (int) (-shrink * rPlate), (int) (2 * shrink * rPlate), (int) (2 * shrink * rPlate), this);
}
g2d.setTransform(saveTrans);
// Draw philosophers
g2d.setColor(Color.black);
g2d.setStroke(new BasicStroke((int) buffer));
// Left arm
if (armState[0][ii] != 0) {
final float leftEx = 0.3f + 0.7f * armState[0][ii] / 10.0f;
g2d.translate((int) rFaceCenter, 0);
g2d.drawLine(0, 0, (int) (leftEx * (-(rFaceCenter + buffer) + Math.cos(theta / 2) * rTable)), (int) (leftEx * Math.sin(theta / 2) * (rTable - buffer)));
g2d.fillOval((int) (leftEx * (-(rFaceCenter + buffer) + Math.cos(theta / 2) * rTable) - buffer), (int) (leftEx * Math.sin(theta / 2) * (rTable - buffer) - buffer), (int) (2 * buffer), (int) (2 * buffer));
g2d.setTransform(saveTrans);
}
// Right arm
if (armState[1][ii] != 0) {
final float rightEx = 0.3f + 0.7f * armState[1][ii] / 10.0f;
g2d.translate((int) rFaceCenter, 0);
g2d.drawLine(0, 0, (int) (rightEx * (-(rFaceCenter + buffer) + Math.cos(theta / 2) * rTable)), (int) (-rightEx * Math.sin(theta / 2) * (rTable - buffer)));
g2d.fillOval((int) (rightEx * (-(rFaceCenter + buffer) + Math.cos(theta / 2) * rTable) - buffer), (int) (-rightEx * Math.sin(theta / 2) * (rTable - buffer) - buffer), (int) (2 * buffer), (int) (2 * buffer));
g2d.setTransform(saveTrans);
}
// Head
g2d.translate((int) rFaceCenter, 0);
g2d.drawImage(headImg, (int) -rFace, (int) -rFace, (int) (2 * rFace), (int) (2 * rFace), this);
// g2d.setTransform(saveTrans);
// Thinking
// g2d.translate((int)(rFaceCenter),0);
if (thinkState[ii] != 0) {
final double rotEx = 2 * Math.PI * thinkState[ii] / 10.0f;
g2d.rotate(rotEx, 0, 0);
g2d.drawImage(thoughtImg, (int) -rFace, (int) -rFace, (int) (2 * rFace), (int) (2 * rFace), this);
}
g2d.setTransform(saveTrans);
// Rotate the rest of the way
g2d.rotate(theta / 2);
}
}
// super.paintComponent clears offscreen pixmap,
// since we're using double buffering by default.
protected void clear(final Graphics g) {
super.paintComponent(g);
}
public static void main(final String[] args) {
final Philosopher se = new Philosopher();
se.open();
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.slice;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.GenerateMicroBenchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.util.concurrent.ThreadLocalRandom;
import static io.airlift.slice.Slice.getUnsafe;
@SuppressWarnings("restriction")
@BenchmarkMode(Mode.Throughput)
@Fork(5)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
public class MemoryCopyBenchmark
{
static final int PAGE_SIZE = 4 * 1024;
static final int N_PAGES = 256 * 1024;
static final int ALLOC_SIZE = PAGE_SIZE * N_PAGES;
@State(Scope.Thread)
public static class Buffers
{
Slice data;
long startOffset;
long destOffset;
@Setup
public void fillWithBogusData()
{
data = Slices.allocate(ALLOC_SIZE);
for (int idx = 0; idx < data.length() / 8; idx++) {
data.setLong(idx, ThreadLocalRandom.current().nextLong());
}
long startOffsetPages = ThreadLocalRandom.current().nextInt(N_PAGES / 4);
long destOffsetPages = ThreadLocalRandom.current().nextInt(N_PAGES / 4) + N_PAGES / 2;
startOffset = startOffsetPages * PAGE_SIZE;
destOffset = destOffsetPages * PAGE_SIZE;
}
}
@GenerateMicroBenchmark
public Slice b00sliceZero(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 0);
}
@GenerateMicroBenchmark
public Slice b01customLoopZero(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 0);
}
@GenerateMicroBenchmark
public Slice b02unsafeZero(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 0);
}
@GenerateMicroBenchmark
public Slice b03slice32B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 32);
}
@GenerateMicroBenchmark
public Slice b04customLoop32B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 32);
}
@GenerateMicroBenchmark
public Slice b05unsafe32B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 32);
}
@GenerateMicroBenchmark
public Slice b06slice128B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 128);
}
@GenerateMicroBenchmark
public Slice b07customLoop128B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 128);
}
@GenerateMicroBenchmark
public Slice b08unsafe128B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 128);
}
@GenerateMicroBenchmark
public Slice b09slice512B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 512);
}
@GenerateMicroBenchmark
public Slice b10customLoop512B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 512);
}
@GenerateMicroBenchmark
public Slice b11unsafe512B(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 512);
}
@GenerateMicroBenchmark
public Slice b12slice1K(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 1024);
}
@GenerateMicroBenchmark
public Slice b13customLoop1K(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 1024);
}
@GenerateMicroBenchmark
public Slice b14unsafe1K(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 1024);
}
@GenerateMicroBenchmark
public Slice b15slice1M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 1024 * 1024);
}
@GenerateMicroBenchmark
public Slice b16customLoop1M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 1024 * 1024);
}
@GenerateMicroBenchmark
public Slice b17unsafe1M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 1024 * 1024);
}
@GenerateMicroBenchmark
public Slice b18slice128M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.SLICE, 128 * 1024 * 1024);
}
@GenerateMicroBenchmark
public Slice b19customLoop128M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.CUSTOM_LOOP, 128 * 1024 * 1024);
}
@GenerateMicroBenchmark
public Slice b20unsafe128M(Buffers buffers)
{
return doCopy(buffers, CopyStrategy.UNSAFE, 128 * 1024 * 1024);
}
static Slice doCopy(Buffers buffers, CopyStrategy strategy, int length)
{
assert buffers.startOffset >= 0 : "startOffset < 0";
assert buffers.destOffset >= 0 : "destOffset < 0";
assert buffers.startOffset + length < ALLOC_SIZE : "startOffset + length >= ALLOC_SIZE";
assert buffers.destOffset + length < ALLOC_SIZE : "destOffset + length >= ALLOC_SIZE";
strategy.doCopy(buffers.data, buffers.startOffset, buffers.destOffset, length);
return buffers.data;
}
private enum CopyStrategy
{
SLICE
{
@Override
public void doCopy(Slice data, long src, long dest, int length)
{
data.setBytes((int) dest, data, (int) src, length);
}
},
CUSTOM_LOOP
{
@Override
public void doCopy(Slice data, long src, long dest, int length)
{
Object base = data.getBase();
long offset = data.getAddress();
while (length >= SizeOf.SIZE_OF_LONG) {
long srcLong = getUnsafe().getLong(base, src + offset);
getUnsafe().putLong(base, dest + offset, srcLong);
offset += SizeOf.SIZE_OF_LONG;
length -= SizeOf.SIZE_OF_LONG;
}
while (length > 0) {
byte srcByte = getUnsafe().getByte(base, src + offset);
getUnsafe().putByte(base, dest + offset, srcByte);
offset++;
length--;
}
}
},
UNSAFE
{
@Override
public void doCopy(Slice data, long srcOffset, long destOffset, int length)
{
Object base = data.getBase();
srcOffset += data.getAddress();
destOffset += data.getAddress();
int bytesToCopy = length - (length % 8);
getUnsafe().copyMemory(base, srcOffset, base, destOffset, bytesToCopy);
getUnsafe().copyMemory(base, srcOffset + bytesToCopy, base, destOffset + bytesToCopy, length - bytesToCopy);
}
};
public abstract void doCopy(Slice data, long src, long dest, int length);
}
public static void main(String[] args)
throws RunnerException
{
Options options = new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.include(".*" + MemoryCopyBenchmark.class.getSimpleName() + ".*")
.build();
new Runner(options).run();
}
}
| |
package crazypants.enderio.item.darksteel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Triple;
import com.google.common.collect.ImmutableList;
import crazypants.enderio.EnderIO;
import crazypants.enderio.integration.forestry.ApiaristArmorUpgrade;
import crazypants.enderio.integration.forestry.NaturalistEyeUpgrade;
import crazypants.enderio.integration.top.TheOneProbeUpgrade;
import crazypants.enderio.item.darksteel.upgrade.ElytraUpgrade;
import crazypants.enderio.item.darksteel.upgrade.EnergyUpgrade;
import crazypants.enderio.item.darksteel.upgrade.GliderUpgrade;
import crazypants.enderio.item.darksteel.upgrade.IDarkSteelUpgrade;
import crazypants.enderio.item.darksteel.upgrade.JumpUpgrade;
import crazypants.enderio.item.darksteel.upgrade.NightVisionUpgrade;
import crazypants.enderio.item.darksteel.upgrade.SolarUpgrade;
import crazypants.enderio.item.darksteel.upgrade.SoundDetectorUpgrade;
import crazypants.enderio.item.darksteel.upgrade.SpeedUpgrade;
import crazypants.enderio.item.darksteel.upgrade.SpoonUpgrade;
import crazypants.enderio.item.darksteel.upgrade.SwimUpgrade;
import crazypants.enderio.item.darksteel.upgrade.TravelUpgrade;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class DarkSteelRecipeManager {
public static DarkSteelRecipeManager instance = new DarkSteelRecipeManager();
private List<IDarkSteelUpgrade> upgrades = new ArrayList<IDarkSteelUpgrade>();
public DarkSteelRecipeManager() {
upgrades.add(EnergyUpgrade.EMPOWERED);
upgrades.add(EnergyUpgrade.EMPOWERED_TWO);
upgrades.add(EnergyUpgrade.EMPOWERED_THREE);
upgrades.add(EnergyUpgrade.EMPOWERED_FOUR);
upgrades.add(JumpUpgrade.JUMP_ONE);
upgrades.add(JumpUpgrade.JUMP_TWO);
upgrades.add(JumpUpgrade.JUMP_THREE);
upgrades.add(SpeedUpgrade.SPEED_ONE);
upgrades.add(SpeedUpgrade.SPEED_TWO);
upgrades.add(SpeedUpgrade.SPEED_THREE);
upgrades.add(GliderUpgrade.INSTANCE);
upgrades.add(ElytraUpgrade.INSTANCE);
upgrades.add(SoundDetectorUpgrade.INSTANCE);
upgrades.add(SwimUpgrade.INSTANCE);
upgrades.add(NightVisionUpgrade.INSTANCE);
upgrades.add(TravelUpgrade.INSTANCE);
upgrades.add(SpoonUpgrade.INSTANCE);
upgrades.add(SolarUpgrade.SOLAR_ONE);
upgrades.add(SolarUpgrade.SOLAR_TWO);
upgrades.add(SolarUpgrade.SOLAR_THREE);
//TODO: Mod Thaumcraft
// if(Loader.isModLoaded("Thaumcraft")) {
// ThaumcraftCompat.loadUpgrades(upgrades);
// }
if(Loader.isModLoaded("forestry")) {
upgrades.add(NaturalistEyeUpgrade.INSTANCE);
upgrades.add(ApiaristArmorUpgrade.HELMET);
upgrades.add(ApiaristArmorUpgrade.CHEST);
upgrades.add(ApiaristArmorUpgrade.LEGS);
upgrades.add(ApiaristArmorUpgrade.BOOTS);
}
if (TheOneProbeUpgrade.INSTANCE.isAvailable()) {
upgrades.add(TheOneProbeUpgrade.INSTANCE);
}
}
@SubscribeEvent
public void handleAnvilEvent(AnvilUpdateEvent evt) {
if(evt.getLeft() == null || evt.getRight() == null) {
return;
}
if(isRepair(evt)) {
handleRepair(evt);
} else {
handleUpgrade(evt);
}
}
private boolean isRepair(AnvilUpdateEvent evt) {
if(evt.getLeft().getItem() instanceof IDarkSteelItem) {
IDarkSteelItem dsi = (IDarkSteelItem)evt.getLeft().getItem();
if(dsi.isItemForRepair(evt.getRight())) {
return true;
}
}
return false;
}
private void handleRepair(AnvilUpdateEvent evt) {
ItemStack targetStack = evt.getLeft();
ItemStack ingots = evt.getRight();
//repair event
IDarkSteelItem targetItem = (IDarkSteelItem)targetStack.getItem();
int maxIngots = targetItem.getIngotsRequiredForFullRepair();
double damPerc = (double)targetStack.getItemDamage()/ targetStack.getMaxDamage();
int requiredIngots = (int)Math.ceil(damPerc * maxIngots);
if(ingots.stackSize > requiredIngots) {
return;
}
int damageAddedPerIngot = (int)Math.ceil((double)targetStack.getMaxDamage()/maxIngots);
int totalDamageRemoved = damageAddedPerIngot * ingots.stackSize;
ItemStack resultStack = targetStack.copy();
resultStack.setItemDamage(Math.max(0, resultStack.getItemDamage() - totalDamageRemoved));
evt.setOutput(resultStack);
evt.setCost(ingots.stackSize + (int)Math.ceil(getEnchantmentRepairCost(resultStack)/2));
}
private void handleUpgrade(AnvilUpdateEvent evt) {
for (IDarkSteelUpgrade upgrade : upgrades) {
if(upgrade.isUpgradeItem(evt.getRight()) && upgrade.canAddToItem(evt.getLeft())) {
ItemStack res = new ItemStack(evt.getLeft().getItem(), 1, evt.getLeft().getItemDamage());
if(evt.getLeft().getTagCompound() != null) {
res.setTagCompound(evt.getLeft().getTagCompound().copy());
}
upgrade.writeToItem(res);
evt.setOutput(res);
evt.setCost(upgrade.getLevelCost());
return;
}
}
}
public static int getEnchantmentRepairCost(ItemStack itemStack) {
//derived from ContainerRepair
int res = 0;
Map<Enchantment, Integer> map1 = EnchantmentHelper.getEnchantments(itemStack);
Iterator<Enchantment> iter = map1.keySet().iterator();
while (iter.hasNext()) {
Enchantment i1 = iter.next();
Enchantment enchantment = i1;
int level = map1.get(enchantment).intValue();
if(enchantment.canApply(itemStack)) {
if(level > enchantment.getMaxLevel()) {
level = enchantment.getMaxLevel();
}
int costPerLevel = 0;
switch (enchantment.getRarity()) {
case VERY_RARE:
costPerLevel = 8;
break;
case RARE:
costPerLevel = 4;
case UNCOMMON:
costPerLevel = 2;
break;
case COMMON:
costPerLevel = 1;
}
res += costPerLevel * level;
}
}
return res;
}
public List<IDarkSteelUpgrade> getUpgrades() {
return upgrades;
}
public void addCommonTooltipEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
for (IDarkSteelUpgrade upgrade : upgrades) {
if(upgrade.hasUpgrade(itemstack)) {
upgrade.addCommonEntries(itemstack, entityplayer, list, flag);
}
}
}
public void addBasicTooltipEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
for (IDarkSteelUpgrade upgrade : upgrades) {
if(upgrade.hasUpgrade(itemstack)) {
upgrade.addBasicEntries(itemstack, entityplayer, list, flag);
}
}
}
public void addAdvancedTooltipEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
List<IDarkSteelUpgrade> applyableUpgrades = new ArrayList<IDarkSteelUpgrade>();
for (IDarkSteelUpgrade upgrade : upgrades) {
if(upgrade.hasUpgrade(itemstack)) {
upgrade.addDetailedEntries(itemstack, entityplayer, list, flag);
} else if(upgrade.canAddToItem(itemstack)) {
applyableUpgrades.add(upgrade);
}
}
if(!applyableUpgrades.isEmpty()) {
list.add(TextFormatting.YELLOW + EnderIO.lang.localize("tooltip.anvilupgrades") + " ");
for (IDarkSteelUpgrade up : applyableUpgrades) {
list.add(TextFormatting.DARK_AQUA + "" + "" + EnderIO.lang.localizeExact(up.getUnlocalizedName() + ".name") + ": ");
list.add(TextFormatting.DARK_AQUA + "" + TextFormatting.ITALIC + " " + up.getUpgradeItemName() + " + " + up.getLevelCost()
+ " " + EnderIO.lang.localize("item.darkSteel.tooltip.lvs"));
}
}
}
public Iterator<IDarkSteelUpgrade> recipeIterator() {
return ImmutableList.copyOf(upgrades).iterator();
}
public String getUpgradesAsString(ItemStack stack) {
String result = "";
for (IDarkSteelUpgrade upgrade : upgrades) {
if (upgrade.hasUpgrade(stack)) {
result += upgrade.getUnlocalizedName();
}
}
return result.isEmpty() ? null : result;
}
public List<ItemStack> getRecipes(Set<String> seen, List<Triple<ItemStack, ItemStack, ItemStack>> list, List<ItemStack> input) {
List<ItemStack> output = new ArrayList<ItemStack>();
for (ItemStack stack : input) {
for (IDarkSteelUpgrade upgrade : upgrades) {
if (upgrade.canAddToItem(stack)) {
ItemStack newStack = stack.copy();
upgrade.writeToItem(newStack);
String id = newStack.getItem() + getUpgradesAsString(newStack);
if (!seen.contains(id)) {
seen.add(id);
list.add(Triple.of(stack, upgrade.getUpgradeItem(), newStack));
output.add(newStack);
}
}
}
}
return output;
}
public static List<Triple<ItemStack, ItemStack, ItemStack>> getAllRecipes(List<ItemStack> validItems) {
List<Triple<ItemStack, ItemStack, ItemStack>> list = new ArrayList<Triple<ItemStack, ItemStack, ItemStack>>();
Set<String> seen = new HashSet<String>();
List<ItemStack> items = instance.getRecipes(seen, list, validItems);
while (!items.isEmpty()) {
items = instance.getRecipes(seen, list, items);
}
return list;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.generator.openapi;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Collections;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.apicurio.datamodels.Library;
import io.apicurio.datamodels.openapi.models.OasDocument;
import io.apicurio.datamodels.openapi.v2.models.Oas20Document;
import io.apicurio.datamodels.openapi.v3.models.Oas30Document;
import io.apicurio.datamodels.openapi.v3.models.Oas30Server;
import io.apicurio.datamodels.openapi.v3.models.Oas30ServerVariable;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.rest.RestsDefinition;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RestDslGeneratorTest {
static OasDocument document;
final Instant generated = Instant.parse("2017-10-17T00:00:00.000Z");
@Test
public void shouldCreateDefinitions() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
final RestsDefinition definition = RestDslGenerator.toDefinition(document).generate(context);
assertThat(definition).isNotNull();
assertThat(definition.getRests()).hasSize(1);
assertThat(definition.getRests().get(0).getPath()).isEqualTo("/v2");
}
}
@Test
public void shouldDetermineBasePathFromV2Document() {
final Oas20Document oas20Document = new Oas20Document();
oas20Document.basePath = "/api";
assertThat(RestDslGenerator.determineBasePathFrom(oas20Document)).isEqualTo("/api");
}
@Test
public void shouldDetermineBasePathFromV3DocumentsServerUrl() {
final Oas30Document oas30Document = new Oas30Document();
final Oas30Server server = new Oas30Server();
server.url = "https://example.com/api";
oas30Document.servers = Collections.singletonList(server);
assertThat(RestDslGenerator.determineBasePathFrom(oas30Document)).isEqualTo("/api");
}
@Test
public void shouldDetermineBasePathFromV3DocumentsServerUrlWithTemplateVariables() {
final Oas30Document oas30Document = new Oas30Document();
final Oas30Server server = new Oas30Server();
addVariableTo(server, "base", "api");
addVariableTo(server, "path", "v3");
server.url = "https://example.com/{base}/{path}";
oas30Document.servers = Collections.singletonList(server);
assertThat(RestDslGenerator.determineBasePathFrom(oas30Document)).isEqualTo("/api/v3");
}
@Test
public void shouldDetermineBasePathFromV3DocumentsWhenServerUrlIsRelative() {
final Oas30Document oas30Document = new Oas30Document();
final Oas30Server server = new Oas30Server();
server.url = "/api/v3";
oas30Document.servers = Collections.singletonList(server);
assertThat(RestDslGenerator.determineBasePathFrom(oas30Document)).isEqualTo("/api/v3");
}
@Test
public void shouldDetermineBasePathFromV3DocumentsWhenServerUrlIsRelativeWithoutStartingSlash() {
final Oas30Document oas30Document = new Oas30Document();
final Oas30Server server = new Oas30Server();
server.url = "api/v3";
oas30Document.servers = Collections.singletonList(server);
assertThat(RestDslGenerator.determineBasePathFrom(oas30Document)).isEqualTo("/api/v3");
}
@Test
public void shouldGenerateSourceCodeWithDefaults() throws Exception {
final StringBuilder code = new StringBuilder();
RestDslGenerator.toAppendable(document).withGeneratedTime(generated).generate(code);
final URI file = RestDslGeneratorTest.class.getResource("/OpenApiPetstore.txt").toURI();
final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8);
assertThat(code.toString()).isEqualTo(expectedContent);
}
@Test
public void shouldGenerateSourceCodeWithFilter() throws Exception {
final StringBuilder code = new StringBuilder();
RestDslGenerator.toAppendable(document)
.withGeneratedTime(generated)
.withClassName("MyRestRoute")
.withPackageName("com.example")
.withIndent("\t")
.withSourceCodeTimestamps()
.withOperationFilter("find*,deletePet,updatePet")
.withDestinationGenerator(o -> "direct:rest-" + o.operationId)
.generate(code);
final URI file = RestDslGeneratorTest.class.getResource("/MyRestRouteFilter.txt").toURI();
final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8);
assertThat(code.toString()).isEqualTo(expectedContent);
}
@Test
public void shouldGenerateSourceCodeWithOptions() throws Exception {
final StringBuilder code = new StringBuilder();
RestDslGenerator.toAppendable(document)
.withGeneratedTime(generated)
.withClassName("MyRestRoute")
.withPackageName("com.example")
.withIndent("\t")
.withSourceCodeTimestamps()
.withDestinationGenerator(o -> "direct:rest-" + o.operationId).generate(code);
final URI file = RestDslGeneratorTest.class.getResource("/MyRestRoute.txt").toURI();
final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8);
assertThat(code.toString()).isEqualTo(expectedContent);
}
@Test
public void shouldGenerateSourceCodeWithRestComponent() throws Exception {
final StringBuilder code = new StringBuilder();
RestDslGenerator.toAppendable(document)
.withGeneratedTime(generated)
.withRestComponent("servlet")
.withRestContextPath("/")
.generate(code);
final URI file = RestDslGeneratorTest.class.getResource("/OpenApiPetstoreWithRestComponent.txt").toURI();
final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8);
assertThat(code.toString()).isEqualTo(expectedContent);
}
@Test
public void shouldResolveEmptyVariables() {
assertThat(RestDslGenerator.resolveVariablesIn("", new Oas30Server())).isEmpty();
}
@Test
public void shouldResolveMultipleOccurancesOfVariables() {
final Oas30Server server = new Oas30Server();
addVariableTo(server, "var1", "value1");
addVariableTo(server, "var2", "value2");
assertThat(RestDslGenerator.resolveVariablesIn("{var2} before {var1} after {var2}", server)).isEqualTo("value2 before value1 after value2");
}
@Test
public void shouldResolveMultipleVariables() {
final Oas30Server server = new Oas30Server();
addVariableTo(server, "var1", "value1");
addVariableTo(server, "var2", "value2");
assertThat(RestDslGenerator.resolveVariablesIn("before {var1} after {var2}", server)).isEqualTo("before value1 after value2");
}
@Test
public void shouldResolveSingleVariable() {
final Oas30Server server = new Oas30Server();
addVariableTo(server, "var", "value");
assertThat(RestDslGenerator.resolveVariablesIn("before {var} after", server)).isEqualTo("before value after");
}
@BeforeClass
public static void readOpenApiDoc() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
try (InputStream is = RestDslGeneratorTest.class.getResourceAsStream("openapi-v2.json")) {
final JsonNode node = mapper.readTree(is);
document = (OasDocument) Library.readDocument(node);
}
}
private static void addVariableTo(final Oas30Server server, final String name, final String value) {
final Oas30ServerVariable variable = new Oas30ServerVariable(name);
variable.default_ = value;
server.addServerVariable(name, variable);
}
}
| |
/**
* $Id: mxCellHandler.java,v 1.25 2011-01-17 11:14:44 gaudenz Exp $
* Copyright (c) 2008, Gaudenz Alder
*/
package com.mxgraph.swing.handler;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.view.mxCellState;
import com.mxgraph.view.mxGraph;
/**
* @author Administrator
*
*/
public class mxCellHandler
{
/**
* Reference to the enclosing graph component.
*/
protected mxGraphComponent graphComponent;
/**
* Holds the cell state associated with this handler.
*/
protected mxCellState state;
/**
* Holds the rectangles that define the handles.
*/
protected Rectangle[] handles;
/**
* Specifies if the handles should be painted. Default is true.
*/
protected boolean handlesVisible = true;
/**
* Holds the bounding box of the handler.
*/
protected transient Rectangle bounds;
/**
* Holds the component that is used for preview.
*/
protected transient JComponent preview;
/**
* Holds the start location of the mouse gesture.
*/
protected transient Point first;
/**
* Holds the index of the handle that was clicked.
*/
protected transient int index;
/**
* Constructs a new cell handler for the given cell state.
*
* @param graphComponent Enclosing graph component.
* @param state Cell state for which the handler is created.
*/
public mxCellHandler(mxGraphComponent graphComponent, mxCellState state)
{
this.graphComponent = graphComponent;
refresh(state);
}
/**
*
*/
public boolean isActive()
{
return first != null;
}
/**
* Refreshes the cell handler.
*/
public void refresh(mxCellState state)
{
this.state = state;
handles = createHandles();
mxGraph graph = graphComponent.getGraph();
mxRectangle tmp = graph.getBoundingBox(state.getCell());
if (tmp != null)
{
bounds = tmp.getRectangle();
if (handles != null)
{
for (int i = 0; i < handles.length; i++)
{
if (isHandleVisible(i))
{
bounds.add(handles[i]);
}
}
}
}
}
/**
*
*/
public mxGraphComponent getGraphComponent()
{
return graphComponent;
}
/**
* Returns the cell state that is associated with this handler.
*/
public mxCellState getState()
{
return state;
}
/**
* Returns the index of the current handle.
*/
public int getIndex()
{
return index;
}
/**
* Returns the bounding box of this handler.
*/
public Rectangle getBounds()
{
return bounds;
}
/**
* Returns true if the label is movable.
*/
public boolean isLabelMovable()
{
mxGraph graph = graphComponent.getGraph();
String label = graph.getLabel(state.getCell());
return graph.isLabelMovable(state.getCell()) && label != null
&& label.length() > 0;
}
/**
* Returns true if the handles should be painted.
*/
public boolean isHandlesVisible()
{
return handlesVisible;
}
/**
* Specifies if the handles should be painted.
*/
public void setHandlesVisible(boolean handlesVisible)
{
this.handlesVisible = handlesVisible;
}
/**
* Returns true if the given index is the index of the last handle.
*/
public boolean isLabel(int index)
{
return index == getHandleCount() - 1;
}
/**
* Creates the rectangles that define the handles.
*/
protected Rectangle[] createHandles()
{
return null;
}
/**
* Returns the number of handles in this handler.
*/
protected int getHandleCount()
{
return (handles != null) ? handles.length : 0;
}
/**
* Hook for subclassers to return tooltip texts for certain points on the
* handle.
*/
public String getToolTipText(MouseEvent e)
{
return null;
}
/**
* Returns the index of the handle at the given location.
*
* @param x X-coordinate of the location.
* @param y Y-coordinate of the location.
* @return Returns the handle index for the given location.
*/
public int getIndexAt(int x, int y)
{
if (handles != null && isHandlesVisible())
{
int tol = graphComponent.getTolerance();
Rectangle rect = new Rectangle(x - tol / 2, y - tol / 2, tol, tol);
for (int i = handles.length - 1; i >= 0; i--)
{
if (isHandleVisible(i) && handles[i].intersects(rect))
{
return i;
}
}
}
return -1;
}
/**
* Processes the given event.
*/
public void mousePressed(MouseEvent e)
{
if (!e.isConsumed())
{
int tmp = getIndexAt(e.getX(), e.getY());
if (!isIgnoredEvent(e) && tmp >= 0 && isHandleEnabled(tmp))
{
graphComponent.stopEditing(true);
start(e, tmp);
e.consume();
}
}
}
/**
* Processes the given event.
*/
public void mouseMoved(MouseEvent e)
{
if (!e.isConsumed() && handles != null)
{
int index = getIndexAt(e.getX(), e.getY());
if (index >= 0 && isHandleEnabled(index))
{
Cursor cursor = getCursor(e, index);
if (cursor != null)
{
graphComponent.getGraphControl().setCursor(cursor);
e.consume();
}
else
{
graphComponent.getGraphControl().setCursor(
new Cursor(Cursor.HAND_CURSOR));
}
}
}
}
/**
* Processes the given event.
*/
public void mouseDragged(MouseEvent e)
{
// empty
}
/**
* Processes the given event.
*/
public void mouseReleased(MouseEvent e)
{
reset();
}
/**
* Starts handling a gesture at the given handle index.
*/
public void start(MouseEvent e, int index)
{
this.index = index;
first = e.getPoint();
preview = createPreview();
if (preview != null)
{
graphComponent.getGraphControl().add(preview, 0);
}
}
/**
* Returns true if the given event should be ignored.
*/
protected boolean isIgnoredEvent(MouseEvent e)
{
return graphComponent.isEditEvent(e);
}
/**
* Creates the preview for this handler.
*/
protected JComponent createPreview()
{
return null;
}
/**
* Resets the state of the handler and removes the preview.
*/
public void reset()
{
if (preview != null)
{
preview.setVisible(false);
preview.getParent().remove(preview);
preview = null;
}
first = null;
}
/**
* Returns the cursor for the given event and handle.
*/
protected Cursor getCursor(MouseEvent e, int index)
{
return null;
}
/**
* Paints the visible handles of this handler.
*/
public void paint(Graphics g)
{
if (handles != null && isHandlesVisible())
{
for (int i = 0; i < handles.length; i++)
{
if (isHandleVisible(i)
&& g.hitClip(handles[i].x, handles[i].y,
handles[i].width, handles[i].height))
{
g.setColor(getHandleFillColor(i));
g.fillRect(handles[i].x, handles[i].y, handles[i].width,
handles[i].height);
g.setColor(getHandleBorderColor(i));
g.drawRect(handles[i].x, handles[i].y,
handles[i].width - 1, handles[i].height - 1);
}
}
}
}
/**
* Returns the color used to draw the selection border. This implementation
* returns null.
*/
public Color getSelectionColor()
{
return null;
}
/**
* Returns the stroke used to draw the selection border. This implementation
* returns null.
*/
public Stroke getSelectionStroke()
{
return null;
}
/**
* Returns true if the handle at the specified index is enabled.
*/
protected boolean isHandleEnabled(int index)
{
return true;
}
/**
* Returns true if the handle at the specified index is visible.
*/
protected boolean isHandleVisible(int index)
{
return !isLabel(index) || isLabelMovable();
}
/**
* Returns the color to be used to fill the handle at the specified index.
*/
protected Color getHandleFillColor(int index)
{
if (isLabel(index))
{
return mxConstants.LABEL_HANDLE_FILLCOLOR;
}
return mxConstants.HANDLE_FILLCOLOR;
}
/**
* Returns the border color of the handle at the specified index.
*/
protected Color getHandleBorderColor(int index)
{
return mxConstants.HANDLE_BORDERCOLOR;
}
}
| |
/*
Copyright 2001-2003 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.batik.util;
import java.util.Iterator;
/**
* This class represents an object which queues Runnable objects for
* invocation in a single thread.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public class RunnableQueue implements Runnable {
/**
* Type-safe enumeration of queue states.
*/
public static class RunnableQueueState {
final String value;
private RunnableQueueState(String value) {
this.value = value.intern(); }
public String getValue() { return value; }
public String toString() {
return "[RunnableQueueState: " + value + "]"; }
}
/**
* The queue is in the process of running tasks.
*/
public static final RunnableQueueState RUNNING
= new RunnableQueueState("Running");
/**
* The queue may still be running tasks but as soon as possible
* will go to SUSPENDED state.
*/
public static final RunnableQueueState SUSPENDING
= new RunnableQueueState("Suspending");
/**
* The queue is no longer running any tasks and will not
* run any tasks until resumeExecution is called.
*/
public static final RunnableQueueState SUSPENDED
= new RunnableQueueState("Suspended");
/**
* The Suspension state of this thread.
*/
protected RunnableQueueState state;
/**
* Object to synchronize/wait/notify for suspension
* issues.
*/
protected Object stateLock = new Object();
/**
* Used to indicate if the queue was resumed while
* still running, so a 'resumed' event can be sent.
*/
protected boolean wasResumed;
/**
* The Runnable objects list, also used as synchoronization point
* for pushing/poping runables.
*/
protected DoublyLinkedList list = new DoublyLinkedList();
/**
* Count of preempt entries in queue, so preempt entries
* can be kept properly ordered.
*/
protected int preemptCount = 0;
/**
* The object which handle run events.
*/
protected RunHandler runHandler;
/**
* The current thread.
*/
protected HaltingThread runnableQueueThread;
/**
* The Runnable to run if the queue is empty.
*/
protected Runnable idleRunnable;
/**
* Creates a new RunnableQueue started in a new thread.
* @return a RunnableQueue which is guaranteed to have entered its
* <tt>run()</tt> method.
*/
public static RunnableQueue createRunnableQueue() {
RunnableQueue result = new RunnableQueue();
synchronized (result) {
HaltingThread ht = new HaltingThread
(result, "RunnableQueue-" + threadCount++);
ht.setDaemon(true);
ht.start();
while (result.getThread() == null) {
try {
result.wait();
} catch (InterruptedException ie) {
}
}
}
return result;
}
private static int threadCount;
/**
* Runs this queue.
*/
public void run() {
synchronized (this) {
runnableQueueThread = (HaltingThread)Thread.currentThread();
// Wake the create method so it knows we are in
// our run and ready to go.
notify();
}
Link l;
Runnable rable;
try {
while (!HaltingThread.hasBeenHalted()) {
boolean callSuspended = false;
boolean callResumed = false;
// Mutex for suspension work.
synchronized (stateLock) {
if (state != RUNNING) {
state = SUSPENDED;
callSuspended = true;
}
}
if (callSuspended)
executionSuspended();
synchronized (stateLock) {
while (state != RUNNING) {
state = SUSPENDED;
// notify suspendExecution in case it is
// waiting til we shut down.
stateLock.notifyAll();
// Wait until resumeExecution called.
try {
stateLock.wait();
} catch(InterruptedException ie) { }
}
if (wasResumed) {
wasResumed = false;
callResumed = true;
}
}
if (callResumed)
executionResumed();
// The following seriously stress tests the class
// for stuff happening between the two sync blocks.
//
// try {
// Thread.sleep(1);
// } catch (InterruptedException ie) { }
synchronized (list) {
if (state == SUSPENDING)
continue;
l = (Link)list.pop();
if (preemptCount != 0) preemptCount--;
if (l == null) {
// No item to run, see if there is an idle runnable
// to run instead.
if (idleRunnable != null) {
rable = idleRunnable;
} else {
// Wait for a runnable.
try {
list.wait();
} catch (InterruptedException ie) {
// just loop again.
}
continue; // start loop over again...
}
} else {
rable = l.runnable;
}
}
runnableStart(rable);
try {
rable.run();
} catch (ThreadDeath td) {
// Let it kill us...
throw td;
} catch (Throwable t) {
// Might be nice to notify someone directly.
// But this is more or less what Swing does.
t.printStackTrace();
}
// Notify something waiting on the runnable just completed,
// if we just ran one from the queue.
if (l != null) {
l.unlock();
}
runnableInvoked(rable);
}
} finally {
synchronized (this) {
runnableQueueThread = null;
}
}
}
/**
* Returns the thread in which the RunnableQueue is currently running.
* @return null if the RunnableQueue has not entered his
* <tt>run()</tt> method.
*/
public HaltingThread getThread() {
return runnableQueueThread;
}
/**
* Schedules the given Runnable object for a later invocation, and
* returns.
* An exception is thrown if the RunnableQueue was not started.
* @throws IllegalStateException if getThread() is null.
*/
public void invokeLater(Runnable r) {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
synchronized (list) {
list.push(new Link(r));
list.notify();
}
}
/**
* Waits until the given Runnable's <tt>run()</tt> has returned.
* <em>Note: <tt>invokeAndWait()</tt> must not be called from the
* current thread (for example from the <tt>run()</tt> method of the
* argument).
* @throws IllegalStateException if getThread() is null or if the
* thread returned by getThread() is the current one.
*/
public void invokeAndWait(Runnable r) throws InterruptedException {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
if (runnableQueueThread == Thread.currentThread()) {
throw new IllegalStateException
("Cannot be called from the RunnableQueue thread");
}
LockableLink l = new LockableLink(r);
synchronized (list) {
list.push(l);
list.notify();
}
l.lock();
}
/**
* Schedules the given Runnable object for a later invocation, and
* returns. The given runnable preempts any runnable that is not
* currently executing (ie the next runnable started will be the
* one given). An exception is thrown if the RunnableQueue was
* not started.
* @throws IllegalStateException if getThread() is null.
*/
public void preemptLater(Runnable r) {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
synchronized (list) {
list.add(preemptCount, new Link(r));
preemptCount++;
list.notify();
}
}
/**
* Waits until the given Runnable's <tt>run()</tt> has returned.
* The given runnable preempts any runnable that is not currently
* executing (ie the next runnable started will be the one given).
* <em>Note: <tt>preemptAndWait()</tt> must not be called from the
* current thread (for example from the <tt>run()</tt> method of the
* argument).
* @throws IllegalStateException if getThread() is null or if the
* thread returned by getThread() is the current one.
*/
public void preemptAndWait(Runnable r) throws InterruptedException {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
if (runnableQueueThread == Thread.currentThread()) {
throw new IllegalStateException
("Cannot be called from the RunnableQueue thread");
}
LockableLink l = new LockableLink(r);
synchronized (list) {
list.add(preemptCount, l);
preemptCount++;
list.notify();
}
l.lock();
}
public RunnableQueueState getQueueState() {
synchronized (stateLock) {
return state;
}
}
/**
* Suspends the execution of this queue after the current runnable
* completes.
* @param waitTillSuspended if true this method will not return
* until the queue has suspended (no runnable in progress
* or about to be in progress). If resumeExecution is
* called while waiting will simply return (this really
* indicates a race condition in your code). This may
* return before an associated RunHandler is notified.
* @throws IllegalStateException if getThread() is null. */
public void suspendExecution(boolean waitTillSuspended) {
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
// System.err.println("Suspend Called");
synchronized (stateLock) {
wasResumed = false;
if (state == SUSPENDED) {
// already suspended, notify stateLock so an event is
// generated.
stateLock.notifyAll();
return;
}
if (state == RUNNING) {
state = SUSPENDING;
synchronized (list) {
// Wake up run thread if it is waiting for jobs,
// so we go into the suspended case (notifying
// run-handler etc...)
list.notify();
}
}
if (waitTillSuspended) {
while (state == SUSPENDING) {
try {
stateLock.wait();
} catch(InterruptedException ie) { }
}
}
}
}
/**
* Resumes the execution of this queue.
* @throws IllegalStateException if getThread() is null.
*/
public void resumeExecution() {
// System.err.println("Resume Called");
if (runnableQueueThread == null) {
throw new IllegalStateException
("RunnableQueue not started or has exited");
}
synchronized (stateLock) {
wasResumed = true;
if (state != RUNNING) {
state = RUNNING;
stateLock.notifyAll(); // wake it up.
}
}
}
/**
* Returns iterator lock to use to work with the iterator
* returned by iterator().
*/
public Object getIteratorLock() {
return list;
}
/**
* Returns an iterator over the runnables.
*/
public Iterator iterator() {
return new Iterator() {
Link head = (Link)list.getHead();
Link link;
public boolean hasNext() {
if (head == null) {
return false;
}
if (link == null) {
return true;
}
return link != head;
}
public Object next() {
if (head == null || head == link) {
throw new java.util.NoSuchElementException();
}
if (link == null) {
link = (Link)head.getNext();
return head.runnable;
}
Object result = link.runnable;
link = (Link)link.getNext();
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Sets the RunHandler for this queue.
*/
public synchronized void setRunHandler(RunHandler rh) {
runHandler = rh;
}
/**
* Returns the RunHandler or null.
*/
public synchronized RunHandler getRunHandler() {
return runHandler;
}
/**
* Sets a Runnable to be run whenever the queue is empty.
*/
public synchronized void setIdleRunnable(Runnable r) {
idleRunnable = r;
}
/**
* Called when execution is being suspended.
* Currently just notifies runHandler
*/
protected synchronized void executionSuspended() {
// System.err.println("Suspend Sent");
if (runHandler != null) {
runHandler.executionSuspended(this);
}
}
/**
* Called when execution is being resumed.
* Currently just notifies runHandler
*/
protected synchronized void executionResumed() {
// System.err.println("Resumed Sent");
if (runHandler != null) {
runHandler.executionResumed(this);
}
}
/**
* Called just prior to executing a Runnable.
* Currently just notifies runHandler
* @param rable The runnable that is about to start
*/
protected synchronized void runnableStart(Runnable rable ) {
if (runHandler != null) {
runHandler.runnableStart(this, rable);
}
}
/**
* Called when a Runnable completes.
* Currently just notifies runHandler
* @param rable The runnable that just completed.
*/
protected synchronized void runnableInvoked(Runnable rable ) {
if (runHandler != null) {
runHandler.runnableInvoked(this, rable);
}
}
/**
* This interface must be implemented by an object which wants to
* be notified of run events.
*/
public interface RunHandler {
/**
* Called just prior to invoking the runnable
*/
void runnableStart(RunnableQueue rq, Runnable r);
/**
* Called when the given Runnable has just been invoked and
* has returned.
*/
void runnableInvoked(RunnableQueue rq, Runnable r);
/**
* Called when the execution of the queue has been suspended.
*/
void executionSuspended(RunnableQueue rq);
/**
* Called when the execution of the queue has been resumed.
*/
void executionResumed(RunnableQueue rq);
}
/**
* This is an adapter class that implements the RunHandler interface.
* It simply does nothing in response to the calls.
*/
public static class RunHandlerAdapter implements RunHandler {
/**
* Called just prior to invoking the runnable
*/
public void runnableStart(RunnableQueue rq, Runnable r) { }
/**
* Called when the given Runnable has just been invoked and
* has returned.
*/
public void runnableInvoked(RunnableQueue rq, Runnable r) { }
/**
* Called when the execution of the queue has been suspended.
*/
public void executionSuspended(RunnableQueue rq) { }
/**
* Called when the execution of the queue has been resumed.
*/
public void executionResumed(RunnableQueue rq) { }
}
/**
* To store a Runnable.
*/
protected static class Link extends DoublyLinkedList.Node {
/**
* The Runnable.
*/
public Runnable runnable;
/**
* Creates a new link.
*/
public Link(Runnable r) {
runnable = r;
}
/**
* unlock link and notify locker.
* Basic implementation does nothing.
*/
public void unlock() { return; }
}
/**
* To store a Runnable with an object waiting for him to be executed.
*/
protected static class LockableLink extends Link {
/**
* Whether this link is actually locked.
*/
protected boolean locked;
/**
* Creates a new link.
*/
public LockableLink(Runnable r) {
super(r);
}
/**
* Whether the link is actually locked.
*/
public boolean isLocked() {
return locked;
}
/**
* Locks this link.
*/
public synchronized void lock() throws InterruptedException {
locked = true;
notify();
wait();
}
/**
* unlocks this link.
*/
public synchronized void unlock() {
while (!locked) {
try {
wait(); // Wait until lock is called...
} catch (InterruptedException ie) {
// Loop again...
}
}
locked = false;
// Wake the locking thread...
notify();
}
}
}
| |
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2012 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.bean;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import net.sourceforge.servestream.dbutils.StreamDatabase;
import android.content.ContentValues;
import android.net.Uri;
public class UriBean {
public static final String BEAN_NAME = "uri";
/* Database fields */
private long id = -1;
private String nickname = null;
private String username = null;
private String password = null;
private String hostname = null;
private int port = -2;
private String path = null;
private String query = null;
private String reference = null;
private String protocol = null;
private long lastConnect = -1;
private String contentType = null;
private int listPosition = -1;
public UriBean() {
}
public String getBeanName() {
return BEAN_NAME;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getHostname() {
return hostname;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return port;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
public void setQuery(String query) {
this.query = query;
}
public String getQuery() {
return query;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getReference() {
return reference;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocol() {
return protocol;
}
public void setLastConnect(long lastConnect) {
this.lastConnect = lastConnect;
}
public long getLastConnect() {
return lastConnect;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
public void setListPosition(int listPosition) {
this.listPosition = listPosition;
}
public int getListPosition() {
return listPosition;
}
public String getDescription() {
String description = String.format("%s@%s", username, hostname);
if (port != 22)
description += String.format(":%d", port);
return description;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(StreamDatabase.FIELD_STREAM_NICKNAME, nickname);
values.put(StreamDatabase.FIELD_STREAM_PROTOCOL, protocol);
values.put(StreamDatabase.FIELD_STREAM_USERNAME, username);
values.put(StreamDatabase.FIELD_STREAM_PASSWORD, password);
values.put(StreamDatabase.FIELD_STREAM_HOSTNAME, hostname);
values.put(StreamDatabase.FIELD_STREAM_PORT, port);
values.put(StreamDatabase.FIELD_STREAM_PATH, path);
values.put(StreamDatabase.FIELD_STREAM_QUERY, query);
values.put(StreamDatabase.FIELD_STREAM_REFERENCE, reference);
values.put(StreamDatabase.FIELD_STREAM_LASTCONNECT, lastConnect);
values.put(StreamDatabase.FIELD_STREAM_LIST_POSITION, listPosition);
return values;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof UriBean))
return false;
UriBean host = (UriBean)o;
if (id != -1 && host.getId() != -1)
return host.getId() == id;
if (nickname == null) {
if (host.getNickname() != null)
return false;
} else if (!nickname.equals(host.getNickname()))
return false;
if (protocol == null) {
if (host.getProtocol() != null)
return false;
} else if (!protocol.equals(host.getProtocol()))
return false;
if (username == null) {
if (host.getUsername() != null)
return false;
} else if (!username.equals(host.getUsername()))
return false;
if (password == null) {
if (host.getPassword() != null)
return false;
} else if (!password.equals(host.getPassword()))
return false;
if (hostname == null) {
if (host.getHostname() != null)
return false;
} else if (!hostname.equals(host.getHostname()))
return false;
if (port != host.getPort())
return false;
if (path == null) {
if (host.getPath() != null)
return false;
} else if (!path.equals(host.getPath()))
return false;
if (query == null) {
if (host.getQuery() != null)
return false;
} else if (!query.equals(host.getQuery()))
return false;
if (reference == null) {
if (host.getReference() != null)
return false;
} else if (!reference.equals(host.getReference()))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
if (id != -1)
return (int)id;
hash = 31 * hash + (null == nickname ? 0 : nickname.hashCode());
hash = 31 * hash + (null == protocol ? 0 : protocol.hashCode());
hash = 31 * hash + (null == username ? 0 : username.hashCode());
hash = 31 * hash + (null == password ? 0 : password.hashCode());
hash = 31 * hash + (null == hostname ? 0 : hostname.hashCode());
hash = 31 * hash + port;
hash = 31 * hash + (null == path ? 0 : path.hashCode());
hash = 31 * hash + (null == query ? 0 : query.hashCode());
hash = 31 * hash + (null == reference ? 0 : reference.hashCode());
return hash;
}
/**
* @return URI identifying this HostBean
*/
public Uri getUri() {
StringBuilder sb = new StringBuilder();
sb.append(protocol)
.append("://");
if (username != null && password != null) {
sb.append(Uri.encode(username))
.append(":")
.append(password)
.append('@');
}
if (hostname != null) {
sb.append(hostname)
.append(':');
}
if (port != -2) {
sb.append(port);
}
if (path != null) {
sb.append(path);
}
if (query != null) {
sb.append("?")
.append(query);
}
if (reference != null) {
sb.append("#")
.append(reference);
}
return Uri.parse(sb.toString());
}
/**
* @return URI identifying this HostBean
*/
public Uri getScrubbedUri() {
StringBuilder sb = new StringBuilder();
sb.append(protocol)
.append("://");
if (hostname != null) {
sb.append(hostname)
.append(':');
}
if (port != -2) {
sb.append(port);
}
if (path != null) {
sb.append(path);
}
if (query != null) {
sb.append("?")
.append(query);
}
if (reference != null) {
sb.append("#")
.append(reference);
}
return Uri.parse(sb.toString());
}
/**
* @return URL identifying this HostBean
*/
public URL getScrubbedURL() {
URI encodedUri = null;
Uri uri = getScrubbedUri();
try {
encodedUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
}
URL url = null;
try {
url = encodedUri.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
public URL getURL() {
URI encodedUri = null;
Uri uri = getUri();
try {
encodedUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
}
URL url = null;
try {
url = encodedUri.toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
}
| |
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.client.thrift;
import static com.linecorp.armeria.common.SessionProtocol.H1C;
import static com.linecorp.armeria.common.SessionProtocol.H2C;
import static com.linecorp.armeria.common.SessionProtocol.HTTP;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.EnumSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.thrift.server.TServlet;
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linecorp.armeria.client.ClientBuilder;
import com.linecorp.armeria.client.Clients;
import com.linecorp.armeria.client.SessionProtocolNegotiationCache;
import com.linecorp.armeria.client.SessionProtocolNegotiationException;
import com.linecorp.armeria.common.ClosedSessionException;
import com.linecorp.armeria.common.RpcRequest;
import com.linecorp.armeria.common.RpcResponse;
import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.common.logging.RequestLogAvailability;
import com.linecorp.armeria.common.thrift.ThriftProtocolFactories;
import com.linecorp.armeria.service.test.thrift.main.HelloService;
import com.linecorp.armeria.service.test.thrift.main.HelloService.Processor;
/**
* Test to verify interaction between armeria client and official thrift
* library's {@link TServlet}.
*/
public class ThriftOverHttpClientTServletIntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(ThriftOverHttpClientTServletIntegrationTest.class);
private static final int MAX_RETRIES = 9;
private static final String TSERVLET_PATH = "/thrift";
@SuppressWarnings("unchecked")
private static final Servlet thriftServlet =
new TServlet(new Processor(name -> "Hello, " + name + '!'), ThriftProtocolFactories.BINARY);
private static final Servlet rootServlet = new HttpServlet() {
private static final long serialVersionUID = 6765028749367036441L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
resp.setStatus(404);
resp.setContentLength(0);
}
};
private static final AtomicBoolean sendConnectionClose = new AtomicBoolean();
private static Server http1server;
private static Server http2server;
@BeforeClass
public static void createServer() throws Exception {
http1server = startHttp1();
http2server = startHttp2();
}
private static Server startHttp1() throws Exception {
Server server = new Server(0);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
handler.addServletWithMapping(newServletHolder(rootServlet), "/");
handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*",
EnumSet.of(DispatcherType.REQUEST));
server.setHandler(handler);
for (Connector c : server.getConnectors()) {
for (ConnectionFactory f : c.getConnectionFactories()) {
for (String p : f.getProtocols()) {
if (p.startsWith("h2c")) {
fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " +
f.getProtocols());
}
}
}
}
server.start();
return server;
}
@Nonnull
private static ServletHolder newServletHolder(Servlet rootServlet) {
final ServletHolder holder = new ServletHolder(rootServlet);
holder.setInitParameter("cacheControl", "max-age=0, public");
return holder;
}
private static Server startHttp2() throws Exception {
Server server = new Server();
// Common HTTP configuration.
HttpConfiguration config = new HttpConfiguration();
// HTTP/1.1 support.
HttpConnectionFactory http1 = new HttpConnectionFactory(config);
// HTTP/2 cleartext support.
HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(config);
// Add the connector.
ServerConnector connector = new ServerConnector(server, http1, http2c);
connector.setPort(0);
server.addConnector(connector);
// Add the servlet.
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
server.setHandler(handler);
// Start the server.
server.start();
return server;
}
@AfterClass
public static void destroyServer() throws Exception {
CompletableFuture.runAsync(() -> {
if (http1server != null) {
try {
http1server.stop();
} catch (Exception e) {
logger.warn("Failed to stop HTTP/1 server", e);
}
}
if (http2server != null) {
try {
http2server.stop();
} catch (Exception e) {
logger.warn("Failed to stop HTTP/2 server", e);
}
}
});
}
@Before
public void setup() {
SessionProtocolNegotiationCache.clear();
sendConnectionClose.set(false);
}
@Test
public void sendHelloViaHttp1() throws Exception {
final AtomicReference<SessionProtocol> sessionProtocol = new AtomicReference<>();
final HelloService.Iface client = newSchemeCapturingClient(http1uri(HTTP), sessionProtocol);
for (int i = 0; i <= MAX_RETRIES; i++) {
try {
assertEquals("Hello, old world!", client.hello("old world"));
assertThat(sessionProtocol.get()).isEqualTo(H1C);
if (i != 0) {
logger.warn("Succeeded after {} retries.", i);
}
break;
} catch (ClosedSessionException e) {
// Flaky test; try again.
// FIXME(trustin): Fix flakiness.
if (i == MAX_RETRIES) {
throw e;
}
}
}
}
/**
* When an upgrade request is rejected with 'Connection: close', the client should retry the connection
* attempt silently with explicit H1C.
*/
@Test
public void sendHelloViaHttp1WithConnectionClose() throws Exception {
sendConnectionClose.set(true);
final AtomicReference<SessionProtocol> sessionProtocol = new AtomicReference<>();
final HelloService.Iface client = newSchemeCapturingClient(http1uri(HTTP), sessionProtocol);
for (int i = 0; i <= MAX_RETRIES; i++) {
try {
assertEquals("Hello, ancient world!", client.hello("ancient world"));
assertThat(sessionProtocol.get()).isEqualTo(H1C);
if (i != 0) {
logger.warn("Succeeded after {} retries.", i);
}
break;
} catch (ClosedSessionException e) {
// Flaky test; try again.
// FIXME(trustin): Fix flakiness.
if (i == MAX_RETRIES) {
throw e;
}
}
}
}
@Test
public void sendHelloViaHttp2() throws Exception {
final AtomicReference<SessionProtocol> sessionProtocol = new AtomicReference<>();
final HelloService.Iface client = newSchemeCapturingClient(http2uri(HTTP), sessionProtocol);
assertEquals("Hello, new world!", client.hello("new world"));
assertThat(sessionProtocol.get()).isEqualTo(H2C);
}
/**
* {@link SessionProtocolNegotiationException} should be raised if a user specified H2C explicitly and the
* client failed to upgrade.
*/
@Test
public void testRejectedUpgrade() throws Exception {
final InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", http1Port());
assertFalse(SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C));
final HelloService.Iface client =
Clients.newClient(http1uri(H2C), HelloService.Iface.class);
try {
client.hello("unused");
fail();
} catch (SessionProtocolNegotiationException e) {
// Test if a failed upgrade attempt triggers an exception with
// both 'expected' and 'actual' protocols.
assertThat(e.expected()).isEqualTo(H2C);
assertThat(e.actual()).contains(H1C);
// .. and if the negotiation cache is updated.
assertTrue(SessionProtocolNegotiationCache.isUnsupported(remoteAddress, H2C));
}
try {
client.hello("unused");
fail();
} catch (SessionProtocolNegotiationException e) {
// Test if no upgrade attempt is made thanks to the cache.
assertThat(e.expected()).isEqualTo(H2C);
// It has no idea about the actual protocol, because it did not create any connection.
assertThat(e.actual().isPresent()).isFalse();
}
}
private static HelloService.Iface newSchemeCapturingClient(
String uri, AtomicReference<SessionProtocol> sessionProtocol) {
return new ClientBuilder(uri)
.decorator(RpcRequest.class, RpcResponse.class,
(delegate, ctx, req) -> {
ctx.log().addListener(log -> sessionProtocol.set(log.sessionProtocol()),
RequestLogAvailability.REQUEST_START);
return delegate.execute(ctx, req);
})
.build(HelloService.Iface.class);
}
private static String http1uri(SessionProtocol protocol) {
return "tbinary+" + protocol.uriText() + "://127.0.0.1:" + http1Port() + TSERVLET_PATH;
}
private static int http1Port() {
return ((NetworkConnector) http1server.getConnectors()[0]).getLocalPort();
}
private static String http2uri(SessionProtocol protocol) {
return "tbinary+" + protocol.uriText() + "://127.0.0.1:" + http2Port() + TSERVLET_PATH;
}
private static int http2Port() {
return ((NetworkConnector) http2server.getConnectors()[0]).getLocalPort();
}
private static class ConnectionCloseFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
if (sendConnectionClose.get()) {
((HttpServletResponse) response).setHeader("Connection", "close");
}
}
@Override
public void destroy() {}
}
}
| |
/*
* You are free to use this code anywhere, copy, modify and redistribute at your
* own risk.
* Your are solely responsibly for any damage that may occur by using this code.
*
* This code is not tested for all boundary conditions. Use it at your own risk.
*
* Original code: http://www.newthinktank.com/2013/03/binary-tree-in-java/
*/
package com.zhokhov.interview.data;
/**
* @author <a href='mailto:alexey@zhokhov.com'>Alexey Zhokhov</a>
*/
public class BinaryTree {
private class Node {
int key;
String name;
Node leftChild;
Node rightChild;
//Node parent;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return name + " has the key " + key;
/*
* return name + " has the key " + key + "\nLeft Child: " + leftChild +
* "\nRight Child: " + rightChild + "\n";
*/
}
}
Node root;
public void addNode(int key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
// root is the top parent so we start
// there
parent = focusNode;
// Check if the new node should go on
// the left side of the parent node
if (key < focusNode.key) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
// All nodes are visited in ascending order
// Recursion is used to go to one node and
// then go to its child nodes and so forth
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
// Traverse the left node
inOrderTraverseTree(focusNode.leftChild);
// Visit the currently focused on node
System.out.println(focusNode);
// Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
// Start at the top of the tree
Node focusNode = root;
// While we haven't found the Node
// keep looking
while (focusNode.key != key) {
// If we should search to the left
if (key < focusNode.key) {
// Shift the focus Node to the left child
focusNode = focusNode.leftChild;
} else {
// Shift the focus Node to the right child
focusNode = focusNode.rightChild;
}
// The node wasn't found
if (focusNode == null)
return null;
}
return focusNode;
}
// TODO
/*
int depth(Node u) {
int d = 0;
while (u != r) {
u = u.parent;
d++;
}
return d;
}
*/
int size(Node u) {
if (u == null) return 0;
return 1 + size(u.leftChild) + size(u.rightChild);
}
public static void main(String[] args) {
BinaryTree theTree = new BinaryTree();
theTree.addNode(50, "Boss");
theTree.addNode(25, "Vice President");
theTree.addNode(15, "Office Manager");
theTree.addNode(30, "Secretary");
theTree.addNode(75, "Sales Manager");
theTree.addNode(85, "Salesman 1");
// Different ways to traverse binary trees
// theTree.inOrderTraverseTree(theTree.root);
// theTree.preorderTraverseTree(theTree.root);
// theTree.postOrderTraverseTree(theTree.root);
// Find the node with key 75
System.out.println("\nNode with the key 75");
System.out.println(theTree.findNode(75));
}
}
| |
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb.internal.connection;
import com.mongodb.MongoException;
import com.mongodb.MongoTimeoutException;
import org.junit.Test;
import java.io.Closeable;
import java.util.function.Consumer;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ConcurrentPoolTest {
private ConcurrentPool<TestCloseable> pool;
@Test
public void testThatGetDecreasesAvailability() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
pool.get();
pool.get();
pool.get();
try {
pool.get(1, MILLISECONDS);
fail();
} catch (MongoTimeoutException e) {
// all good
}
}
@Test
public void testThatReleaseIncreasesAvailability() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
pool.get();
pool.get();
pool.release(pool.get());
assertNotNull(pool.get());
}
@Test
public void testThatGetReleasesPermitIfCreateFails() {
pool = new ConcurrentPool<TestCloseable>(1, new TestItemFactory(true));
try {
pool.get();
fail();
} catch (MongoException e) {
// expected
}
assertTrue(pool.acquirePermit(-1, MILLISECONDS));
}
@Test
public void testInUseCount() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
assertEquals(0, pool.getInUseCount());
TestCloseable closeable = pool.get();
assertEquals(1, pool.getInUseCount());
pool.release(closeable);
assertEquals(0, pool.getInUseCount());
}
@Test
public void testAvailableCount() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
assertEquals(0, pool.getAvailableCount());
TestCloseable closeable = pool.get();
assertEquals(0, pool.getAvailableCount());
pool.release(closeable);
assertEquals(1, pool.getAvailableCount());
closeable = pool.get();
pool.release(closeable, true);
assertEquals(0, pool.getAvailableCount());
}
@Test
public void testAddItemToPoolOnRelease() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
TestCloseable closeable = pool.get();
pool.release(closeable, false);
assertFalse(closeable.isClosed());
}
@Test
public void testCloseItemOnReleaseWithDiscard() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
TestCloseable closeable = pool.get();
pool.release(closeable, true);
assertTrue(closeable.isClosed());
}
@Test
public void testCloseAllItemsAfterPoolClosed() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
TestCloseable c1 = pool.get();
TestCloseable c2 = pool.get();
pool.release(c1);
pool.release(c2);
pool.close();
assertTrue(c1.isClosed());
assertTrue(c2.isClosed());
}
@Test
public void testCloseItemOnReleaseAfterPoolClosed() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
TestCloseable c1 = pool.get();
pool.close();
pool.release(c1);
assertTrue(c1.isClosed());
}
@Test
public void testEnsureMinSize() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
Consumer<TestCloseable> initAndRelease = connection -> pool.release(connection);
pool.ensureMinSize(0, initAndRelease);
assertEquals(0, pool.getAvailableCount());
pool.ensureMinSize(1, initAndRelease);
assertEquals(1, pool.getAvailableCount());
pool.ensureMinSize(1, initAndRelease);
assertEquals(1, pool.getAvailableCount());
pool.get();
pool.ensureMinSize(1, initAndRelease);
assertEquals(0, pool.getAvailableCount());
pool.ensureMinSize(4, initAndRelease);
assertEquals(3, pool.getAvailableCount());
}
@Test
public void whenEnsuringMinSizeShouldNotInitializePooledItemIfNotRequested() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
pool.ensureMinSize(1, pool::release);
assertFalse(pool.get().isInitialized());
}
@Test
public void whenEnsuringMinSizeShouldInitializePooledItemIfRequested() {
pool = new ConcurrentPool<TestCloseable>(3, new TestItemFactory());
pool.ensureMinSize(1, connection -> {
connection.initialized = true;
pool.release(connection);
});
assertTrue(pool.get().isInitialized());
}
@Test
public void testThatEnsuringMinSizeReleasesPermitIfCreateFails() {
pool = new ConcurrentPool<TestCloseable>(1, new TestItemFactory(true));
try {
pool.ensureMinSize(1, ignore -> fail());
fail();
} catch (MongoException e) {
// expected
}
assertTrue(pool.acquirePermit(-1, MILLISECONDS));
}
@Test
public void testPrune() {
pool = new ConcurrentPool<TestCloseable>(5, new TestItemFactory());
TestCloseable t1 = pool.get();
TestCloseable t2 = pool.get();
TestCloseable t3 = pool.get();
TestCloseable t4 = pool.get();
TestCloseable t5 = pool.get();
t1.shouldPrune = ConcurrentPool.Prune.YES;
t2.shouldPrune = ConcurrentPool.Prune.NO;
t3.shouldPrune = ConcurrentPool.Prune.YES;
t4.shouldPrune = ConcurrentPool.Prune.STOP;
t5.shouldPrune = null;
pool.release(t1);
pool.release(t2);
pool.release(t3);
pool.release(t4);
pool.release(t5);
pool.prune();
assertEquals(3, pool.getAvailableCount());
assertEquals(0, pool.getInUseCount());
assertTrue(t1.isClosed());
assertTrue(!t2.isClosed());
assertTrue(t3.isClosed());
assertTrue(!t4.isClosed());
assertTrue(!t5.isClosed());
}
class TestItemFactory implements ConcurrentPool.ItemFactory<TestCloseable> {
private final boolean shouldThrowOnCreate;
TestItemFactory() {
this(false);
}
TestItemFactory(final boolean shouldThrowOnCreate) {
this.shouldThrowOnCreate = shouldThrowOnCreate;
}
@Override
public TestCloseable create() {
if (shouldThrowOnCreate) {
throw new MongoException("This is a journey");
}
return new TestCloseable();
}
@Override
public void close(final TestCloseable closeable) {
closeable.close();
}
@Override
public ConcurrentPool.Prune shouldPrune(final TestCloseable testCloseable) {
return testCloseable.shouldPrune();
}
}
static class TestCloseable implements Closeable {
private boolean closed;
private ConcurrentPool.Prune shouldPrune;
private boolean initialized;
TestCloseable() {
}
@Override
public void close() {
closed = true;
}
boolean isClosed() {
return closed;
}
public boolean isInitialized() {
return initialized;
}
public ConcurrentPool.Prune shouldPrune() {
return shouldPrune;
}
}
}
| |
/*
* Copyright (c) 2012 - 2014 Ngewi Fet <ngewif@gmail.com>
* Copyright (c) 2014 Yongxin Wang <fefe.wyx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gnucash.android.ui.account;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import org.gnucash.android.R;
import org.gnucash.android.db.AccountsDbAdapter;
import org.gnucash.android.db.CommoditiesDbAdapter;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.model.Account;
import org.gnucash.android.model.AccountType;
import org.gnucash.android.model.Commodity;
import org.gnucash.android.model.Money;
import org.gnucash.android.ui.colorpicker.ColorPickerDialog;
import org.gnucash.android.ui.colorpicker.ColorPickerSwatch;
import org.gnucash.android.ui.colorpicker.ColorSquare;
import org.gnucash.android.ui.common.UxArgument;
import org.gnucash.android.util.CommoditiesCursorAdapter;
import org.gnucash.android.util.QualifiedAccountNameCursorAdapter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Fragment used for creating and editing accounts
* @author Ngewi Fet <ngewif@gmail.com>
* @author Yongxin Wang <fefe.wyx@gmail.com>
*/
public class AccountFormFragment extends Fragment {
/**
* Tag for the color picker dialog fragment
*/
public static final String COLOR_PICKER_DIALOG_TAG = "color_picker_dialog";
/**
* EditText for the name of the account to be created/edited
*/
@Bind(R.id.input_account_name) EditText mNameEditText;
@Bind(R.id.name_text_input_layout) TextInputLayout mTextInputLayout;
/**
* Spinner for selecting the currency of the account
* Currencies listed are those specified by ISO 4217
*/
@Bind(R.id.input_currency_spinner) Spinner mCurrencySpinner;
/**
* Accounts database adapter
*/
private AccountsDbAdapter mAccountsDbAdapter;
/**
* List of all currency codes (ISO 4217) supported by the app
*/
private List<String> mCurrencyCodes;
/**
* GUID of the parent account
* This value is set to the parent account of the transaction being edited or
* the account in which a new sub-account is being created
*/
private String mParentAccountUID = null;
/**
* Account ID of the root account
*/
private long mRootAccountId = -1;
/**
* Account UID of the root account
*/
private String mRootAccountUID = null;
/**
* Reference to account object which will be created at end of dialog
*/
private Account mAccount = null;
/**
* Unique ID string of account being edited
*/
private String mAccountUID = null;
/**
* Cursor which will hold set of eligible parent accounts
*/
private Cursor mParentAccountCursor;
/**
* List of all descendant Account UIDs, if we are modifying an account
* null if creating a new account
*/
private List<String> mDescendantAccountUIDs;
/**
* SimpleCursorAdapter for the parent account spinner
* @see QualifiedAccountNameCursorAdapter
*/
private SimpleCursorAdapter mParentAccountCursorAdapter;
/**
* Spinner for parent account list
*/
@Bind(R.id.input_parent_account) Spinner mParentAccountSpinner;
/**
* Checkbox which activates the parent account spinner when selected
* Leaving this unchecked means it is a top-level root account
*/
@Bind(R.id.checkbox_parent_account) CheckBox mParentCheckBox;
/**
* Spinner for the account type
* @see org.gnucash.android.model.AccountType
*/
@Bind(R.id.input_account_type_spinner) Spinner mAccountTypeSpinner;
/**
* Checkbox for activating the default transfer account spinner
*/
@Bind(R.id.checkbox_default_transfer_account) CheckBox mDefaultTransferAccountCheckBox;
/**
* Spinner for selecting the default transfer account
*/
@Bind(R.id.input_default_transfer_account) Spinner mDefaulTransferAccountSpinner;
/**
* Account description input text view
*/
@Bind(R.id.input_account_description) EditText mDescriptionEditText;
/**
* Checkbox indicating if account is a placeholder account
*/
@Bind(R.id.checkbox_placeholder_account) CheckBox mPlaceholderCheckBox;
/**
* Cursor adapter which binds to the spinner for default transfer account
*/
private SimpleCursorAdapter mDefaultTransferAccountCursorAdapter;
/**
* Flag indicating if double entry transactions are enabled
*/
private boolean mUseDoubleEntry;
/**
* Default to transparent
*/
private String mSelectedColor = null;
/**
* Trigger for color picker dialog
*/
@Bind(R.id.input_color_picker) ColorSquare mColorSquare;
private ColorPickerSwatch.OnColorSelectedListener mColorSelectedListener = new ColorPickerSwatch.OnColorSelectedListener() {
@Override
public void onColorSelected(int color) {
mColorSquare.setBackgroundColor(color);
mSelectedColor = String.format("#%06X", (0xFFFFFF & color));
}
};
/**
* Default constructor
* Required, else the app crashes on screen rotation
*/
public AccountFormFragment() {
//nothing to see here, move along
}
/**
* Construct a new instance of the dialog
* @return New instance of the dialog fragment
*/
static public AccountFormFragment newInstance() {
AccountFormFragment f = new AccountFormFragment();
f.mAccountsDbAdapter = AccountsDbAdapter.getInstance();
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUseDoubleEntry = sharedPrefs.getBoolean(getString(R.string.key_use_double_entry), true);
}
/**
* Inflates the dialog view and retrieves references to the dialog elements
*/
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account_form, container, false);
ButterKnife.bind(this, view);
mNameEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//nothing to see here, move along
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//nothing to see here, move along
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
mTextInputLayout.setErrorEnabled(false);
}
}
});
mAccountTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
loadParentAccountList(getSelectedAccountType());
if (mParentAccountUID != null)
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
//nothing to see here, move along
}
});
mParentAccountSpinner.setEnabled(false);
mParentCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mParentAccountSpinner.setEnabled(isChecked);
}
});
mDefaulTransferAccountSpinner.setEnabled(false);
mDefaultTransferAccountCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mDefaulTransferAccountSpinner.setEnabled(isChecked);
}
});
mColorSquare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showColorPickerDialog();
}
});
return view;
}
/**
* Initializes the values of the views in the dialog
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CommoditiesCursorAdapter commoditiesAdapter = new CommoditiesCursorAdapter(
getActivity(), android.R.layout.simple_spinner_item);
commoditiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCurrencySpinner.setAdapter(commoditiesAdapter);
mAccountUID = getArguments().getString(UxArgument.SELECTED_ACCOUNT_UID);
ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (mAccountUID != null) {
mAccount = mAccountsDbAdapter.getRecord(mAccountUID);
supportActionBar.setTitle(R.string.title_edit_account);
} else {
supportActionBar.setTitle(R.string.title_create_account);
}
mRootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
if (mRootAccountUID != null)
mRootAccountId = mAccountsDbAdapter.getID(mRootAccountUID);
//need to load the cursor adapters for the spinners before initializing the views
loadAccountTypesList();
loadDefaultTransferAccountList();
setDefaultTransferAccountInputsVisible(mUseDoubleEntry);
if (mAccount != null){
initializeViewsWithAccount(mAccount);
//do not immediately open the keyboard when editing an account
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
} else {
initializeViews();
}
}
/**
* Initialize view with the properties of <code>account</code>.
* This is applicable when editing an account
* @param account Account whose fields are used to populate the form
*/
private void initializeViewsWithAccount(Account account){
if (account == null)
throw new IllegalArgumentException("Account cannot be null");
loadParentAccountList(account.getAccountType());
mParentAccountUID = account.getParentUID();
if (mParentAccountUID == null) {
// null parent, set Parent as root
mParentAccountUID = mRootAccountUID;
}
if (mParentAccountUID != null) {
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
String currencyCode = account.getCurrency().getCurrencyCode();
setSelectedCurrency(currencyCode);
if (mAccountsDbAdapter.getTransactionMaxSplitNum(mAccount.getUID()) > 1)
{
//TODO: Allow changing the currency and effecting the change for all transactions without any currency exchange (purely cosmetic change)
mCurrencySpinner.setEnabled(false);
}
mNameEditText.setText(account.getName());
mNameEditText.setSelection(mNameEditText.getText().length());
if (account.getDescription() != null)
mDescriptionEditText.setText(account.getDescription());
if (mUseDoubleEntry) {
if (account.getDefaultTransferAccountUID() != null) {
long doubleDefaultAccountId = mAccountsDbAdapter.getID(account.getDefaultTransferAccountUID());
setDefaultTransferAccountSelection(doubleDefaultAccountId, true);
} else {
String currentAccountUID = account.getParentUID();
long defaultTransferAccountID = 0;
String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
while (!currentAccountUID.equals(rootAccountUID)) {
defaultTransferAccountID = mAccountsDbAdapter.getDefaultTransferAccountID(mAccountsDbAdapter.getID(currentAccountUID));
if (defaultTransferAccountID > 0) {
setDefaultTransferAccountSelection(defaultTransferAccountID, false);
break; //we found a parent with default transfer setting
}
currentAccountUID = mAccountsDbAdapter.getParentAccountUID(currentAccountUID);
}
}
}
mPlaceholderCheckBox.setChecked(account.isPlaceholderAccount());
initializeColorSquarePreview(account.getColorHexCode());
setAccountTypeSelection(account.getAccountType());
}
/**
* Initialize views with defaults for new account
*/
private void initializeViews(){
setSelectedCurrency(Money.DEFAULT_CURRENCY_CODE);
mColorSquare.setBackgroundColor(Color.LTGRAY);
mParentAccountUID = getArguments().getString(UxArgument.PARENT_ACCOUNT_UID);
if (mParentAccountUID != null) {
AccountType parentAccountType = mAccountsDbAdapter.getAccountType(mParentAccountUID);
setAccountTypeSelection(parentAccountType);
loadParentAccountList(parentAccountType);
setParentAccountSelection(mAccountsDbAdapter.getID(mParentAccountUID));
}
}
/**
* Initializes the preview of the color picker (color square) to the specified color
* @param colorHex Color of the format #rgb or #rrggbb
*/
private void initializeColorSquarePreview(String colorHex){
if (colorHex != null)
mColorSquare.setBackgroundColor(Color.parseColor(colorHex));
else
mColorSquare.setBackgroundColor(Color.LTGRAY);
}
/**
* Selects the corresponding account type in the spinner
* @param accountType AccountType to be set
*/
private void setAccountTypeSelection(AccountType accountType){
String[] accountTypeEntries = getResources().getStringArray(R.array.key_account_type_entries);
int accountTypeIndex = Arrays.asList(accountTypeEntries).indexOf(accountType.name());
mAccountTypeSpinner.setSelection(accountTypeIndex);
}
/**
* Toggles the visibility of the default transfer account input fields.
* This field is irrelevant for users who do not use double accounting
*/
private void setDefaultTransferAccountInputsVisible(boolean visible) {
final int visibility = visible ? View.VISIBLE : View.GONE;
final View view = getView();
assert view != null;
view.findViewById(R.id.layout_default_transfer_account).setVisibility(visibility);
view.findViewById(R.id.label_default_transfer_account).setVisibility(visibility);
}
/**
* Selects the currency with code <code>currencyCode</code> in the spinner
* @param currencyCode ISO 4217 currency code to be selected
*/
private void setSelectedCurrency(String currencyCode){
CommoditiesDbAdapter commodityDbAdapter = CommoditiesDbAdapter.getInstance();
long commodityId = commodityDbAdapter.getID(commodityDbAdapter.getCommodityUID(currencyCode));
int position = 0;
for (int i = 0; i < mCurrencySpinner.getCount(); i++) {
if (commodityId == mCurrencySpinner.getItemIdAtPosition(i)) {
position = i;
}
}
mCurrencySpinner.setSelection(position);
}
/**
* Selects the account with ID <code>parentAccountId</code> in the parent accounts spinner
* @param parentAccountId Record ID of parent account to be selected
*/
private void setParentAccountSelection(long parentAccountId){
if (parentAccountId <= 0 || parentAccountId == mRootAccountId) {
return;
}
for (int pos = 0; pos < mParentAccountCursorAdapter.getCount(); pos++) {
if (mParentAccountCursorAdapter.getItemId(pos) == parentAccountId){
mParentCheckBox.setChecked(true);
mParentAccountSpinner.setEnabled(true);
mParentAccountSpinner.setSelection(pos, true);
break;
}
}
}
/**
* Selects the account with ID <code>parentAccountId</code> in the default transfer account spinner
* @param defaultTransferAccountId Record ID of parent account to be selected
*/
private void setDefaultTransferAccountSelection(long defaultTransferAccountId, boolean enableTransferAccount) {
if (defaultTransferAccountId > 0) {
mDefaultTransferAccountCheckBox.setChecked(enableTransferAccount);
mDefaulTransferAccountSpinner.setEnabled(enableTransferAccount);
} else
return;
for (int pos = 0; pos < mDefaultTransferAccountCursorAdapter.getCount(); pos++) {
if (mDefaultTransferAccountCursorAdapter.getItemId(pos) == defaultTransferAccountId) {
mDefaulTransferAccountSpinner.setSelection(pos);
break;
}
}
}
/**
* Returns an array of colors used for accounts.
* The array returned has the actual color values and not the resource ID.
* @return Integer array of colors used for accounts
*/
private int[] getAccountColorOptions(){
Resources res = getResources();
TypedArray colorTypedArray = res.obtainTypedArray(R.array.account_colors);
int[] colorOptions = new int[colorTypedArray.length()];
for (int i = 0; i < colorTypedArray.length(); i++) {
int color = colorTypedArray.getColor(i, R.color.title_green);
colorOptions[i] = color;
}
return colorOptions;
}
/**
* Shows the color picker dialog
*/
private void showColorPickerDialog(){
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
int currentColor = Color.LTGRAY;
if (mAccount != null){
String accountColor = mAccount.getColorHexCode();
if (accountColor != null){
currentColor = Color.parseColor(accountColor);
}
}
ColorPickerDialog colorPickerDialogFragment = ColorPickerDialog.newInstance(
R.string.color_picker_default_title,
getAccountColorOptions(),
currentColor, 4, 12);
colorPickerDialogFragment.setOnColorSelectedListener(mColorSelectedListener);
colorPickerDialogFragment.show(fragmentManager, COLOR_PICKER_DIALOG_TAG);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.default_save_actions, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
saveAccount();
return true;
case android.R.id.home:
finishFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Initializes the default transfer account spinner with eligible accounts
*/
private void loadDefaultTransferAccountList(){
String condition = DatabaseSchema.AccountEntry.COLUMN_UID + " != '" + mAccountUID + "' " //when creating a new account mAccountUID is null, so don't use whereArgs
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + "=0"
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + "=0"
+ " AND " + DatabaseSchema.AccountEntry.COLUMN_TYPE + " != ?";
Cursor defaultTransferAccountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(condition,
new String[]{AccountType.ROOT.name()});
if (mDefaulTransferAccountSpinner.getCount() <= 0) {
setDefaultTransferAccountInputsVisible(false);
}
mDefaultTransferAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(),
defaultTransferAccountCursor);
mDefaulTransferAccountSpinner.setAdapter(mDefaultTransferAccountCursorAdapter);
}
/**
* Loads the list of possible accounts which can be set as a parent account and initializes the spinner.
* The allowed parent accounts depends on the account type
* @param accountType AccountType of account whose allowed parent list is to be loaded
*/
private void loadParentAccountList(AccountType accountType){
String condition = DatabaseSchema.SplitEntry.COLUMN_TYPE + " IN ("
+ getAllowedParentAccountTypes(accountType) + ") AND " + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + "!=1 ";
if (mAccount != null){ //if editing an account
mDescendantAccountUIDs = mAccountsDbAdapter.getDescendantAccountUIDs(mAccount.getUID(), null, null);
String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID();
List<String> descendantAccountUIDs = new ArrayList<>(mDescendantAccountUIDs);
if (rootAccountUID != null)
descendantAccountUIDs.add(rootAccountUID);
// limit cyclic account hierarchies.
condition += " AND (" + DatabaseSchema.AccountEntry.COLUMN_UID + " NOT IN ( '"
+ TextUtils.join("','", descendantAccountUIDs) + "','" + mAccountUID + "' ) )";
}
//if we are reloading the list, close the previous cursor first
if (mParentAccountCursor != null)
mParentAccountCursor.close();
mParentAccountCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(condition, null);
final View view = getView();
assert view != null;
if (mParentAccountCursor.getCount() <= 0){
mParentCheckBox.setChecked(false); //disable before hiding, else we can still read it when saving
view.findViewById(R.id.layout_parent_account).setVisibility(View.GONE);
view.findViewById(R.id.label_parent_account).setVisibility(View.GONE);
} else {
view.findViewById(R.id.layout_parent_account).setVisibility(View.VISIBLE);
view.findViewById(R.id.label_parent_account).setVisibility(View.VISIBLE);
}
mParentAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(
getActivity(), mParentAccountCursor);
mParentAccountSpinner.setAdapter(mParentAccountCursorAdapter);
}
/**
* Returns a comma separated list of account types which can be parent accounts for the specified <code>type</code>.
* The strings in the list are the {@link org.gnucash.android.model.AccountType#name()}s of the different types.
* @param type {@link org.gnucash.android.model.AccountType}
* @return String comma separated list of account types
*/
private String getAllowedParentAccountTypes(AccountType type) {
switch (type) {
case EQUITY:
return "'" + AccountType.EQUITY.name() + "'";
case INCOME:
case EXPENSE:
return "'" + AccountType.EXPENSE.name() + "', '" + AccountType.INCOME.name() + "'";
case CASH:
case BANK:
case CREDIT:
case ASSET:
case LIABILITY:
case PAYABLE:
case RECEIVABLE:
case CURRENCY:
case STOCK:
case MUTUAL: {
List<String> accountTypeStrings = getAccountTypeStringList();
accountTypeStrings.remove(AccountType.EQUITY.name());
accountTypeStrings.remove(AccountType.EXPENSE.name());
accountTypeStrings.remove(AccountType.INCOME.name());
accountTypeStrings.remove(AccountType.ROOT.name());
return "'" + TextUtils.join("','", accountTypeStrings) + "'";
}
case TRADING:
return "'" + AccountType.TRADING.name() + "'";
case ROOT:
default:
return Arrays.toString(AccountType.values()).replaceAll("\\[|]", "");
}
}
/**
* Returns a list of all the available {@link org.gnucash.android.model.AccountType}s as strings
* @return String list of all account types
*/
private List<String> getAccountTypeStringList(){
String[] accountTypes = Arrays.toString(AccountType.values()).replaceAll("\\[|]", "").split(",");
List<String> accountTypesList = new ArrayList<String>();
for (String accountType : accountTypes) {
accountTypesList.add(accountType.trim());
}
return accountTypesList;
}
/**
* Loads the list of account types into the account type selector spinner
*/
private void loadAccountTypesList(){
String[] accountTypes = getResources().getStringArray(R.array.account_type_entry_values);
ArrayAdapter<String> accountTypesAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1, accountTypes);
accountTypesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAccountTypeSpinner.setAdapter(accountTypesAdapter);
}
/**
* Finishes the fragment appropriately.
* Depends on how the fragment was loaded, it might have a backstack or not
*/
private void finishFragment() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mNameEditText.getWindowToken(), 0);
final String action = getActivity().getIntent().getAction();
if (action != null && action.equals(Intent.ACTION_INSERT_OR_EDIT)){
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} else {
getActivity().getSupportFragmentManager().popBackStack();
}
}
@Override
public void onDestroy() {
super.onDestroyView();
if (mParentAccountCursor != null)
mParentAccountCursor.close();
if (mDefaultTransferAccountCursorAdapter != null) {
mDefaultTransferAccountCursorAdapter.getCursor().close();
}
}
/**
* Reads the fields from the account form and saves as a new account
*/
private void saveAccount() {
Log.i("AccountFormFragment", "Saving account");
// accounts to update, in case we're updating full names of a sub account tree
ArrayList<Account> accountsToUpdate = new ArrayList<>();
boolean nameChanged = false;
if (mAccount == null){
String name = getEnteredName();
if (name == null || name.length() == 0){
mTextInputLayout.setErrorEnabled(true);
mTextInputLayout.setError(getString(R.string.toast_no_account_name_entered));
return;
}
mAccount = new Account(getEnteredName());
}
else {
nameChanged = !mAccount.getName().equals(getEnteredName());
mAccount.setName(getEnteredName());
}
long commodityId = mCurrencySpinner.getSelectedItemId();
Commodity commodity = CommoditiesDbAdapter.getInstance().getRecord(commodityId);
mAccount.setCommodity(commodity);
AccountType selectedAccountType = getSelectedAccountType();
mAccount.setAccountType(selectedAccountType);
mAccount.setDescription(mDescriptionEditText.getText().toString());
mAccount.setPlaceHolderFlag(mPlaceholderCheckBox.isChecked());
mAccount.setColorCode(mSelectedColor);
long newParentAccountId;
String newParentAccountUID;
if (mParentCheckBox.isChecked()) {
newParentAccountId = mParentAccountSpinner.getSelectedItemId();
newParentAccountUID = mAccountsDbAdapter.getUID(newParentAccountId);
mAccount.setParentUID(newParentAccountUID);
} else {
//need to do this explicitly in case user removes parent account
newParentAccountUID = mRootAccountUID;
newParentAccountId = mRootAccountId;
}
mAccount.setParentUID(newParentAccountUID);
if (mDefaultTransferAccountCheckBox.isChecked()){
long id = mDefaulTransferAccountSpinner.getSelectedItemId();
mAccount.setDefaultTransferAccountUID(mAccountsDbAdapter.getUID(id));
} else {
//explicitly set in case of removal of default account
mAccount.setDefaultTransferAccountUID(null);
}
long parentAccountId = mParentAccountUID == null ? -1 : mAccountsDbAdapter.getID(mParentAccountUID);
// update full names
if (nameChanged || mDescendantAccountUIDs == null || newParentAccountId != parentAccountId) {
// current account name changed or new Account or parent account changed
String newAccountFullName;
if (newParentAccountId == mRootAccountId){
newAccountFullName = mAccount.getName();
}
else {
newAccountFullName = mAccountsDbAdapter.getAccountFullName(newParentAccountUID) +
AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + mAccount.getName();
}
mAccount.setFullName(newAccountFullName);
if (mDescendantAccountUIDs != null) {
// modifying existing account, e.t. name changed and/or parent changed
if ((nameChanged || parentAccountId != newParentAccountId) && mDescendantAccountUIDs.size() > 0) {
// parent change, update all full names of descent accounts
accountsToUpdate.addAll(mAccountsDbAdapter.getSimpleAccountList(
DatabaseSchema.AccountEntry.COLUMN_UID + " IN ('" +
TextUtils.join("','", mDescendantAccountUIDs) + "')",
null,
null
));
}
HashMap<String, Account> mapAccount = new HashMap<String, Account>();
for (Account acct : accountsToUpdate) mapAccount.put(acct.getUID(), acct);
for (String uid: mDescendantAccountUIDs) {
// mAccountsDbAdapter.getDescendantAccountUIDs() will ensure a parent-child order
Account acct = mapAccount.get(uid);
// mAccount cannot be root, so acct here cannot be top level account.
if (mAccount.getUID().equals(acct.getParentUID())) {
acct.setFullName(mAccount.getFullName() + AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR + acct.getName());
}
else {
acct.setFullName(
mapAccount.get(acct.getParentUID()).getFullName() +
AccountsDbAdapter.ACCOUNT_NAME_SEPARATOR +
acct.getName()
);
}
}
}
}
accountsToUpdate.add(mAccount);
if (mAccountsDbAdapter == null)
mAccountsDbAdapter = AccountsDbAdapter.getInstance();
// bulk update, will not update transactions
mAccountsDbAdapter.enableForeignKey(false);
mAccountsDbAdapter.bulkAddRecords(accountsToUpdate);
mAccountsDbAdapter.enableForeignKey(true);
finishFragment();
}
/**
* Returns the currently selected account type in the spinner
* @return {@link org.gnucash.android.model.AccountType} currently selected
*/
private AccountType getSelectedAccountType() {
int selectedAccountTypeIndex = mAccountTypeSpinner.getSelectedItemPosition();
String[] accountTypeEntries = getResources().getStringArray(R.array.key_account_type_entries);
return AccountType.valueOf(accountTypeEntries[selectedAccountTypeIndex]);
}
/**
* Retrieves the name of the account which has been entered in the EditText
* @return Name of the account which has been entered in the EditText
*/
public String getEnteredName(){
return mNameEditText.getText().toString().trim();
}
}
| |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.singlethreader;
import java.io.IOException;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ObjectLocationSpecificationMethod;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.RepositoryElementMetaInterface;
import org.pentaho.di.repository.RepositoryObject;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.singlethreader.SingleThreaderMeta;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.LabelTextVar;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.repository.dialog.SelectObjectDialog;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.vfs.ui.VfsFileChooserDialog;
public class SingleThreaderDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = SingleThreaderMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private SingleThreaderMeta singleThreaderMeta;
private Group gTransGroup;
// File
//
private Button radioFilename;
private Button wbbFilename;
private TextVar wFilename;
// Repository by name
//
private Button radioByName;
private TextVar wTransname, wDirectory;
private Button wbTrans;
// Repository by reference
//
private Button radioByReference;
private Button wbByReference;
private TextVar wByReference;
// Edit the mapping transformation in Spoon
//
private Button wEditTrans;
private LabelTextVar wBatchSize;
private LabelTextVar wInjectStep;
private Button wGetInjectStep;
private LabelTextVar wRetrieveStep;
private Button wGetRetrieveStep;
private TableView wParameters;
private TransMeta mappingTransMeta = null;
protected boolean transModified;
private ModifyListener lsMod;
private int middle;
private int margin;
private ObjectId referenceObjectId;
private ObjectLocationSpecificationMethod specificationMethod;
private Group gParametersGroup;
private Button wPassParams;
private Button wbGetParams;
private LabelTextVar wBatchTime;
public SingleThreaderDialog(Shell parent, Object in, TransMeta tr, String sname)
{
super(parent, (BaseStepMeta) in, tr, sname);
singleThreaderMeta = (SingleThreaderMeta) in;
transModified = false;
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, singleThreaderMeta);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
singleThreaderMeta.setChanged();
}
};
changed = singleThreaderMeta.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Shell.Title")); //$NON-NLS-1$
middle = props.getMiddlePct();
margin = Const.MARGIN;
// Stepname line
wlStepname = new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right = new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname = new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right = new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// Show a group with 2 main options: a transformation in the repository
// or on file
//
// //////////////////////////////////////////////////
// The sub-transformation definition box
// //////////////////////////////////////////////////
//
gTransGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
gTransGroup.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.TransGroup.Label")); //$NON-NLS-1$;
gTransGroup.setBackground(shell.getBackground()); // the default looks
// ugly
FormLayout transGroupLayout = new FormLayout();
transGroupLayout.marginLeft = margin * 2;
transGroupLayout.marginTop = margin * 2;
transGroupLayout.marginRight = margin * 2;
transGroupLayout.marginBottom = margin * 2;
gTransGroup.setLayout(transGroupLayout);
// Radio button: The mapping is in a file
//
radioFilename = new Button(gTransGroup, SWT.RADIO);
props.setLook(radioFilename);
radioFilename.setSelection(false);
radioFilename.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioFile.Label")); //$NON-NLS-1$
radioFilename.setToolTipText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioFile.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdFileRadio = new FormData();
fdFileRadio.left = new FormAttachment(0, 0);
fdFileRadio.right = new FormAttachment(100, 0);
fdFileRadio.top = new FormAttachment(0, 0);
radioFilename.setLayoutData(fdFileRadio);
radioFilename.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.FILENAME;
setRadioButtons();
}
});
wbbFilename = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbbFilename);
wbbFilename.setText(BaseMessages.getString(PKG, "System.Button.Browse"));
wbbFilename.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbFilename = new FormData();
fdbFilename.right = new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(radioFilename, margin);
wbbFilename.setLayoutData(fdbFilename);
wbbFilename.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e)
{
selectFileTrans();
}
});
wFilename = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
FormData fdFilename = new FormData();
fdFilename.left = new FormAttachment(0, 25);
fdFilename.right = new FormAttachment(wbbFilename, -margin);
fdFilename.top = new FormAttachment(wbbFilename, 0, SWT.CENTER);
wFilename.setLayoutData(fdFilename);
wFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e)
{
specificationMethod=ObjectLocationSpecificationMethod.FILENAME;
setRadioButtons();
}
});
// Radio button: The mapping is in the repository
//
radioByName = new Button(gTransGroup, SWT.RADIO);
props.setLook(radioByName);
radioByName.setSelection(false);
radioByName.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioRep.Label")); //$NON-NLS-1$
radioByName.setToolTipText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioRep.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdRepRadio = new FormData();
fdRepRadio.left = new FormAttachment(0, 0);
fdRepRadio.right = new FormAttachment(100, 0);
fdRepRadio.top = new FormAttachment(wbbFilename, 2 * margin);
radioByName.setLayoutData(fdRepRadio);
radioByName.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME;
setRadioButtons();
}
});
wbTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbTrans);
wbTrans.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Select.Button"));
wbTrans.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbTrans = new FormData();
fdbTrans.right = new FormAttachment(100, 0);
fdbTrans.top = new FormAttachment(radioByName, 2 * margin);
wbTrans.setLayoutData(fdbTrans);
wbTrans.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e)
{
selectRepositoryTrans();
}
});
wDirectory = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDirectory);
wDirectory.addModifyListener(lsMod);
FormData fdTransDir = new FormData();
fdTransDir.left = new FormAttachment(middle + (100 - middle) / 2, 0);
fdTransDir.right = new FormAttachment(wbTrans, -margin);
fdTransDir.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wDirectory.setLayoutData(fdTransDir);
wDirectory.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME;
setRadioButtons();
}
});
wTransname = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransname);
wTransname.addModifyListener(lsMod);
FormData fdTransName = new FormData();
fdTransName.left = new FormAttachment(0, 25);
fdTransName.right = new FormAttachment(wDirectory, -margin);
fdTransName.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wTransname.setLayoutData(fdTransName);
wTransname.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME;
setRadioButtons();
}
});
// Radio button: The mapping is in the repository
//
radioByReference = new Button(gTransGroup, SWT.RADIO);
props.setLook(radioByReference);
radioByReference.setSelection(false);
radioByReference.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioRepByReference.Label")); //$NON-NLS-1$
radioByReference.setToolTipText(BaseMessages.getString(PKG, "SingleThreaderDialog.RadioRepByReference.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdRadioByReference = new FormData();
fdRadioByReference.left = new FormAttachment(0, 0);
fdRadioByReference.right = new FormAttachment(100, 0);
fdRadioByReference.top = new FormAttachment(wTransname, 2 * margin);
radioByReference.setLayoutData(fdRadioByReference);
radioByReference.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE;
setRadioButtons();
}
});
wbByReference = new Button(gTransGroup, SWT.PUSH | SWT.CENTER);
props.setLook(wbByReference);
wbByReference.setImage(GUIResource.getInstance().getImageTransGraph());
wbByReference.setToolTipText(BaseMessages.getString(PKG, "SingleThreaderDialog.SelectTrans.Tooltip"));
FormData fdbByReference = new FormData();
fdbByReference.top = new FormAttachment(radioByReference, margin);
fdbByReference.right = new FormAttachment(100, 0);
wbByReference.setLayoutData(fdbByReference);
wbByReference.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selectTransformationByReference();
}
});
wByReference = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.READ_ONLY);
props.setLook(wByReference);
wByReference.addModifyListener(lsMod);
FormData fdByReference = new FormData();
fdByReference.top = new FormAttachment(radioByReference, margin);
fdByReference.left = new FormAttachment(0, 25);
fdByReference.right = new FormAttachment(wbByReference, -margin);
wByReference.setLayoutData(fdByReference);
wByReference.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE;
setRadioButtons();
}
});
wEditTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wEditTrans);
wEditTrans.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Edit.Button"));
wEditTrans.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdEditTrans = new FormData();
fdEditTrans.left = new FormAttachment(0, 0);
fdEditTrans.right = new FormAttachment(100, 0);
fdEditTrans.top = new FormAttachment(wByReference, 3 * margin);
wEditTrans.setLayoutData(fdEditTrans);
wEditTrans.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e)
{
editTrans();
}
});
FormData fdTransGroup = new FormData();
fdTransGroup.left = new FormAttachment(0, 0);
fdTransGroup.top = new FormAttachment(wStepname, 2 * margin);
fdTransGroup.right = new FormAttachment(100, 0);
// fdTransGroup.bottom = new FormAttachment(wStepname, 350);
gTransGroup.setLayoutData(fdTransGroup);
// Inject step
//
wGetInjectStep = new Button(shell, SWT.PUSH);
wGetInjectStep.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Button.Get"));
FormData fdGetInjectStep = new FormData();
fdGetInjectStep.top = new FormAttachment(gTransGroup, margin);
fdGetInjectStep.right = new FormAttachment(100, 0);
wGetInjectStep.setLayoutData(fdGetInjectStep);
wGetInjectStep.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
try {
loadTransformation();
String stepname = mappingTransMeta==null ? "" : Const.NVL(getInjectorStep(mappingTransMeta), "");
wInjectStep.setText(stepname);
} catch(Exception e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogTitle"),
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
});
wInjectStep = new LabelTextVar(transMeta, shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.InjectStep.Label"),
BaseMessages.getString(PKG, "SingleThreaderDialog.InjectStep.Tooltip")
);
FormData fdInjectStep = new FormData();
fdInjectStep.left = new FormAttachment(0, 0);
fdInjectStep.top = new FormAttachment(gTransGroup, 2*margin);
fdInjectStep.right = new FormAttachment(wGetInjectStep, -margin);
wInjectStep.setLayoutData(fdInjectStep);
// Retrieve step...
//
wGetRetrieveStep = new Button(shell, SWT.PUSH);
wGetRetrieveStep.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.Button.Get"));
FormData fdGetRetrieveStep = new FormData();
fdGetRetrieveStep.top = new FormAttachment(wInjectStep, 2*margin);
fdGetRetrieveStep.right = new FormAttachment(100, 0);
wGetRetrieveStep.setLayoutData(fdGetRetrieveStep);
wGetRetrieveStep.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
try {
loadTransformation();
if (mappingTransMeta!=null) {
String[] stepNames = mappingTransMeta.getStepNames();
EnterSelectionDialog d = new EnterSelectionDialog(shell, stepNames,
BaseMessages.getString(PKG, "SingleThreaderDialog.SelectStep.Title"),
BaseMessages.getString(PKG, "SingleThreaderDialog.SelectStep.Message"));
String step = d.open();
if (step!=null) {
wRetrieveStep.setText(step);
}
}
} catch(Exception e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogTitle"),
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
});
wRetrieveStep = new LabelTextVar(transMeta, shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.RetrieveStep.Label"),
BaseMessages.getString(PKG, "SingleThreaderDialog.RetrieveStep.Tooltip")
);
FormData fdRetrieveStep = new FormData();
fdRetrieveStep.left = new FormAttachment(0, 0);
fdRetrieveStep.top = new FormAttachment(wInjectStep, margin);
fdRetrieveStep.right = new FormAttachment(wGetRetrieveStep, -margin);
wRetrieveStep.setLayoutData(fdRetrieveStep);
// Here come the batch size, inject and retrieve fields...
//
wBatchSize = new LabelTextVar(transMeta, shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.BatchSize.Label"),
BaseMessages.getString(PKG, "SingleThreaderDialog.BatchSize.Tooltip")
);
FormData fdBatchSize = new FormData();
fdBatchSize.left = new FormAttachment(0, 0);
fdBatchSize.top = new FormAttachment(wRetrieveStep, margin);
fdBatchSize.right = new FormAttachment(wGetRetrieveStep, -margin);
wBatchSize.setLayoutData(fdBatchSize);
wBatchTime = new LabelTextVar(transMeta, shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.BatchTime.Label"),
BaseMessages.getString(PKG, "SingleThreaderDialog.BatchTime.Tooltip")
);
FormData fdBatchTime = new FormData();
fdBatchTime.left = new FormAttachment(0, 0);
fdBatchTime.top = new FormAttachment(wBatchSize, margin);
fdBatchTime.right = new FormAttachment(wGetRetrieveStep, -margin);
wBatchTime.setLayoutData(fdBatchTime);
gParametersGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
gParametersGroup.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.ParamGroup.Label")); //$NON-NLS-1$;
gParametersGroup.setBackground(shell.getBackground()); // the default looks ugly
FormLayout paramGroupLayout = new FormLayout();
paramGroupLayout.marginLeft = margin * 2;
paramGroupLayout.marginTop = margin * 2;
paramGroupLayout.marginRight = margin * 2;
paramGroupLayout.marginBottom = margin * 2;
gParametersGroup.setLayout(paramGroupLayout);
// Pass all parameters down
//
Label wlPassParams = new Label(gParametersGroup, SWT.RIGHT);
wlPassParams.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.PassAllParameters.Label"));
props.setLook(wlPassParams);
FormData fdlPassParams = new FormData();
fdlPassParams.left = new FormAttachment(0, 0);
fdlPassParams.top = new FormAttachment(0, 0);
fdlPassParams.right = new FormAttachment(middle, -margin);
wlPassParams.setLayoutData(fdlPassParams);
wPassParams = new Button(gParametersGroup, SWT.CHECK);
props.setLook(wPassParams);
FormData fdPassParams = new FormData();
fdPassParams.left = new FormAttachment(middle, 0);
fdPassParams.top = new FormAttachment(0, 0);
fdPassParams.right = new FormAttachment(100, 0);
wPassParams.setLayoutData(fdPassParams);
wbGetParams = new Button(gParametersGroup, SWT.PUSH);
wbGetParams.setText(BaseMessages.getString(PKG, "SingleThreaderDialog.GetParameters.Button.Label"));
FormData fdGetParams = new FormData();
fdGetParams.top = new FormAttachment(wPassParams, margin);
fdGetParams.right = new FormAttachment(100, 0);
wbGetParams.setLayoutData(fdGetParams);
wbGetParams.addSelectionListener(new SelectionAdapter(){ @Override
public void widgetSelected(SelectionEvent arg0) {
getParameters();
} });
final int parameterRows = singleThreaderMeta.getParameters()!=null ? singleThreaderMeta.getParameters().length : 0;
ColumnInfo[] colinf = new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "SingleThreaderDialog.Parameters.Parameter.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "SingleThreaderDialog.Parameters.Value.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false),
};
colinf[1].setUsingVariables(true);
wParameters = new TableView(transMeta, gParametersGroup, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, parameterRows, lsMod, props);
FormData fdParameters = new FormData();
fdParameters.left = new FormAttachment(0, 0);
fdParameters.top = new FormAttachment(wPassParams, margin);
fdParameters.right = new FormAttachment(wbGetParams, -margin);
fdParameters.bottom = new FormAttachment(100, 0);
wParameters.setLayoutData(fdParameters);
FormData fdParametersComp = new FormData();
fdParametersComp.left = new FormAttachment(0, 0);
fdParametersComp.top = new FormAttachment(wBatchTime, 0);
fdParametersComp.right = new FormAttachment(100, 0);
fdParametersComp.bottom = new FormAttachment(100, -50);
gParametersGroup.setLayoutData(fdParametersComp);
// Some buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wCancel }, margin, gParametersGroup);
// Add listeners
lsCancel = new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
};
lsOK = new Listener()
{
public void handleEvent(Event e)
{
ok();
}
};
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener(SWT.Selection, lsOK);
lsDef = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wStepname.addSelectionListener(lsDef);
wFilename.addSelectionListener(lsDef);
wTransname.addSelectionListener(lsDef);
wBatchSize.addSelectionListener(lsDef);
wBatchTime.addSelectionListener(lsDef);
wInjectStep.addSelectionListener(lsDef);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
// Set the shell size, based upon previous time...
setSize();
getData();
singleThreaderMeta.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
return stepname;
}
protected void selectTransformationByReference() {
if (repository != null) {
SelectObjectDialog sod = new SelectObjectDialog(shell, repository, true, false);
sod.open();
RepositoryElementMetaInterface repositoryObject = sod.getRepositoryObject();
if (repositoryObject != null) {
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE;
getByReferenceData(repositoryObject);
referenceObjectId = repositoryObject.getObjectId();
setRadioButtons();
}
}
}
private void selectRepositoryTrans()
{
try
{
SelectObjectDialog sod = new SelectObjectDialog(shell, repository);
String transName = sod.open();
RepositoryDirectoryInterface repdir = sod.getDirectory();
if (transName != null && repdir != null)
{
loadRepositoryTrans(transName, repdir);
wTransname.setText(mappingTransMeta.getName());
wDirectory.setText(mappingTransMeta.getRepositoryDirectory().getPath());
wFilename.setText("");
radioByName.setSelection(true);
radioFilename.setSelection(false);
specificationMethod=ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME;
setRadioButtons();
}
} catch (KettleException ke)
{
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorSelectingObject.DialogTitle"), BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorSelectingObject.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadRepositoryTrans(String transName, RepositoryDirectoryInterface repdir) throws KettleException
{
// Read the transformation...
//
mappingTransMeta = repository.loadTransformation(transMeta.environmentSubstitute(transName), repdir, null, true, null); // reads last version
mappingTransMeta.clearChanged();
}
private void selectFileTrans() {
String curFile = wFilename.getText();
FileObject root = null;
try {
root = KettleVFS.getFileObject(curFile != null ? curFile : Const.getUserHomeDirectory());
VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog(root.getParent(), root);
FileObject file = vfsFileChooser.open(shell, null, Const.STRING_TRANS_FILTER_EXT, Const.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
if (file == null) {
return;
}
String fname = null;
fname = file.getURL().getFile();
if (fname != null) {
loadFileTrans(fname);
wFilename.setText(mappingTransMeta.getFilename());
wTransname.setText(Const.NVL(mappingTransMeta.getName(), ""));
wDirectory.setText("");
specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
setRadioButtons();
}
} catch (IOException e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogTitle"),
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
} catch (KettleException e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogTitle"),
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadFileTrans(String fname) throws KettleException
{
mappingTransMeta = new TransMeta(transMeta.environmentSubstitute(fname));
mappingTransMeta.clearChanged();
}
private void editTrans()
{
// Load the transformation again to make sure it's still there and
// refreshed
// It's an extra check to make sure it's still OK...
//
try
{
loadTransformation();
// If we're still here, mappingTransMeta is valid.
//
SpoonInterface spoon = SpoonFactory.getInstance();
if (spoon != null) {
spoon.addTransGraph(mappingTransMeta);
}
} catch (KettleException e)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorShowingTransformation.Title"),
BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorShowingTransformation.Message"), e);
}
}
private void loadTransformation() throws KettleException
{
switch(specificationMethod) {
case FILENAME:
loadFileTrans(wFilename.getText());
break;
case REPOSITORY_BY_NAME:
String realDirectory = transMeta.environmentSubstitute(wDirectory.getText());
String realTransname = transMeta.environmentSubstitute(wTransname.getText());
if (Const.isEmpty(realDirectory) || Const.isEmpty(realTransname)) {
throw new KettleException(BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.NoValidMappingDetailsFound"));
}
RepositoryDirectoryInterface repdir = repository.findDirectory(realDirectory);
if (repdir == null)
{
throw new KettleException(BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.UnableToFindRepositoryDirectory)"));
}
loadRepositoryTrans(realTransname, repdir);
break;
case REPOSITORY_BY_REFERENCE:
mappingTransMeta = repository.loadTransformation(referenceObjectId, null); // load the last version
mappingTransMeta.clearChanged();
break;
}
wInjectStep.setText(getInjectorStep(mappingTransMeta));
}
public void setActive() {
radioByName.setEnabled(repository != null);
radioByReference.setEnabled(repository != null);
wFilename.setEnabled(radioFilename.getSelection());
wbbFilename.setEnabled(radioFilename.getSelection());
wTransname.setEnabled(repository != null && radioByName.getSelection());
wDirectory.setEnabled(repository != null && radioByName.getSelection());
wbTrans.setEnabled(repository != null && radioByName.getSelection());
wByReference.setEnabled(repository != null && radioByReference.getSelection());
wbByReference.setEnabled(repository != null && radioByReference.getSelection());
}
protected void setRadioButtons() {
radioFilename.setSelection(specificationMethod==ObjectLocationSpecificationMethod.FILENAME);
radioByName.setSelection(specificationMethod==ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME);
radioByReference.setSelection(specificationMethod==ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE);
setActive();
}
private void getByReferenceData(RepositoryElementMetaInterface transInf) {
String path = transInf.getRepositoryDirectory().getPath();
if (!path.endsWith("/"))
path += "/";
path += transInf.getName();
wByReference.setText(path);
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wStepname.selectAll();
specificationMethod=singleThreaderMeta.getSpecificationMethod();
switch(specificationMethod) {
case FILENAME:
wFilename.setText(Const.NVL(singleThreaderMeta.getFileName(), ""));
break;
case REPOSITORY_BY_NAME:
wDirectory.setText(Const.NVL(singleThreaderMeta.getDirectoryPath(), ""));
wTransname.setText(Const.NVL(singleThreaderMeta.getTransName(), ""));
break;
case REPOSITORY_BY_REFERENCE:
referenceObjectId = singleThreaderMeta.getTransObjectId();
wByReference.setText("");
try {
if (repository==null) {
throw new KettleException(BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.NotConnectedToRepository.Message"));
}
RepositoryObject transInf = repository.getObjectInformation(singleThreaderMeta.getTransObjectId(), RepositoryObjectType.TRANSFORMATION);
if (transInf != null) {
getByReferenceData(transInf);
}
} catch (KettleException e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.UnableToReferenceObjectId.Title"),
BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.UnableToReferenceObjectId.Message"), e);
}
break;
}
setRadioButtons();
wBatchSize.setText(Const.NVL(singleThreaderMeta.getBatchSize(), ""));
wBatchTime.setText(Const.NVL(singleThreaderMeta.getBatchTime(), ""));
wInjectStep.setText(Const.NVL(singleThreaderMeta.getInjectStep(), ""));
wRetrieveStep.setText(Const.NVL(singleThreaderMeta.getRetrieveStep(), ""));
// Parameters
//
if (singleThreaderMeta.getParameters() != null) {
for (int i = 0; i < singleThreaderMeta.getParameters().length; i++) {
TableItem ti = wParameters.table.getItem(i);
if (!Const.isEmpty(singleThreaderMeta.getParameters()[i])) {
ti.setText(1, Const.NVL(singleThreaderMeta.getParameters()[i], ""));
ti.setText(2, Const.NVL(singleThreaderMeta.getParameterValues()[i], ""));
}
}
wParameters.removeEmptyRows();
wParameters.setRowNums();
wParameters.optWidth(true);
}
wPassParams.setSelection(singleThreaderMeta.isPassingAllParameters());
try {
loadTransformation();
} catch (Throwable t) {
// Skip the error, it becomes annoying otherwise
}
}
public static String getInjectorStep(TransMeta mappingTransMeta) {
for (StepMeta stepMeta : mappingTransMeta.getSteps()) {
if (stepMeta.getStepID().equals("Injector") || stepMeta.getStepID().equals("MappingInput")) {
return stepMeta.getName();
}
}
return "";
}
private void cancel()
{
stepname = null;
singleThreaderMeta.setChanged(changed);
dispose();
}
private void getInfo(SingleThreaderMeta meta) throws KettleException {
loadTransformation();
meta.setSpecificationMethod(specificationMethod);
switch(specificationMethod) {
case FILENAME:
meta.setFileName(wFilename.getText());
meta.setDirectoryPath(null);
meta.setTransName(null);
meta.setTransObjectId(null);
break;
case REPOSITORY_BY_NAME:
meta.setDirectoryPath(wDirectory.getText());
meta.setTransName(wTransname.getText());
meta.setFileName(null);
meta.setTransObjectId(null);
break;
case REPOSITORY_BY_REFERENCE:
meta.setFileName(null);
meta.setDirectoryPath(null);
meta.setTransName(null);
meta.setTransObjectId(referenceObjectId);
break;
}
meta.setBatchSize(wBatchSize.getText());
meta.setBatchTime(wBatchTime.getText());
meta.setInjectStep(wInjectStep.getText());
meta.setRetrieveStep(wRetrieveStep.getText());
// The parameters...
//
int nritems = wParameters.nrNonEmpty();
int nr = 0;
for (int i = 0; i < nritems; i++) {
String param = wParameters.getNonEmpty(i).getText(1);
if (!Const.isEmpty(param)) {
nr++;
}
}
meta.setParameters(new String[nr]);
meta.setParameterValues(new String[nr]);
nr = 0;
for (int i = 0; i < nritems; i++) {
String param = wParameters.getNonEmpty(i).getText(1);
String value = wParameters.getNonEmpty(i).getText(2);
meta.getParameters()[nr] = param;
meta.getParameterValues()[nr] = Const.NVL(value, "");
nr++;
}
meta.setPassingAllParameters(wPassParams.getSelection());
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
try
{
getInfo(singleThreaderMeta);
loadTransformation();
} catch (KettleException e)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingSpecifiedTransformation.Title"), BaseMessages.getString(PKG, "SingleThreaderDialog.ErrorLoadingSpecifiedTransformation.Message"), e);
}
dispose();
}
protected void getParameters() {
try {
SingleThreaderMeta jet = new SingleThreaderMeta();
getInfo(jet);
TransMeta mappingTransMeta = SingleThreaderMeta.loadSingleThreadedTransMeta(jet, repository, transMeta);
String[] parameters = mappingTransMeta.listParameters();
String[] existing = wParameters.getItems(1);
for (int i=0;i<parameters.length;i++) {
if (Const.indexOfString(parameters[i], existing)<0) {
TableItem item = new TableItem(wParameters.table, SWT.NONE);
item.setText(1, parameters[i]);
}
}
wParameters.removeEmptyRows();
wParameters.setRowNums();
wParameters.optWidth(true);
} catch(Exception e) {
new ErrorDialog(shell,
BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.UnableToLoadTransformation.Title"),
BaseMessages.getString(PKG, "SingleThreaderDialog.Exception.UnableToLoadTransformation.Message"), e);
}
}
}
| |
/*
* This software and all files contained in it are distrubted under the MIT license.
*
* Copyright (c) 2013 Cogito Learning Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @mainpage CogPar is lightweight but versatile parser for mathematical
* expressions.
*
* It can be used to analyse expressions and store them in an internal data
* structure for later evaluation. Repeated evaluation of the same expression
* using CogPar is fast.
*
* CogPar comes with a highly configurable tokenizer which can be adapted for
* your own needs.
*
* Arbitrary named variables are supported and values can be assigned in a
* single line of code.
*
* The parser, it's grammar an the tokenizer are well documented. You can read
* more about the internal workings of CogPar
* <a href="http://cogitolearning.co.uk/?p=523" alt="CogPar tutorial">in these
* posts</a>.
*
* CogPar is distributed under the MIT license, so feel free to use it in your
* own projects.
*
* To download CogPar, <a href="" alt="Download CogPar">follow this link.</a>
*/
package uk.co.cogitolearning.cogpar;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
/**
* A parser for mathematical expressions. The parser class defines a method
* parse() which takes a string and returns an ExpressionNode that holds a
* representation of the expression.
*
* Parsing is implemented in the form of a recursive descent parser.
*
*/
public class Parser {
/**
* the tokens to parse
*/
LinkedList<Token> tokens;
/**
* the next token
*/
Token lookahead;
/**
* Parse a mathematical expression in a string and return an ExpressionNode.
*
* This is a convenience method that first converts the string into a linked
* list of tokens using the expression tokenizer provided by the Tokenizer
* class.
*
* @param expression the string holding the input
* @return the internal representation of the expression in form of an
* expression tree made out of ExpressionNode objects
*/
public ExpressionNode parse(String expression) {
Tokenizer tokenizer = Tokenizer.getExpressionTokenizer();
tokenizer.tokenize(expression);
LinkedList<Token> tokens = tokenizer.getTokens();
return this.parse(tokens);
}
/**
* Parse a mathematical expression in contained in a list of tokens and
* return an ExpressionNode.
*
* @param tokens a list of tokens holding the tokenized input
* @return the internal representation of the expression in form of an
* expression tree made out of ExpressionNode objects
*/
public ExpressionNode parse(LinkedList<Token> tokens) {
// implementing a recursive descent parser
this.tokens = (LinkedList<Token>)tokens.clone();
try {
lookahead = this.tokens.getFirst();
}
catch(NoSuchElementException ex) {
throw new ParserException("No input found.");
}
// top level non-terminal is expression
ExpressionNode expr = expression();
if(lookahead.token != Token.EPSILON) {
throw new ParserException("Unexpected symbol %s found.", lookahead);
}
return expr;
}
/**
* handles the non-terminal expression
*/
private ExpressionNode expression() {
// only one rule
// expression -> signed_term sum_op
ExpressionNode expr = signedTerm();
expr = sumOp(expr);
return expr;
}
/**
* handles the non-terminal sum_op
*/
private ExpressionNode sumOp(ExpressionNode expr) {
// sum_op -> PLUSMINUS signed_term sum_op
if(lookahead.token == Token.PLUSMINUS) {
AdditionExpressionNode sum;
// This means we are actually dealing with a sum
// If expr is not already a sum, we have to create one
if(expr.getType() == ExpressionNode.ADDITION_NODE) {
sum = (AdditionExpressionNode)expr;
}
else {
sum = new AdditionExpressionNode(expr, AdditionExpressionNode.ADD);
}
// reduce the input and recursively call sum_op
int mode = lookahead.sequence.equals("+") ? AdditionExpressionNode.ADD : AdditionExpressionNode.SUB;
nextToken();
ExpressionNode t = signedTerm();
sum.add(t, mode);
return sumOp(sum);
}
// sum_op -> EPSILON
return expr;
}
/**
* handles the non-terminal signed_term
*/
private ExpressionNode signedTerm() {
// signed_term -> PLUSMINUS signed_term
if(lookahead.token == Token.PLUSMINUS) {
int mode = lookahead.sequence.equals("+") ? AdditionExpressionNode.ADD : AdditionExpressionNode.SUB;
nextToken();
ExpressionNode t = signedTerm();
if(mode == AdditionExpressionNode.ADD) {
return t;
}
else {
return new AdditionExpressionNode(t, AdditionExpressionNode.SUB);
}
}
// signed_term -> term
return term();
}
/**
* handles the non-terminal term
*/
private ExpressionNode term() {
// term -> factor term_op
ExpressionNode f = factor();
return termOp(f);
}
/**
* handles the non-terminal term_op
*/
private ExpressionNode termOp(ExpressionNode expression) {
// term_op -> MULTDIV signed_factor term_op
if(lookahead.token == Token.MULTDIVREM) {
MultiplicationExpressionNode prod;
// This means we are actually dealing with a product
// If expr is not already a product, we have to create one
if(expression.getType() == ExpressionNode.MULTIPLICATION_NODE) {
prod = (MultiplicationExpressionNode)expression;
}
else {
prod = new MultiplicationExpressionNode(expression, MultiplicationExpressionNode.MULT);
}
// reduce the input and recursively call sum_op
int mode;
if(lookahead.sequence.equals("*")) {
mode = MultiplicationExpressionNode.MULT;
}
else if(lookahead.sequence.equals("/")) {
mode = MultiplicationExpressionNode.DIV;
}
else {
mode = MultiplicationExpressionNode.REM;
}
nextToken();
ExpressionNode f = signedFactor();
prod.add(f, mode);
return termOp(prod);
}
// term_op -> EPSILON
return expression;
}
/**
* handles the non-terminal signed_factor
*/
private ExpressionNode signedFactor() {
// signed_factor -> PLUSMINUS signed_factor
if(lookahead.token == Token.PLUSMINUS) {
int mode = lookahead.sequence.equals("+") ? AdditionExpressionNode.ADD : AdditionExpressionNode.SUB;
nextToken();
ExpressionNode t = signedFactor();
if(mode == AdditionExpressionNode.ADD) {
return t;
}
else {
return new AdditionExpressionNode(t, AdditionExpressionNode.SUB);
}
}
// signed_factor -> factor
return factor();
}
/**
* handles the non-terminal factor
*/
private ExpressionNode factor() {
// factor -> argument factor_op
ExpressionNode a = argument();
return factorOp(a);
}
/**
* handles the non-terminal factor_op
*/
private ExpressionNode factorOp(ExpressionNode expr) {
// factor_op -> RAISED signed_factor
if(lookahead.token == Token.RAISED) {
nextToken();
ExpressionNode exponent = signedFactor();
return new ExponentiationExpressionNode(expr, exponent);
}
// factor_op -> EPSILON
return expr;
}
/**
* handles the non-terminal argument
*/
private ExpressionNode argument() {
// argument -> FUNCTION function_argument
if(lookahead.token == Token.FUNCTION) {
int function = FunctionExpressionNode.stringToFunction(lookahead.sequence);
nextToken();
ExpressionNode expr = functionArgument();
return new FunctionExpressionNode(function, expr);
}
// argument -> FUNCTION_2ARG function_argument2
else if(lookahead.token == Token.FUNCTION_2ARGUMENTS) {
int function = Function2ArgumentsExpressionNode.stringToFunction(lookahead.sequence);
nextToken();
ExpressionNode expr[] = functionArgument2();
return new Function2ArgumentsExpressionNode(function, expr[0], expr[1]);
}
// argument -> FUNCTION_DERIVATIVE_2_ARG function_argument2
else if(lookahead.token == Token.FUNCTION_DERIVATIVE_2ARGUMENTS) {
int function = FunctionDerivative2ArgumentsExpressionNode.stringToFunction(lookahead.sequence);
nextToken();
ExpressionNode expr[] = functionArgument2();
if(!(expr[1] instanceof VariableExpressionNode)) {
throw new ParserException("The second argument of a derivative function must be a variable.", lookahead);
}
return new FunctionDerivative2ArgumentsExpressionNode(function, expr[0], expr[1]);
}
// argument -> OPEN_BRACKET expression CLOSE_BRACKET
else if(lookahead.token == Token.OPEN_BRACKET) {
nextToken();
ExpressionNode expr = expression();
if(lookahead.token != Token.CLOSE_BRACKET) {
throw new ParserException("Closing brackets expected.", lookahead);
}
nextToken();
return expr;
}
// argument -> value
return value();
}
/*handles the function with 2 arguments */
private ExpressionNode[] functionArgument2() {
// function_argument2 -> OPEN_BRACKET expression COMMA expression CLOSE_BRACKET
if(lookahead.token == Token.OPEN_BRACKET) {
ExpressionNode[] exprs = new ExpressionNode[2];
nextToken();
exprs[0] = expression();
if(lookahead.token != Token.COMMA) {
throw new ParserException("Comma expected.", lookahead);
}
nextToken();
exprs[1] = expression();
if(lookahead.token != Token.CLOSE_BRACKET) {
throw new ParserException("Closing brackets expected.", lookahead);
}
nextToken();
return exprs;
}
throw new ParserException("Opening brackets expected.", lookahead);
}
/*handles the function with 1 argument */
private ExpressionNode functionArgument() {
// function_argument -> OPEN_BRACKET expression CLOSE_BRACKET
if(lookahead.token == Token.OPEN_BRACKET) {
nextToken();
ExpressionNode expr = expression();
if(lookahead.token != Token.CLOSE_BRACKET) {
throw new ParserException("Closing brackets expected.", lookahead);
}
nextToken();
return expr;
}
throw new ParserException("Opening brackets expected.", lookahead);
}
/**
* handles the non-terminal value
*/
private ExpressionNode value() {
// value -> REAL_NUMBER
if(lookahead.token == Token.REAL_NUMBER) {
ExpressionNode expr = new RealConstantExpressionNode(lookahead.sequence);
nextToken();
return expr;
}
// value -> IMAGINARY_NUMBER
if(lookahead.token == Token.IMAGINARY_NUMBER) {
StringTokenizer tok = new StringTokenizer(lookahead.sequence, "iI");
ExpressionNode expr;
if(tok.hasMoreTokens()) {
expr = new ImaginaryConstantExpressionNode(tok.nextToken());
}
else {
expr = new ImaginaryConstantExpressionNode(1.0);
}
nextToken();
return expr;
}
// value -> VARIABLE
if(lookahead.token == Token.VARIABLE) {
if(lookahead.sequence.equalsIgnoreCase("pi") || lookahead.sequence.equalsIgnoreCase("e") || lookahead.sequence.equalsIgnoreCase("phi")) {
RealConstantExpressionNode expr = null;
if(lookahead.sequence.equalsIgnoreCase("pi")) {
expr = new RealConstantExpressionNode(Math.PI);
}
if(lookahead.sequence.equalsIgnoreCase("e")) {
expr = new RealConstantExpressionNode(Math.E);
}
if(lookahead.sequence.equalsIgnoreCase("phi")) {
expr = new RealConstantExpressionNode(1.618033988749895);
}
nextToken();
return expr;
}
ExpressionNode expr = new VariableExpressionNode(lookahead.sequence);
nextToken();
return expr;
}
if(lookahead.token == Token.EPSILON) {
throw new ParserException("Unexpected end of input.");
}
else {
throw new ParserException("Unexpected symbol %s found.", lookahead);
}
}
/**
* Remove the first token from the list and store the next token in
* lookahead
*/
private void nextToken() {
tokens.pop();
// at the end of input we return an epsilon token
if(tokens.isEmpty()) {
lookahead = new Token(Token.EPSILON, "", -1);
}
else {
lookahead = tokens.getFirst();
}
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.ex.ProjectRootManagerEx;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ThrowableRunnable;
import gnu.trove.THashMap;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import java.util.*;
public class ModuleRootManagerImpl extends ModuleRootManager implements Disposable {
protected static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.ModuleRootManagerImpl");
private final Module myModule;
private final ProjectRootManagerImpl myProjectRootManager;
private final VirtualFilePointerManager myFilePointerManager;
protected RootModelImpl myRootModel;
private boolean myIsDisposed;
private boolean myLoaded;
private final OrderRootsCache myOrderRootsCache;
private final Map<RootModelImpl, Throwable> myModelCreations = new THashMap<>();
protected volatile long myModificationCount;
public ModuleRootManagerImpl(@NotNull Module module,
@NotNull ProjectRootManagerImpl projectRootManager,
@NotNull VirtualFilePointerManager filePointerManager) {
myModule = module;
myProjectRootManager = projectRootManager;
myFilePointerManager = filePointerManager;
myRootModel = new RootModelImpl(this, projectRootManager, filePointerManager);
myOrderRootsCache = new OrderRootsCache(module);
}
@Override
@NotNull
public Module getModule() {
return myModule;
}
@Override
@NotNull
public ModuleFileIndex getFileIndex() {
return ModuleServiceManager.getService(myModule, ModuleFileIndex.class);
}
@Override
public void dispose() {
myRootModel.dispose();
myIsDisposed = true;
if (Disposer.isDebugMode()) {
List<Map.Entry<RootModelImpl, Throwable>> entries;
synchronized (myModelCreations) {
entries = new ArrayList<>(myModelCreations.entrySet());
}
for (final Map.Entry<RootModelImpl, Throwable> entry : entries) {
LOG.warn("\n" +
"***********************************************************************************************\n" +
"*** R O O T M O D E L N O T D I S P O S E D ***\n" +
"***********************************************************************************************\n" +
"Created at:", entry.getValue());
entry.getKey().dispose();
}
}
}
@Override
@NotNull
public ModifiableRootModel getModifiableModel() {
return getModifiableModel(new RootConfigurationAccessor());
}
@NotNull
public ModifiableRootModel getModifiableModel(@NotNull RootConfigurationAccessor accessor) {
ApplicationManager.getApplication().assertReadAccessAllowed();
final RootModelImpl model = new RootModelImpl(myRootModel, this, true, accessor, myFilePointerManager, myProjectRootManager) {
@Override
public void dispose() {
super.dispose();
if (Disposer.isDebugMode()) {
synchronized (myModelCreations) {
myModelCreations.remove(this);
}
}
}
};
if (Disposer.isDebugMode()) {
synchronized (myModelCreations) {
myModelCreations.put(model, new Throwable());
}
}
return model;
}
void makeRootsChange(@NotNull Runnable runnable) {
ProjectRootManagerEx projectRootManagerEx = (ProjectRootManagerEx)ProjectRootManager.getInstance(myModule.getProject());
// IMPORTANT: should be the first listener!
projectRootManagerEx.makeRootsChange(runnable, false, myModule.isLoaded());
}
public RootModelImpl getRootModel() {
return myRootModel;
}
@NotNull
@Override
public ContentEntry[] getContentEntries() {
return myRootModel.getContentEntries();
}
@Override
@NotNull
public OrderEntry[] getOrderEntries() {
return myRootModel.getOrderEntries();
}
@Override
public Sdk getSdk() {
return myRootModel.getSdk();
}
@Override
public boolean isSdkInherited() {
return myRootModel.isSdkInherited();
}
void commitModel(RootModelImpl rootModel) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
LOG.assertTrue(rootModel.myModuleRootManager == this);
boolean changed = rootModel.isChanged();
final Project project = myModule.getProject();
final ModifiableModuleModel moduleModel = ModuleManager.getInstance(project).getModifiableModel();
ModifiableModelCommitter.multiCommit(Collections.singletonList(rootModel), moduleModel);
if (changed) {
stateChanged();
}
}
static void doCommit(RootModelImpl rootModel) {
ModuleRootManagerImpl rootManager = (ModuleRootManagerImpl)getInstance(rootModel.getModule());
LOG.assertTrue(!rootManager.myIsDisposed);
rootModel.docommit();
rootModel.dispose();
try {
rootManager.stateChanged();
}
catch (Exception e) {
LOG.error(e);
}
}
@Override
@NotNull
public Module[] getDependencies() {
return myRootModel.getModuleDependencies();
}
@NotNull
@Override
public Module[] getDependencies(boolean includeTests) {
return myRootModel.getModuleDependencies(includeTests);
}
@NotNull
@Override
public Module[] getModuleDependencies() {
return myRootModel.getModuleDependencies();
}
@NotNull
@Override
public Module[] getModuleDependencies(boolean includeTests) {
return myRootModel.getModuleDependencies(includeTests);
}
@Override
public boolean isDependsOn(Module module) {
return myRootModel.findModuleOrderEntry(module) != null;
}
@Override
@NotNull
public String[] getDependencyModuleNames() {
return myRootModel.getDependencyModuleNames();
}
@Override
public <T> T getModuleExtension(@NotNull final Class<T> klass) {
return myRootModel.getModuleExtension(klass);
}
@Override
public <R> R processOrder(RootPolicy<R> policy, R initialValue) {
LOG.assertTrue(!myIsDisposed);
return myRootModel.processOrder(policy, initialValue);
}
@NotNull
@Override
public OrderEnumerator orderEntries() {
return new ModuleOrderEnumerator(myRootModel, myOrderRootsCache);
}
public static OrderRootsEnumerator getCachingEnumeratorForType(@NotNull OrderRootType type, @NotNull Module module) {
return getEnumeratorForType(type, module).usingCache();
}
@NotNull
private static OrderRootsEnumerator getEnumeratorForType(@NotNull OrderRootType type, @NotNull Module module) {
OrderEnumerator base = OrderEnumerator.orderEntries(module);
if (type == OrderRootType.CLASSES) {
return base.exportedOnly().withoutModuleSourceEntries().recursively().classes();
}
if (type == OrderRootType.SOURCES) {
return base.exportedOnly().recursively().sources();
}
return base.roots(type);
}
@Override
@NotNull
public VirtualFile[] getContentRoots() {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getContentRoots();
}
@Override
@NotNull
public String[] getContentRootUrls() {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getContentRootUrls();
}
@Override
@NotNull
public String[] getExcludeRootUrls() {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getExcludeRootUrls();
}
@Override
@NotNull
public VirtualFile[] getExcludeRoots() {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getExcludeRoots();
}
@Override
@NotNull
public String[] getSourceRootUrls() {
return getSourceRootUrls(true);
}
@NotNull
@Override
public String[] getSourceRootUrls(boolean includingTests) {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getSourceRootUrls(includingTests);
}
@Override
@NotNull
public VirtualFile[] getSourceRoots() {
return getSourceRoots(true);
}
@Override
@NotNull
public VirtualFile[] getSourceRoots(final boolean includingTests) {
LOG.assertTrue(!myIsDisposed);
return myRootModel.getSourceRoots(includingTests);
}
@NotNull
@Override
public List<VirtualFile> getSourceRoots(@NotNull JpsModuleSourceRootType<?> rootType) {
return myRootModel.getSourceRoots(rootType);
}
@NotNull
@Override
public List<VirtualFile> getSourceRoots(@NotNull Set<? extends JpsModuleSourceRootType<?>> rootTypes) {
return myRootModel.getSourceRoots(rootTypes);
}
public void dropCaches() {
myOrderRootsCache.clearCache();
}
public ModuleRootManagerState getState() {
if (Registry.is("store.track.module.root.manager.changes", false)) {
LOG.error("getState, module " + myModule.getName());
}
return new ModuleRootManagerState(myRootModel);
}
public void loadState(ModuleRootManagerState object) {
loadState(object, myLoaded || myModule.isLoaded());
myLoaded = true;
}
protected void loadState(ModuleRootManagerState object, boolean throwEvent) {
ThrowableRunnable<RuntimeException> r = () -> {
final RootModelImpl newModel = new RootModelImpl(object.getRootModelElement(), this, myProjectRootManager, myFilePointerManager, throwEvent);
if (throwEvent) {
makeRootsChange(() -> doCommit(newModel));
}
else {
myRootModel.dispose();
myRootModel = newModel;
}
assert !myRootModel.isOrderEntryDisposed();
};
try {
if (throwEvent) WriteAction.run(r);
else ReadAction.run(r);
}
catch (InvalidDataException e) {
LOG.error(e);
}
}
public void stateChanged() {
if (Registry.is("store.track.module.root.manager.changes", false)) {
LOG.error("ModelRootManager state changed");
}
myModificationCount++;
}
@Override
@Nullable
public ProjectModelExternalSource getExternalSource() {
return ExternalProjectSystemRegistry.getInstance().getExternalSource(myModule);
}
public static class ModuleRootManagerState implements JDOMExternalizable {
private RootModelImpl myRootModel;
private Element myRootModelElement;
public ModuleRootManagerState() {
}
public ModuleRootManagerState(RootModelImpl rootModel) {
myRootModel = rootModel;
}
@Override
public void readExternal(Element element) {
myRootModelElement = element;
}
@Override
public void writeExternal(Element element) {
myRootModel.writeExternal(element);
}
public Element getRootModelElement() {
return myRootModelElement;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysml.api.monitoring;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.sysml.lops.Lop;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.instructions.Instruction;
import org.apache.sysml.runtime.instructions.spark.SPInstruction;
import org.apache.sysml.runtime.instructions.spark.functions.SparkListener;
import scala.collection.Seq;
import scala.xml.Node;
/**
* Usage guide:
* MLContext mlCtx = new MLContext(sc, true);
* mlCtx.register...
* mlCtx.execute(...)
* mlCtx.getMonitoringUtil().getRuntimeInfoInHTML("runtime.html");
*/
public class SparkMonitoringUtil {
private HashMap<String, String> lineageInfo = new HashMap<String, String>(); // instruction -> lineageInfo
private HashMap<String, Long> instructionCreationTime = new HashMap<String, Long>();
private MultiMap<Location, String> instructions = new MultiMap<Location, String>();
private MultiMap<String, Integer> stageIDs = new MultiMap<String, Integer>();
private MultiMap<String, Integer> jobIDs = new MultiMap<String, Integer>();
private MultiMap<Integer, String> rddInstructionMapping = new MultiMap<Integer, String>();
private HashSet<String> getRelatedInstructions(int stageID) {
HashSet<String> retVal = new HashSet<String>();
if(_sparkListener != null) {
ArrayList<Integer> rdds = _sparkListener.stageRDDMapping.get(stageID);
for(Integer rddID : rdds) {
retVal.addAll(rddInstructionMapping.get(rddID));
}
}
return retVal;
}
private SparkListener _sparkListener = null;
public SparkListener getSparkListener() {
return _sparkListener;
}
private String explainOutput = "";
public String getExplainOutput() {
return explainOutput;
}
public void setExplainOutput(String explainOutput) {
this.explainOutput = explainOutput;
}
public SparkMonitoringUtil(SparkListener sparkListener) {
_sparkListener = sparkListener;
}
public void addCurrentInstruction(SPInstruction inst) {
if(_sparkListener != null) {
_sparkListener.addCurrentInstruction(inst);
}
}
public void addRDDForInstruction(SPInstruction inst, Integer rddID) {
this.rddInstructionMapping.put(rddID, getInstructionString(inst));
}
public void removeCurrentInstruction(SPInstruction inst) {
if(_sparkListener != null) {
_sparkListener.removeCurrentInstruction(inst);
}
}
public void setDMLString(String dmlStr) {
this.dmlStrForMonitoring = dmlStr;
}
public void resetMonitoringData() {
if(_sparkListener != null && _sparkListener.stageDAGs != null)
_sparkListener.stageDAGs.clear();
if(_sparkListener != null && _sparkListener.stageTimeline != null)
_sparkListener.stageTimeline.clear();
}
// public Multimap<Location, String> hops = ArrayListMultimap.create(); TODO:
private String dmlStrForMonitoring = null;
public void getRuntimeInfoInHTML(String htmlFilePath) throws DMLRuntimeException, IOException {
String jsAndCSSFiles = "<script src=\"js/lodash.min.js\"></script>"
+ "<script src=\"js/jquery-1.11.1.min.js\"></script>"
+ "<script src=\"js/d3.min.js\"></script>"
+ "<script src=\"js/bootstrap-tooltip.js\"></script>"
+ "<script src=\"js/dagre-d3.min.js\"></script>"
+ "<script src=\"js/graphlib-dot.min.js\"></script>"
+ "<script src=\"js/spark-dag-viz.js\"></script>"
+ "<script src=\"js/timeline-view.js\"></script>"
+ "<script src=\"js/vis.min.js\"></script>"
+ "<link rel=\"stylesheet\" href=\"css/bootstrap.min.css\">"
+ "<link rel=\"stylesheet\" href=\"css/vis.min.css\">"
+ "<link rel=\"stylesheet\" href=\"css/spark-dag-viz.css\">"
+ "<link rel=\"stylesheet\" href=\"css/timeline-view.css\"> ";
BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFilePath));
bw.write("<html><head>\n");
bw.write(jsAndCSSFiles + "\n");
bw.write("</head><body>\n<table border=1>\n");
bw.write("<tr>\n");
bw.write("<td><b>Position in script</b></td>\n");
bw.write("<td><b>DML</b></td>\n");
bw.write("<td><b>Instruction</b></td>\n");
bw.write("<td><b>StageIDs</b></td>\n");
bw.write("<td><b>RDD Lineage</b></td>\n");
bw.write("</tr>\n");
for(Location loc : instructions.keySet()) {
String dml = getExpression(loc);
// Sort the instruction with time - so as to separate recompiled instructions
List<String> listInst = new ArrayList<String>(instructions.get(loc));
Collections.sort(listInst, new InstructionComparator(instructionCreationTime));
if(dml != null && dml.trim().length() > 1) {
bw.write("<tr>\n");
int rowSpan = listInst.size();
bw.write("<td rowspan=\"" + rowSpan + "\">" + loc.toString() + "</td>\n");
bw.write("<td rowspan=\"" + rowSpan + "\">" + dml + "</td>\n");
boolean firstTime = true;
for(String inst : listInst) {
if(!firstTime)
bw.write("<tr>\n");
if(inst.startsWith("SPARK"))
bw.write("<td style=\"color:red\">" + inst + "</td>\n");
else if(isInterestingCP(inst))
bw.write("<td style=\"color:blue\">" + inst + "</td>\n");
else
bw.write("<td>" + inst + "</td>\n");
bw.write("<td>" + getStageIDAsString(inst) + "</td>\n");
if(lineageInfo.containsKey(inst))
bw.write("<td>" + lineageInfo.get(inst).replaceAll("\n", "<br />") + "</td>\n");
else
bw.write("<td></td>\n");
bw.write("</tr>\n");
firstTime = false;
}
}
}
bw.write("</table></body>\n</html>");
bw.close();
}
private String getInQuotes(String str) {
return "\"" + str + "\"";
}
private String getEscapedJSON(String json) {
if(json == null)
return "";
else {
return json
//.replaceAll("\\\\", "\\\\\\")
.replaceAll("\\t", "\\\\t")
.replaceAll("/", "\\\\/")
.replaceAll("\"", "\\\\\"")
.replaceAll("\\r?\\n", "\\\\n");
}
}
private long maxExpressionExecutionTime = 0;
HashMap<Integer, Long> stageExecutionTimes = new HashMap<Integer, Long>();
HashMap<String, Long> expressionExecutionTimes = new HashMap<String, Long>();
HashMap<String, Long> instructionExecutionTimes = new HashMap<String, Long>();
HashMap<Integer, HashSet<String>> relatedInstructionsPerStage = new HashMap<Integer, HashSet<String>>();
private void fillExecutionTimes() {
stageExecutionTimes.clear();
expressionExecutionTimes.clear();
for(Location loc : instructions.keySet()) {
List<String> listInst = new ArrayList<String>(instructions.get(loc));
long expressionExecutionTime = 0;
for(String inst : listInst) {
long instructionExecutionTime = 0;
for(Integer stageId : stageIDs.get(inst)) {
try {
if(getStageExecutionTime(stageId) != null) {
long stageExecTime = getStageExecutionTime(stageId);
instructionExecutionTime += stageExecTime;
expressionExecutionTime += stageExecTime;
stageExecutionTimes.put(stageId, stageExecTime);
}
}
catch(Exception e) {}
relatedInstructionsPerStage.put(stageId, getRelatedInstructions(stageId));
}
instructionExecutionTimes.put(inst, instructionExecutionTime);
}
expressionExecutionTime /= listInst.size(); // average
maxExpressionExecutionTime = Math.max(maxExpressionExecutionTime, expressionExecutionTime);
expressionExecutionTimes.put(loc.toString(), expressionExecutionTime);
}
// Now fill empty instructions
for(Entry<String, Long> kv : instructionExecutionTimes.entrySet()) {
if(kv.getValue() == 0) {
// Find all stages that contain this as related instruction
long sumExecutionTime = 0;
for(Entry<Integer, HashSet<String>> kv1 : relatedInstructionsPerStage.entrySet()) {
if(kv1.getValue().contains(kv.getKey())) {
sumExecutionTime += stageExecutionTimes.get(kv1.getKey());
}
}
kv.setValue(sumExecutionTime);
}
}
for(Location loc : instructions.keySet()) {
if(expressionExecutionTimes.get(loc.toString()) == 0) {
List<String> listInst = new ArrayList<String>(instructions.get(loc));
long expressionExecutionTime = 0;
for(String inst : listInst) {
expressionExecutionTime += instructionExecutionTimes.get(inst);
}
expressionExecutionTime /= listInst.size(); // average
maxExpressionExecutionTime = Math.max(maxExpressionExecutionTime, expressionExecutionTime);
expressionExecutionTimes.put(loc.toString(), expressionExecutionTime);
}
}
}
public String getRuntimeInfoInJSONFormat() throws DMLRuntimeException, IOException {
StringBuilder retVal = new StringBuilder("{\n");
retVal.append(getInQuotes("dml") + ":" + getInQuotes(getEscapedJSON(dmlStrForMonitoring)) + ",\n");
retVal.append(getInQuotes("expressions") + ":" + "[\n");
boolean isFirstExpression = true;
fillExecutionTimes();
for(Location loc : instructions.keySet()) {
String dml = getEscapedJSON(getExpressionInJSON(loc));
if(dml != null) {
// Sort the instruction with time - so as to separate recompiled instructions
List<String> listInst = new ArrayList<String>(instructions.get(loc));
Collections.sort(listInst, new InstructionComparator(instructionCreationTime));
if(!isFirstExpression) {
retVal.append(",\n");
}
retVal.append("{\n");
isFirstExpression = false;
retVal.append(getInQuotes("beginLine") + ":" + loc.beginLine + ",\n");
retVal.append(getInQuotes("beginCol") + ":" + loc.beginCol + ",\n");
retVal.append(getInQuotes("endLine") + ":" + loc.endLine + ",\n");
retVal.append(getInQuotes("endCol") + ":" + loc.endCol + ",\n");
long expressionExecutionTime = expressionExecutionTimes.get(loc.toString());
retVal.append(getInQuotes("expressionExecutionTime") + ":" + expressionExecutionTime + ",\n");
retVal.append(getInQuotes("expressionHeavyHitterFactor") + ":" + ((double)expressionExecutionTime / (double)maxExpressionExecutionTime) + ",\n");
retVal.append(getInQuotes("expression") + ":" + getInQuotes(dml) + ",\n");
retVal.append(getInQuotes("instructions") + ":" + "[\n");
boolean firstTime = true;
for(String inst : listInst) {
if(!firstTime)
retVal.append(", {");
else
retVal.append("{");
if(inst.startsWith("SPARK")) {
retVal.append(getInQuotes("isSpark") + ":" + "true,\n");
}
else if(isInterestingCP(inst)) {
retVal.append(getInQuotes("isInteresting") + ":" + "true,\n");
}
retVal.append(getStageIDAsJSONString(inst) + "\n");
if(lineageInfo.containsKey(inst)) {
retVal.append(getInQuotes("lineageInfo") + ":" + getInQuotes(getEscapedJSON(lineageInfo.get(inst))) + ",\n");
}
retVal.append(getInQuotes("instruction") + ":" + getInQuotes(getEscapedJSON(inst)));
retVal.append("}");
firstTime = false;
}
retVal.append("]\n");
retVal.append("}\n");
}
}
return retVal.append("]\n}").toString();
}
private boolean isInterestingCP(String inst) {
if(inst.startsWith("CP rmvar") || inst.startsWith("CP cpvar") || inst.startsWith("CP mvvar"))
return false;
else if(inst.startsWith("CP"))
return true;
else
return false;
}
private String getStageIDAsString(String instruction) {
String retVal = "";
for(Integer stageId : stageIDs.get(instruction)) {
String stageDAG = "";
String stageTimeLine = "";
if(getStageDAGs(stageId) != null) {
stageDAG = getStageDAGs(stageId).toString();
}
if(getStageTimeLine(stageId) != null) {
stageTimeLine = getStageTimeLine(stageId).toString();
}
retVal += "Stage:" + stageId +
" ("
+ "<div>"
+ stageDAG.replaceAll("toggleDagViz\\(false\\)", "toggleDagViz(false, this)")
+ "</div>, "
+ "<div id=\"timeline-" + stageId + "\">"
+ stageTimeLine
.replaceAll("drawTaskAssignmentTimeline\\(", "registerTimelineData(" + stageId + ", ")
.replaceAll("class=\"expand-task-assignment-timeline\"", "class=\"expand-task-assignment-timeline\" onclick=\"toggleStageTimeline(this)\"")
+ "</div>"
+ ")";
}
return retVal;
}
private String getStageIDAsJSONString(String instruction) {
long instructionExecutionTime = instructionExecutionTimes.get(instruction);
StringBuilder retVal = new StringBuilder(getInQuotes("instructionExecutionTime") + ":" + instructionExecutionTime + ",\n");
boolean isFirst = true;
if(stageIDs.get(instruction).size() == 0) {
// Find back references
HashSet<Integer> relatedStages = new HashSet<Integer>();
for(Entry<Integer, HashSet<String>> kv : relatedInstructionsPerStage.entrySet()) {
if(kv.getValue().contains(instruction)) {
relatedStages.add(kv.getKey());
}
}
HashSet<String> relatedInstructions = new HashSet<String>();
for(Entry<String, Integer> kv : stageIDs.entries()) {
if(relatedStages.contains(kv.getValue())) {
relatedInstructions.add(kv.getKey());
}
}
retVal.append(getInQuotes("backReferences") + ": [\n");
boolean isFirstRelInst = true;
for(String relInst : relatedInstructions) {
if(!isFirstRelInst) {
retVal.append(",\n");
}
retVal.append(getInQuotes(relInst));
isFirstRelInst = false;
}
retVal.append("], \n");
}
else {
retVal.append(getInQuotes("stages") + ": {");
for(Integer stageId : stageIDs.get(instruction)) {
String stageDAG = "";
String stageTimeLine = "";
if(getStageDAGs(stageId) != null) {
stageDAG = getStageDAGs(stageId).toString();
}
if(getStageTimeLine(stageId) != null) {
stageTimeLine = getStageTimeLine(stageId).toString();
}
long stageExecutionTime = stageExecutionTimes.get(stageId);
if(!isFirst) {
retVal.append(",\n");
}
retVal.append(getInQuotes("" + stageId) + ": {");
// Now add related instructions
HashSet<String> relatedInstructions = relatedInstructionsPerStage.get(stageId);
retVal.append(getInQuotes("relatedInstructions") + ": [\n");
boolean isFirstRelInst = true;
for(String relInst : relatedInstructions) {
if(!isFirstRelInst) {
retVal.append(",\n");
}
retVal.append(getInQuotes(relInst));
isFirstRelInst = false;
}
retVal.append("],\n");
retVal.append(getInQuotes("DAG") + ":")
.append(
getInQuotes(
getEscapedJSON(stageDAG.replaceAll("toggleDagViz\\(false\\)", "toggleDagViz(false, this)"))
) + ",\n"
)
.append(getInQuotes("stageExecutionTime") + ":" + stageExecutionTime + ",\n")
.append(getInQuotes("timeline") + ":")
.append(
getInQuotes(
getEscapedJSON(
stageTimeLine
.replaceAll("drawTaskAssignmentTimeline\\(", "registerTimelineData(" + stageId + ", ")
.replaceAll("class=\"expand-task-assignment-timeline\"", "class=\"expand-task-assignment-timeline\" onclick=\"toggleStageTimeline(this)\""))
)
)
.append("}");
isFirst = false;
}
retVal.append("}, ");
}
retVal.append(getInQuotes("jobs") + ": {");
isFirst = true;
for(Integer jobId : jobIDs.get(instruction)) {
String jobDAG = "";
if(getJobDAGs(jobId) != null) {
jobDAG = getJobDAGs(jobId).toString();
}
if(!isFirst) {
retVal.append(",\n");
}
retVal.append(getInQuotes("" + jobId) + ": {")
.append(getInQuotes("DAG") + ":" )
.append(getInQuotes(
getEscapedJSON(jobDAG.replaceAll("toggleDagViz\\(true\\)", "toggleDagViz(true, this)"))
) + "}\n");
isFirst = false;
}
retVal.append("}, ");
return retVal.toString();
}
String [] dmlLines = null;
private String getExpression(Location loc) {
try {
if(dmlLines == null) {
dmlLines = dmlStrForMonitoring.split("\\r?\\n");
}
if(loc.beginLine == loc.endLine) {
return dmlLines[loc.beginLine-1].substring(loc.beginCol-1, loc.endCol);
}
else {
String retVal = dmlLines[loc.beginLine-1].substring(loc.beginCol-1);
for(int i = loc.beginLine+1; i < loc.endLine; i++) {
retVal += "<br />" + dmlLines[i-1];
}
retVal += "<br />" + dmlLines[loc.endLine-1].substring(0, loc.endCol);
return retVal;
}
}
catch(Exception e) {
return null; // "[[" + loc.beginLine + "," + loc.endLine + "," + loc.beginCol + "," + loc.endCol + "]]";
}
}
private String getExpressionInJSON(Location loc) {
try {
if(dmlLines == null) {
dmlLines = dmlStrForMonitoring.split("\\r?\\n");
}
if(loc.beginLine == loc.endLine) {
return dmlLines[loc.beginLine-1].substring(loc.beginCol-1, loc.endCol);
}
else {
String retVal = dmlLines[loc.beginLine-1].substring(loc.beginCol-1);
for(int i = loc.beginLine+1; i < loc.endLine; i++) {
retVal += "\\n" + dmlLines[i-1];
}
retVal += "\\n" + dmlLines[loc.endLine-1].substring(0, loc.endCol);
return retVal;
}
}
catch(Exception e) {
return null; // "[[" + loc.beginLine + "," + loc.endLine + "," + loc.beginCol + "," + loc.endCol + "]]";
}
}
public Seq<Node> getStageDAGs(int stageIDs) {
if(_sparkListener == null || _sparkListener.stageDAGs == null)
return null;
else
return _sparkListener.stageDAGs.get(stageIDs);
}
public Long getStageExecutionTime(int stageID) {
if(_sparkListener == null || _sparkListener.stageDAGs == null)
return null;
else
return _sparkListener.stageExecutionTime.get(stageID);
}
public Seq<Node> getJobDAGs(int jobID) {
if(_sparkListener == null || _sparkListener.jobDAGs == null)
return null;
else
return _sparkListener.jobDAGs.get(jobID);
}
public Seq<Node> getStageTimeLine(int stageIDs) {
if(_sparkListener == null || _sparkListener.stageTimeline == null)
return null;
else
return _sparkListener.stageTimeline.get(stageIDs);
}
public void setLineageInfo(Instruction inst, String plan) {
lineageInfo.put(getInstructionString(inst), plan);
}
public void setStageId(Instruction inst, int stageId) {
stageIDs.put(getInstructionString(inst), stageId);
}
public void setJobId(Instruction inst, int jobId) {
jobIDs.put(getInstructionString(inst), jobId);
}
public void setInstructionLocation(Location loc, Instruction inst) {
String instStr = getInstructionString(inst);
instructions.put(loc, instStr);
instructionCreationTime.put(instStr, System.currentTimeMillis());
}
private String getInstructionString(Instruction inst) {
String tmp = inst.toString();
tmp = tmp.replaceAll(Lop.OPERAND_DELIMITOR, " ");
tmp = tmp.replaceAll(Lop.DATATYPE_PREFIX, ".");
tmp = tmp.replaceAll(Lop.INSTRUCTION_DELIMITOR, ", ");
return tmp;
}
public class MultiMap<K, V extends Comparable<V>> {
private SortedMap<K, List<V>> m = new TreeMap<K, List<V>>();
public MultiMap(){
}
public void put(K key, V value) {
List<V> list;
if (!m.containsKey(key)) {
list = new ArrayList<V>();
m.put(key, list);
} else {
list = m.get(key);
}
list.add(value);
Collections.sort(list);
}
public Collection<Entry<K, V>> entries() {
// the treemap is sorted and the lists are sorted, so can traverse
// to generate a key/value ordered list of all entries.
Collection<Entry<K, V>> allEntries = new ArrayList<Entry<K, V>>();
for (K key : m.keySet()) {
List<V> list = m.get(key);
for (V value : list) {
Entry<K, V> listEntry = new SimpleEntry<K, V>(key, value);
allEntries.add(listEntry);
}
}
return allEntries;
}
public List<V> get(K key) {
return m.get(key);
}
public Set<K> keySet() {
return m.keySet();
}
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lexmodelsv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/models.lex.v2-2020-08-07/UntagResource" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UntagResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
* </p>
*/
private String resourceARN;
/**
* <p>
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.
* </p>
*/
private java.util.List<String> tagKeys;
/**
* <p>
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
* </p>
*
* @param resourceARN
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
*/
public void setResourceARN(String resourceARN) {
this.resourceARN = resourceARN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
* </p>
*
* @return The Amazon Resource Name (ARN) of the resource to remove the tags from.
*/
public String getResourceARN() {
return this.resourceARN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
* </p>
*
* @param resourceARN
* The Amazon Resource Name (ARN) of the resource to remove the tags from.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withResourceARN(String resourceARN) {
setResourceARN(resourceARN);
return this;
}
/**
* <p>
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.
* </p>
*
* @return A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is
* ignored.
*/
public java.util.List<String> getTagKeys() {
return tagKeys;
}
/**
* <p>
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.
* </p>
*
* @param tagKeys
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is
* ignored.
*/
public void setTagKeys(java.util.Collection<String> tagKeys) {
if (tagKeys == null) {
this.tagKeys = null;
return;
}
this.tagKeys = new java.util.ArrayList<String>(tagKeys);
}
/**
* <p>
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTagKeys(java.util.Collection)} or {@link #withTagKeys(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param tagKeys
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is
* ignored.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withTagKeys(String... tagKeys) {
if (this.tagKeys == null) {
setTagKeys(new java.util.ArrayList<String>(tagKeys.length));
}
for (String ele : tagKeys) {
this.tagKeys.add(ele);
}
return this;
}
/**
* <p>
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.
* </p>
*
* @param tagKeys
* A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is
* ignored.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withTagKeys(java.util.Collection<String> tagKeys) {
setTagKeys(tagKeys);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResourceARN() != null)
sb.append("ResourceARN: ").append(getResourceARN()).append(",");
if (getTagKeys() != null)
sb.append("TagKeys: ").append(getTagKeys());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UntagResourceRequest == false)
return false;
UntagResourceRequest other = (UntagResourceRequest) obj;
if (other.getResourceARN() == null ^ this.getResourceARN() == null)
return false;
if (other.getResourceARN() != null && other.getResourceARN().equals(this.getResourceARN()) == false)
return false;
if (other.getTagKeys() == null ^ this.getTagKeys() == null)
return false;
if (other.getTagKeys() != null && other.getTagKeys().equals(this.getTagKeys()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceARN() == null) ? 0 : getResourceARN().hashCode());
hashCode = prime * hashCode + ((getTagKeys() == null) ? 0 : getTagKeys().hashCode());
return hashCode;
}
@Override
public UntagResourceRequest clone() {
return (UntagResourceRequest) super.clone();
}
}
| |
/*
* Copyright 2014 OpenMarket Ltd
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.data;
import android.os.Looper;
import android.text.TextUtils;
import org.matrix.androidsdk.core.Log;
import org.matrix.androidsdk.core.callback.ApiCallback;
import org.matrix.androidsdk.core.callback.SimpleApiCallback;
import org.matrix.androidsdk.core.model.MatrixError;
import org.matrix.androidsdk.data.store.IMXStore;
import org.matrix.androidsdk.data.timeline.EventTimeline;
import org.matrix.androidsdk.rest.client.RoomsRestClient;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.TokensChunkEvents;
import org.matrix.androidsdk.rest.model.filter.RoomEventFilter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Layer for retrieving data either from the storage implementation, or from the server if the information is not available.
*/
public class DataRetriever {
private static final String LOG_TAG = DataRetriever.class.getSimpleName();
private RoomsRestClient mRestClient;
private final Map<String, String> mPendingForwardRequestTokenByRoomId = new HashMap<>();
private final Map<String, String> mPendingBackwardRequestTokenByRoomId = new HashMap<>();
private final Map<String, String> mPendingRemoteRequestTokenByRoomId = new HashMap<>();
public RoomsRestClient getRoomsRestClient() {
return mRestClient;
}
public void setRoomsRestClient(final RoomsRestClient client) {
mRestClient = client;
}
/**
* Provides the cached messages for a dedicated roomId
*
* @param store the store.
* @param roomId the roomId
* @return the events list, null if the room does not exist
*/
public Collection<Event> getCachedRoomMessages(final IMXStore store, final String roomId) {
return store.getRoomMessages(roomId);
}
/**
* Cancel any history requests for a dedicated room
*
* @param roomId the room id.
*/
public void cancelHistoryRequests(final String roomId) {
Log.d(LOG_TAG, "## cancelHistoryRequests() : roomId " + roomId);
clearPendingToken(mPendingForwardRequestTokenByRoomId, roomId);
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
}
/**
* Cancel any request history requests for a dedicated room
*
* @param roomId the room id.
*/
public void cancelRemoteHistoryRequest(final String roomId) {
Log.d(LOG_TAG, "## cancelRemoteHistoryRequest() : roomId " + roomId);
clearPendingToken(mPendingRemoteRequestTokenByRoomId, roomId);
}
/**
* Get the event associated with the eventId and roomId
* Look in the store before hitting the rest client.
*
* @param store the store to look in
* @param roomId the room Id
* @param eventId the eventId
* @param callback the callback
*/
public void getEvent(final IMXStore store, final String roomId, final String eventId, final ApiCallback<Event> callback) {
final Event event = store.getEvent(eventId, roomId);
if (event == null) {
mRestClient.getEvent(roomId, eventId, callback);
} else {
callback.onSuccess(event);
}
}
/**
* Trigger a back pagination for a dedicated room from Token.
*
* @param store the store to use
* @param roomId the room Id
* @param token the start token.
* @param limit the maximum number of messages to retrieve
* @param roomEventFilter the filter to use
* @param callback the callback
*/
public void backPaginate(final IMXStore store,
final String roomId,
final String token,
final int limit,
final RoomEventFilter roomEventFilter,
final ApiCallback<TokensChunkEvents> callback) {
// reach the marker end
if (TextUtils.equals(token, Event.PAGINATE_BACK_TOKEN_END)) {
// nothing more to provide
final android.os.Handler handler = new android.os.Handler(Looper.getMainLooper());
// call the callback with a delay
// to reproduce the same behaviour as a network request.
// except for the initial request.
Runnable r = new Runnable() {
@Override
public void run() {
handler.postDelayed(new Runnable() {
public void run() {
callback.onSuccess(new TokensChunkEvents());
}
}, 0);
}
};
handler.post(r);
return;
}
Log.d(LOG_TAG, "## backPaginate() : starts for roomId " + roomId);
TokensChunkEvents storageResponse = store.getEarlierMessages(roomId, token, limit);
putPendingToken(mPendingBackwardRequestTokenByRoomId, roomId, token);
if (storageResponse != null) {
final android.os.Handler handler = new android.os.Handler(Looper.getMainLooper());
final TokensChunkEvents fStorageResponse = storageResponse;
Log.d(LOG_TAG, "## backPaginate() : some data has been retrieved into the local storage (" + fStorageResponse.chunk.size() + " events)");
// call the callback with a delay
// to reproduce the same behaviour as a network request.
// except for the initial request.
Runnable r = new Runnable() {
@Override
public void run() {
handler.postDelayed(new Runnable() {
public void run() {
String expectedToken = getPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
Log.d(LOG_TAG, "## backPaginate() : local store roomId " + roomId + " token " + token + " vs " + expectedToken);
if (TextUtils.equals(expectedToken, token)) {
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
callback.onSuccess(fStorageResponse);
}
}
}, 0);
}
};
Thread t = new Thread(r);
t.start();
} else {
Log.d(LOG_TAG, "## backPaginate() : trigger a remote request");
mRestClient.getRoomMessagesFrom(roomId, token, EventTimeline.Direction.BACKWARDS, limit, roomEventFilter,
new SimpleApiCallback<TokensChunkEvents>(callback) {
@Override
public void onSuccess(TokensChunkEvents tokensChunkEvents) {
String expectedToken = getPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
Log.d(LOG_TAG, "## backPaginate() succeeds : roomId " + roomId + " token " + token + " vs " + expectedToken);
if (TextUtils.equals(expectedToken, token)) {
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
// Watch for the one event overlap
Event oldestEvent = store.getOldestEvent(roomId);
if (tokensChunkEvents.chunk.size() != 0) {
tokensChunkEvents.chunk.get(0).mToken = tokensChunkEvents.start;
// there is no more data on server side
if (null == tokensChunkEvents.end) {
tokensChunkEvents.end = Event.PAGINATE_BACK_TOKEN_END;
}
tokensChunkEvents.chunk.get(tokensChunkEvents.chunk.size() - 1).mToken = tokensChunkEvents.end;
Event firstReturnedEvent = tokensChunkEvents.chunk.get(0);
if ((oldestEvent != null) && (firstReturnedEvent != null)
&& TextUtils.equals(oldestEvent.eventId, firstReturnedEvent.eventId)) {
tokensChunkEvents.chunk.remove(0);
}
store.storeRoomEvents(roomId, tokensChunkEvents, EventTimeline.Direction.BACKWARDS);
}
Log.d(LOG_TAG, "## backPaginate() succeed : roomId " + roomId
+ " token " + token
+ " got " + tokensChunkEvents.chunk.size());
callback.onSuccess(tokensChunkEvents);
}
}
private void logErrorMessage(String expectedToken, String errorMessage) {
Log.e(LOG_TAG, "## backPaginate() failed : roomId " + roomId
+ " token " + token
+ " expected " + expectedToken
+ " with " + errorMessage);
}
@Override
public void onNetworkError(Exception e) {
String expectedToken = getPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
logErrorMessage(expectedToken, e.getMessage());
// dispatch only if it is expected
if (TextUtils.equals(token, expectedToken)) {
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
String expectedToken = getPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
logErrorMessage(expectedToken, e.getMessage());
// dispatch only if it is expected
if (TextUtils.equals(token, expectedToken)) {
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
String expectedToken = getPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
logErrorMessage(expectedToken, e.getMessage());
// dispatch only if it is expected
if (TextUtils.equals(token, expectedToken)) {
clearPendingToken(mPendingBackwardRequestTokenByRoomId, roomId);
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Trigger a forward pagination for a dedicated room from Token.
*
* @param store the store to use
* @param roomId the room Id
* @param token the start token.
* @param roomEventFilter the filter to use
* @param callback the callback
*/
private void forwardPaginate(final IMXStore store,
final String roomId,
final String token,
final RoomEventFilter roomEventFilter,
final ApiCallback<TokensChunkEvents> callback) {
putPendingToken(mPendingForwardRequestTokenByRoomId, roomId, token);
mRestClient.getRoomMessagesFrom(roomId, token, EventTimeline.Direction.FORWARDS, RoomsRestClient.DEFAULT_MESSAGES_PAGINATION_LIMIT, roomEventFilter,
new SimpleApiCallback<TokensChunkEvents>(callback) {
@Override
public void onSuccess(TokensChunkEvents tokensChunkEvents) {
if (TextUtils.equals(getPendingToken(mPendingForwardRequestTokenByRoomId, roomId), token)) {
clearPendingToken(mPendingForwardRequestTokenByRoomId, roomId);
store.storeRoomEvents(roomId, tokensChunkEvents, EventTimeline.Direction.FORWARDS);
callback.onSuccess(tokensChunkEvents);
}
}
});
}
/**
* Request messages than the given token. These will come from storage if available, from the server otherwise.
*
* @param store the store to use
* @param roomId the room id
* @param token the token to go back from. Null to start from live.
* @param direction the pagination direction
* @param roomEventFilter the filter to use
* @param callback the onComplete callback
*/
public void paginate(final IMXStore store,
final String roomId,
final String token,
final EventTimeline.Direction direction,
final RoomEventFilter roomEventFilter,
final ApiCallback<TokensChunkEvents> callback) {
if (direction == EventTimeline.Direction.BACKWARDS) {
backPaginate(store, roomId, token, RoomsRestClient.DEFAULT_MESSAGES_PAGINATION_LIMIT, roomEventFilter, callback);
} else {
forwardPaginate(store, roomId, token, roomEventFilter, callback);
}
}
/**
* Request events to the server. The local cache is not used.
* The events will not be saved in the local storage.
*
* @param roomId the room id
* @param token the token to go back from.
* @param paginationCount the number of events to retrieve.
* @param roomEventFilter the filter to use for pagination
* @param callback the onComplete callback
*/
public void requestServerRoomHistory(final String roomId,
final String token,
final int paginationCount,
final RoomEventFilter roomEventFilter,
final ApiCallback<TokensChunkEvents> callback) {
putPendingToken(mPendingRemoteRequestTokenByRoomId, roomId, token);
mRestClient.getRoomMessagesFrom(roomId, token, EventTimeline.Direction.BACKWARDS, paginationCount, roomEventFilter,
new SimpleApiCallback<TokensChunkEvents>(callback) {
@Override
public void onSuccess(TokensChunkEvents info) {
if (TextUtils.equals(getPendingToken(mPendingRemoteRequestTokenByRoomId, roomId), token)) {
if (info.chunk.size() != 0) {
info.chunk.get(0).mToken = info.start;
info.chunk.get(info.chunk.size() - 1).mToken = info.end;
}
clearPendingToken(mPendingRemoteRequestTokenByRoomId, roomId);
callback.onSuccess(info);
}
}
});
}
//==============================================================================================================
// Pending token management
//==============================================================================================================
/**
* Clear token for a dedicated room
*
* @param dict the token cache
* @param roomId the room id
*/
private void clearPendingToken(final Map<String, String> dict, final String roomId) {
Log.d(LOG_TAG, "## clearPendingToken() : roomId " + roomId);
if (null != roomId) {
synchronized (dict) {
dict.remove(roomId);
}
}
}
/**
* Get the pending token for a dedicated room
*
* @param dict the token cache
* @param roomId the room Id
* @return the token
*/
private String getPendingToken(final Map<String, String> dict, final String roomId) {
String expectedToken = "Not a valid token";
synchronized (dict) {
// token == null is a valid value
if (dict.containsKey(roomId)) {
expectedToken = dict.get(roomId);
if (TextUtils.isEmpty(expectedToken)) {
expectedToken = null;
}
}
}
Log.d(LOG_TAG, "## getPendingToken() : roomId " + roomId + " token " + expectedToken);
return expectedToken;
}
/**
* Store a token for a dedicated room
*
* @param dict the token cache
* @param roomId the room id
* @param token the token
*/
private void putPendingToken(final Map<String, String> dict, final String roomId, final String token) {
Log.d(LOG_TAG, "## putPendingToken() : roomId " + roomId + " token " + token);
synchronized (dict) {
// null is allowed for a request
if (null == token) {
dict.put(roomId, "");
} else {
dict.put(roomId, token);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shindig.gadgets.oauth;
import com.google.common.collect.Lists;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.common.Pair;
import org.apache.shindig.common.crypto.BlobCrypter;
import org.apache.shindig.common.crypto.BlobCrypterException;
import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.http.HttpResponseBuilder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Container for OAuth specific data to include in the response to the client.
*/
public class OAuthResponseParams {
private static final Logger LOG = Logger.getLogger(OAuthResponseParams.class.getName());
// Finds the values of sensitive response params: oauth_token_secret and oauth_session_handle
private static final Pattern REMOVE_SECRETS =
Pattern.compile("(?<=(oauth_token_secret|oauth_session_handle)=)[^=& \t\r\n]*");
// names for the JSON values we return to the client
public static final String CLIENT_STATE = "oauthState";
public static final String APPROVAL_URL = "oauthApprovalUrl";
public static final String ERROR_CODE = "oauthError";
public static final String ERROR_TEXT = "oauthErrorText";
/**
* Transient state we want to cache client side.
*/
private final OAuthClientState newClientState;
/**
* Security token used to authenticate request.
*/
private final SecurityToken securityToken;
/**
* Original request from client.
*/
private final HttpRequest originalRequest;
/**
* Request/response pairs we sent onward.
*/
private final List<Pair<HttpRequest, HttpResponse>> requestTrace = Lists.newArrayList();
/**
* Authorization URL for the client.
*/
private String aznUrl;
/**
* Whether we should include the request trace in the response to the application.
*
* It might be nice to make this configurable based on options passed to makeRequest. For now
* we use some heuristics to figure it out.
*/
private boolean sendTraceToClient;
/**
* Create response parameters.
*/
public OAuthResponseParams(SecurityToken securityToken, HttpRequest originalRequest,
BlobCrypter stateCrypter) {
this.securityToken = securityToken;
this.originalRequest = originalRequest;
newClientState = new OAuthClientState(stateCrypter);
}
/**
* Log a warning message that includes the details of the request.
*/
public void logDetailedWarning(String note) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, note + '\n' + getDetails(null));
}
}
/**
* Log a warning message that includes the details of the request and the thrown exception.
*/
public void logDetailedWarning(String note, Throwable e) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, note + '\n' + getDetails(e), e);
}
}
public void logDetailedInfo(String note, Throwable e) {
if (LOG.isLoggable(Level.INFO)) {
LOG.log(Level.INFO, note + '\n' + getDetails(e), e);
}
}
/**
* Add a request/response pair to our trace of actions associated with this request.
*/
public void addRequestTrace(HttpRequest request, HttpResponse response) {
this.requestTrace.add(Pair.of(request, response));
}
/**
* @return true if the target server returned an error at some point during the request
*/
public boolean sawErrorResponse() {
for (Pair<HttpRequest, HttpResponse> event : requestTrace) {
if (event.two == null || event.two.isError()) {
return true;
}
}
return false;
}
private String getDetails(Throwable e) {
String error = null;
if (null != e) {
if(e instanceof OAuthRequestException) {
OAuthRequestException reqException = ((OAuthRequestException) e);
error = reqException.getError() + ", " + reqException.getErrorText();
}
else {
error = e.getMessage();
}
}
return "OAuth error [" + error + "] for application "
+ securityToken.getAppUrl() + ". Request trace:" + getRequestTrace();
}
private String getRequestTrace() {
StringBuilder trace = new StringBuilder();
trace.append("\n==== Original request:\n");
trace.append(originalRequest);
trace.append("\n====");
int i = 1;
for (Pair<HttpRequest, HttpResponse> event : requestTrace) {
trace.append("\n==== Sent request ").append(i).append(":\n");
if (event.one != null) {
trace.append(filterSecrets(event.one.toString()));
}
trace.append("\n==== Received response ").append(i).append(":\n");
if (event.two != null) {
trace.append(filterSecrets(event.two.toString()));
}
trace.append("\n====");
++i;
}
return trace.toString();
}
/**
* Removes security sensitive parameters from requests and responses.
*/
static String filterSecrets(String in) {
Matcher m = REMOVE_SECRETS.matcher(in);
return m.replaceAll("REMOVED");
}
/**
* Update a response with additional data to be returned to the application.
*/
public void addToResponse(HttpResponseBuilder response, OAuthRequestException e) {
if (!newClientState.isEmpty()) {
try {
response.setMetadata(CLIENT_STATE, newClientState.getEncryptedState());
} catch (BlobCrypterException cryptException) {
// Configuration error somewhere, this should never happen.
throw new RuntimeException(cryptException);
}
}
if (aznUrl != null) {
response.setMetadata(APPROVAL_URL, aznUrl);
}
if (e != null || sendTraceToClient) {
StringBuilder verboseError = new StringBuilder();
if (e != null) {
response.setMetadata(ERROR_CODE, e.getError());
verboseError.append(e.getErrorText());
}
if (sendTraceToClient) {
verboseError.append('\n');
verboseError.append(getRequestTrace());
}
response.setMetadata(ERROR_TEXT, verboseError.toString());
}
}
/**
* Get the state we will return to the client.
*/
public OAuthClientState getNewClientState() {
return newClientState;
}
public String getAznUrl() {
return aznUrl;
}
/**
* Set the authorization URL we will return to the client.
*/
public void setAznUrl(String aznUrl) {
this.aznUrl = aznUrl;
}
public boolean sendTraceToClient() {
return sendTraceToClient;
}
public void setSendTraceToClient(boolean sendTraceToClient) {
this.sendTraceToClient = sendTraceToClient;
}
}
| |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.xwalk.core.internal;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.http.SslError;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
import org.chromium.content.browser.ContentViewClient;
import org.chromium.content.browser.WebContentsObserverAndroid;
import org.chromium.content_public.browser.WebContents;
import org.chromium.net.NetError;
/**
* Base-class that a XWalkViewContents embedder derives from to receive callbacks.
* This extends ContentViewClient, as in many cases we want to pass-thru ContentViewCore
* callbacks right to our embedder, and this setup facilities that.
* For any other callbacks we need to make transformations of (e.g. adapt parameters
* or perform filtering) we can provide final overrides for methods here, and then introduce
* new abstract methods that the our own client must implement.
* i.e.: all methods in this class should either be final, or abstract.
*/
abstract class XWalkContentsClient extends ContentViewClient {
private static final String TAG = "XWalkContentsClient";
private final XWalkContentsClientCallbackHelper mCallbackHelper =
new XWalkContentsClientCallbackHelper(this);
private XWalkWebContentsObserver mWebContentsObserver;
private double mDIPScale;
public class XWalkWebContentsObserver extends WebContentsObserverAndroid {
public XWalkWebContentsObserver(WebContents webContents) {
super(webContents);
}
@Override
public void didStopLoading(String url) {
onPageFinished(url);
}
@Override
public void didFailLoad(boolean isProvisionalLoad,
boolean isMainFrame, int errorCode, String description, String failingUrl) {
if (errorCode == NetError.ERR_ABORTED || !isMainFrame) {
// This error code is generated for the following reasons:
// - XWalkViewInternal.stopLoading is called,
// - the navigation is intercepted by the embedder via shouldOverrideNavigation.
//
// The XWalkViewInternal does not notify the embedder of these situations using this
// error code with the XWalkClient.onReceivedError callback. What's more,
// the XWalkViewInternal does not notify the embedder of sub-frame failures.
return;
}
onReceivedError(ErrorCodeConversionHelper.convertErrorCode(errorCode),
description, failingUrl);
}
@Override
public void didNavigateAnyFrame(String url, String baseUrl, boolean isReload) {
doUpdateVisitedHistory(url, isReload);
}
@Override
public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) {
// Both didStopLoading and didFinishLoad will be called once a page is finished
// to load, but didStopLoading will also be called when user clicks "X" button
// on browser UI to stop loading page.
//
// So it is safe for Crosswalk to rely on didStopLoading to ensure onPageFinished
// can be called.
}
}
@Override
final public void onUpdateTitle(String title) {
onTitleChanged(title);
}
@Override
public boolean shouldOverrideKeyEvent(KeyEvent event) {
return super.shouldOverrideKeyEvent(event);
}
void installWebContentsObserver(WebContents webContents) {
if (mWebContentsObserver != null) {
mWebContentsObserver.detachFromWebContents();
}
mWebContentsObserver = new XWalkWebContentsObserver(webContents);
}
void setDIPScale(double dipScale) {
mDIPScale = dipScale;
}
final XWalkContentsClientCallbackHelper getCallbackHelper() {
return mCallbackHelper;
}
//--------------------------------------------------------------------------------------------
// XWalkViewInternal specific methods that map directly to XWalkViewClient / XWalkWebChromeClient
//--------------------------------------------------------------------------------------------
public abstract void getVisitedHistory(ValueCallback<String[]> callback);
public abstract void doUpdateVisitedHistory(String url, boolean isReload);
public abstract void onProgressChanged(int progress);
public abstract WebResourceResponse shouldInterceptRequest(String url);
public abstract void onResourceLoadStarted(String url);
public abstract void onResourceLoadFinished(String url);
public abstract void onLoadResource(String url);
public abstract boolean shouldOverrideUrlLoading(String url);
public abstract void onUnhandledKeyEvent(KeyEvent event);
public abstract boolean onConsoleMessage(ConsoleMessage consoleMessage);
public abstract void onReceivedHttpAuthRequest(XWalkHttpAuthHandler handler,
String host, String realm);
public abstract void onReceivedSslError(ValueCallback<Boolean> callback, SslError error);
public abstract void onReceivedLoginRequest(String realm, String account, String args);
public abstract void onFormResubmission(Message dontResend, Message resend);
public abstract void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength);
public abstract void onGeolocationPermissionsShowPrompt(String origin,
XWalkGeolocationPermissions.Callback callback);
public abstract void onGeolocationPermissionsHidePrompt();
public final void onScaleChanged(float oldScaleFactor, float newScaleFactor) {
onScaleChangedScaled((float)(oldScaleFactor * mDIPScale), (float)(newScaleFactor * mDIPScale));
}
public abstract void onScaleChangedScaled(float oldScale, float newScale);
protected abstract boolean onCreateWindow(boolean isDialog, boolean isUserGesture);
protected abstract void onCloseWindow();
public abstract void onReceivedIcon(Bitmap bitmap);
protected abstract void onRequestFocus();
public abstract void onPageStarted(String url);
public abstract void onPageFinished(String url);
protected abstract void onStopLoading();
public abstract void onReceivedError(int errorCode, String description, String failingUrl);
public abstract void onRendererUnresponsive();
public abstract void onRendererResponsive();
public abstract void onTitleChanged(String title);
public abstract void onToggleFullscreen(boolean enterFullscreen);
public abstract boolean hasEnteredFullscreen();
public abstract boolean shouldOverrideRunFileChooser(
int processId, int renderId, int mode, String acceptTypes, boolean capture);
// TODO (michaelbai): Remove this method once the same method remove from
// XWalkContentsClientAdapter.
public abstract void onShowCustomView(View view,
int requestedOrientation, XWalkWebChromeClient.CustomViewCallback callback);
// TODO (michaelbai): This method should be abstract, having empty body here
// makes the merge to the Android easy.
public void onShowCustomView(View view, XWalkWebChromeClient.CustomViewCallback callback) {
onShowCustomView(view, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, callback);
}
public abstract void onHideCustomView();
public abstract void didFinishLoad(String url);
//--------------------------------------------------------------------------------------------
// Other XWalkViewInternal-specific methods
//--------------------------------------------------------------------------------------------
//
public abstract void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches,
boolean isDoneCounting);
/**
* Called whenever there is a new content picture available.
* @param picture New picture.
*/
public abstract void onNewPicture(Picture picture);
public abstract boolean shouldOpenWithDefaultBrowser(String contentUrl);
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.protocol.core.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException;
import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.persistence.OperationContext;
import org.apache.activemq.artemis.core.protocol.core.Channel;
import org.apache.activemq.artemis.core.protocol.core.ChannelHandler;
import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.ServerSessionPacketHandler;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverReplyMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateQueueMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ReattachSessionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ReattachSessionResponseMessage;
import org.apache.activemq.artemis.core.security.ActiveMQPrincipal;
import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.RoutingType;
import org.apache.activemq.artemis.core.server.ServerSession;
import org.apache.activemq.artemis.core.version.Version;
import org.jboss.logging.Logger;
/**
* A packet handler for all packets that need to be handled at the server level
*/
public class ActiveMQPacketHandler implements ChannelHandler {
private static final Logger logger = Logger.getLogger(ActiveMQPacketHandler.class);
private final ActiveMQServer server;
private final Channel channel1;
private final CoreRemotingConnection connection;
private final CoreProtocolManager protocolManager;
public ActiveMQPacketHandler(final CoreProtocolManager protocolManager,
final ActiveMQServer server,
final Channel channel1,
final CoreRemotingConnection connection) {
this.protocolManager = protocolManager;
this.server = server;
this.channel1 = channel1;
this.connection = connection;
}
@Override
public void handlePacket(final Packet packet) {
byte type = packet.getType();
switch (type) {
case PacketImpl.CREATESESSION: {
CreateSessionMessage request = (CreateSessionMessage) packet;
handleCreateSession(request);
break;
}
case PacketImpl.CHECK_FOR_FAILOVER: {
CheckFailoverMessage request = (CheckFailoverMessage) packet;
handleCheckForFailover(request);
break;
}
case PacketImpl.REATTACH_SESSION: {
ReattachSessionMessage request = (ReattachSessionMessage) packet;
handleReattachSession(request);
break;
}
case PacketImpl.CREATE_QUEUE: {
// Create queue can also be fielded here in the case of a replicated store and forward queue creation
CreateQueueMessage request = (CreateQueueMessage) packet;
handleCreateQueue(request);
break;
}
default: {
ActiveMQServerLogger.LOGGER.invalidPacket(packet);
}
}
}
private void handleCheckForFailover(CheckFailoverMessage failoverMessage) {
String nodeID = failoverMessage.getNodeID();
boolean okToFailover = nodeID == null || !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(new SimpleString(nodeID)));
channel1.send(new CheckFailoverReplyMessage(okToFailover));
}
private void handleCreateSession(final CreateSessionMessage request) {
boolean incompatibleVersion = false;
Packet response;
try {
Version version = server.getVersion();
if (!version.isCompatible(request.getVersion())) {
throw ActiveMQMessageBundle.BUNDLE.incompatibleClientServer();
}
if (!server.isStarted()) {
throw ActiveMQMessageBundle.BUNDLE.serverNotStarted();
}
// XXX HORNETQ-720 Taylor commented out this test. Should be verified.
/*if (!server.checkActivate())
{
throw new ActiveMQException(ActiveMQException.SESSION_CREATION_REJECTED,
"Server will not accept create session requests");
}*/
if (connection.getClientVersion() == 0) {
connection.setClientVersion(request.getVersion());
} else if (connection.getClientVersion() != request.getVersion()) {
ActiveMQServerLogger.LOGGER.incompatibleVersionAfterConnect(request.getVersion(), connection.getClientVersion());
}
Channel channel = connection.getChannel(request.getSessionChannelID(), request.getWindowSize());
ActiveMQPrincipal activeMQPrincipal = null;
if (request.getUsername() == null) {
activeMQPrincipal = connection.getDefaultActiveMQPrincipal();
}
OperationContext sessionOperationContext = server.newOperationContext();
Map<SimpleString, RoutingType> routingTypeMap = protocolManager.getPrefixes();
if (connection.getClientVersion() < PacketImpl.ADDRESSING_CHANGE_VERSION) {
routingTypeMap = new HashMap<>();
routingTypeMap.put(PacketImpl.OLD_QUEUE_PREFIX, RoutingType.ANYCAST);
routingTypeMap.put(PacketImpl.OLD_TOPIC_PREFIX, RoutingType.MULTICAST);
}
ServerSession session = server.createSession(request.getName(), activeMQPrincipal == null ? request.getUsername() : activeMQPrincipal.getUserName(), activeMQPrincipal == null ? request.getPassword() : activeMQPrincipal.getPassword(), request.getMinLargeMessageSize(), connection, request.isAutoCommitSends(), request.isAutoCommitAcks(), request.isPreAcknowledge(), request.isXA(), request.getDefaultAddress(), new CoreSessionCallback(request.getName(), protocolManager, channel, connection), true, sessionOperationContext, routingTypeMap);
ServerSessionPacketHandler handler = new ServerSessionPacketHandler(session, server.getStorageManager(), channel);
channel.setHandler(handler);
// TODO - where is this removed?
protocolManager.addSessionHandler(request.getName(), handler);
response = new CreateSessionResponseMessage(server.getVersion().getIncrementingVersion());
} catch (ActiveMQSecurityException e) {
ActiveMQServerLogger.LOGGER.securityProblemWhileCreatingSession(e.getMessage());
response = new ActiveMQExceptionMessage(e);
} catch (ActiveMQException e) {
if (e.getType() == ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) {
incompatibleVersion = true;
logger.debug("Sending ActiveMQException after Incompatible client", e);
} else {
ActiveMQServerLogger.LOGGER.failedToCreateSession(e);
}
response = new ActiveMQExceptionMessage(e);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.failedToCreateSession(e);
response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException());
}
// send the exception to the client and destroy
// the connection if the client and server versions
// are not compatible
if (incompatibleVersion) {
channel1.sendAndFlush(response);
} else {
channel1.send(response);
}
}
private void handleReattachSession(final ReattachSessionMessage request) {
Packet response = null;
try {
if (!server.isStarted()) {
response = new ReattachSessionResponseMessage(-1, false);
}
logger.debug("Reattaching request from " + connection.getRemoteAddress());
ServerSessionPacketHandler sessionHandler = protocolManager.getSessionHandler(request.getName());
// HORNETQ-720 XXX ataylor?
if (/*!server.checkActivate() || */ sessionHandler == null) {
response = new ReattachSessionResponseMessage(-1, false);
} else {
if (sessionHandler.getChannel().getConfirmationWindowSize() == -1) {
// Even though session exists, we can't reattach since confi window size == -1,
// i.e. we don't have a resend cache for commands, so we just close the old session
// and let the client recreate
ActiveMQServerLogger.LOGGER.reattachRequestFailed(connection.getRemoteAddress());
sessionHandler.closeListeners();
sessionHandler.close();
response = new ReattachSessionResponseMessage(-1, false);
} else {
// Reconnect the channel to the new connection
int serverLastConfirmedCommandID = sessionHandler.transferConnection(connection, request.getLastConfirmedCommandID());
response = new ReattachSessionResponseMessage(serverLastConfirmedCommandID, true);
}
}
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.failedToReattachSession(e);
response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException());
}
channel1.send(response);
}
private void handleCreateQueue(final CreateQueueMessage request) {
try {
server.createQueue(request.getAddress(), null, request.getQueueName(), request.getFilterString(), request.isDurable(), request.isTemporary());
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.failedToHandleCreateQueue(e);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.streams.state.internals;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.KeyValueStoreTestDriver;
import org.apache.kafka.test.InternalMockProcessorContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public abstract class AbstractKeyValueStoreTest {
protected abstract <K, V> KeyValueStore<K, V> createKeyValueStore(final ProcessorContext context);
protected InternalMockProcessorContext context;
protected KeyValueStore<Integer, String> store;
protected KeyValueStoreTestDriver<Integer, String> driver;
@Before
public void before() {
driver = KeyValueStoreTestDriver.create(Integer.class, String.class);
context = (InternalMockProcessorContext) driver.context();
context.setTime(10);
store = createKeyValueStore(context);
}
@After
public void after() {
store.close();
driver.clear();
}
private static Map<Integer, String> getContents(final KeyValueIterator<Integer, String> iter) {
final HashMap<Integer, String> result = new HashMap<>();
while (iter.hasNext()) {
final KeyValue<Integer, String> entry = iter.next();
result.put(entry.key, entry.value);
}
return result;
}
@Test
public void shouldNotIncludeDeletedFromRangeResult() {
store.close();
final Serializer<String> serializer = new StringSerializer() {
private int numCalls = 0;
@Override
public byte[] serialize(final String topic, final String data) {
if (++numCalls > 3) {
fail("Value serializer is called; it should never happen");
}
return super.serialize(topic, data);
}
};
context.setValueSerde(Serdes.serdeFrom(serializer, new StringDeserializer()));
store = createKeyValueStore(driver.context());
store.put(0, "zero");
store.put(1, "one");
store.put(2, "two");
store.delete(0);
store.delete(1);
// should not include deleted records in iterator
final Map<Integer, String> expectedContents = Collections.singletonMap(2, "two");
assertEquals(expectedContents, getContents(store.all()));
}
@Test
public void shouldDeleteIfSerializedValueIsNull() {
store.close();
final Serializer<String> serializer = new StringSerializer() {
@Override
public byte[] serialize(final String topic, final String data) {
if (data.equals("null")) {
// will be serialized to null bytes, indicating deletes
return null;
}
return super.serialize(topic, data);
}
};
context.setValueSerde(Serdes.serdeFrom(serializer, new StringDeserializer()));
store = createKeyValueStore(driver.context());
store.put(0, "zero");
store.put(1, "one");
store.put(2, "two");
store.put(0, "null");
store.put(1, "null");
// should not include deleted records in iterator
final Map<Integer, String> expectedContents = Collections.singletonMap(2, "two");
assertEquals(expectedContents, getContents(store.all()));
}
@Test
public void testPutGetRange() {
// Verify that the store reads and writes correctly ...
store.put(0, "zero");
store.put(1, "one");
store.put(2, "two");
store.put(4, "four");
store.put(5, "five");
assertEquals(5, driver.sizeOf(store));
assertEquals("zero", store.get(0));
assertEquals("one", store.get(1));
assertEquals("two", store.get(2));
assertNull(store.get(3));
assertEquals("four", store.get(4));
assertEquals("five", store.get(5));
// Flush now so that for caching store, we will not skip the deletion following an put
store.flush();
store.delete(5);
assertEquals(4, driver.sizeOf(store));
// Flush the store and verify all current entries were properly flushed ...
store.flush();
assertEquals("zero", driver.flushedEntryStored(0));
assertEquals("one", driver.flushedEntryStored(1));
assertEquals("two", driver.flushedEntryStored(2));
assertEquals("four", driver.flushedEntryStored(4));
assertNull(driver.flushedEntryStored(5));
assertFalse(driver.flushedEntryRemoved(0));
assertFalse(driver.flushedEntryRemoved(1));
assertFalse(driver.flushedEntryRemoved(2));
assertFalse(driver.flushedEntryRemoved(4));
assertTrue(driver.flushedEntryRemoved(5));
final HashMap<Integer, String> expectedContents = new HashMap<>();
expectedContents.put(2, "two");
expectedContents.put(4, "four");
// Check range iteration ...
assertEquals(expectedContents, getContents(store.range(2, 4)));
assertEquals(expectedContents, getContents(store.range(2, 6)));
// Check all iteration ...
expectedContents.put(0, "zero");
expectedContents.put(1, "one");
assertEquals(expectedContents, getContents(store.all()));
}
@Test
public void testPutGetRangeWithDefaultSerdes() {
// Verify that the store reads and writes correctly ...
store.put(0, "zero");
store.put(1, "one");
store.put(2, "two");
store.put(4, "four");
store.put(5, "five");
assertEquals(5, driver.sizeOf(store));
assertEquals("zero", store.get(0));
assertEquals("one", store.get(1));
assertEquals("two", store.get(2));
assertNull(store.get(3));
assertEquals("four", store.get(4));
assertEquals("five", store.get(5));
store.flush();
store.delete(5);
// Flush the store and verify all current entries were properly flushed ...
store.flush();
assertEquals("zero", driver.flushedEntryStored(0));
assertEquals("one", driver.flushedEntryStored(1));
assertEquals("two", driver.flushedEntryStored(2));
assertEquals("four", driver.flushedEntryStored(4));
assertNull(null, driver.flushedEntryStored(5));
assertFalse(driver.flushedEntryRemoved(0));
assertFalse(driver.flushedEntryRemoved(1));
assertFalse(driver.flushedEntryRemoved(2));
assertFalse(driver.flushedEntryRemoved(4));
assertTrue(driver.flushedEntryRemoved(5));
}
@Test
public void testRestore() {
store.close();
// Add any entries that will be restored to any store
// that uses the driver's context ...
driver.addEntryToRestoreLog(0, "zero");
driver.addEntryToRestoreLog(1, "one");
driver.addEntryToRestoreLog(2, "two");
driver.addEntryToRestoreLog(3, "three");
// Create the store, which should register with the context and automatically
// receive the restore entries ...
store = createKeyValueStore(driver.context());
context.restore(store.name(), driver.restoredEntries());
// Verify that the store's contents were properly restored ...
assertEquals(0, driver.checkForRestoredEntries(store));
// and there are no other entries ...
assertEquals(4, driver.sizeOf(store));
}
@Test
public void testRestoreWithDefaultSerdes() {
store.close();
// Add any entries that will be restored to any store
// that uses the driver's context ...
driver.addEntryToRestoreLog(0, "zero");
driver.addEntryToRestoreLog(1, "one");
driver.addEntryToRestoreLog(2, "two");
driver.addEntryToRestoreLog(3, "three");
// Create the store, which should register with the context and automatically
// receive the restore entries ...
store = createKeyValueStore(driver.context());
context.restore(store.name(), driver.restoredEntries());
// Verify that the store's contents were properly restored ...
assertEquals(0, driver.checkForRestoredEntries(store));
// and there are no other entries ...
assertEquals(4, driver.sizeOf(store));
}
@Test
public void testPutIfAbsent() {
// Verify that the store reads and writes correctly ...
assertNull(store.putIfAbsent(0, "zero"));
assertNull(store.putIfAbsent(1, "one"));
assertNull(store.putIfAbsent(2, "two"));
assertNull(store.putIfAbsent(4, "four"));
assertEquals("four", store.putIfAbsent(4, "unexpected value"));
assertEquals(4, driver.sizeOf(store));
assertEquals("zero", store.get(0));
assertEquals("one", store.get(1));
assertEquals("two", store.get(2));
assertNull(store.get(3));
assertEquals("four", store.get(4));
// Flush the store and verify all current entries were properly flushed ...
store.flush();
assertEquals("zero", driver.flushedEntryStored(0));
assertEquals("one", driver.flushedEntryStored(1));
assertEquals("two", driver.flushedEntryStored(2));
assertEquals("four", driver.flushedEntryStored(4));
assertFalse(driver.flushedEntryRemoved(0));
assertFalse(driver.flushedEntryRemoved(1));
assertFalse(driver.flushedEntryRemoved(2));
assertFalse(driver.flushedEntryRemoved(4));
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnPutNullKey() {
store.put(null, "anyValue");
}
@Test
public void shouldNotThrowNullPointerExceptionOnPutNullValue() {
store.put(1, null);
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnPutIfAbsentNullKey() {
store.putIfAbsent(null, "anyValue");
}
@Test
public void shouldNotThrowNullPointerExceptionOnPutIfAbsentNullValue() {
store.putIfAbsent(1, null);
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnPutAllNullKey() {
store.putAll(Collections.singletonList(new KeyValue<>(null, "anyValue")));
}
@Test
public void shouldNotThrowNullPointerExceptionOnPutAllNullKey() {
store.putAll(Collections.singletonList(new KeyValue<>(1, null)));
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnDeleteNullKey() {
store.delete(null);
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnGetNullKey() {
store.get(null);
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnRangeNullFromKey() {
store.range(null, 2);
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnRangeNullToKey() {
store.range(2, null);
}
@Test
public void testSize() {
assertEquals("A newly created store should have no entries", 0, store.approximateNumEntries());
store.put(0, "zero");
store.put(1, "one");
store.put(2, "two");
store.put(4, "four");
store.put(5, "five");
store.flush();
assertEquals(5, store.approximateNumEntries());
}
@Test
public void shouldPutAll() {
final List<KeyValue<Integer, String>> entries = new ArrayList<>();
entries.add(new KeyValue<>(1, "one"));
entries.add(new KeyValue<>(2, "two"));
store.putAll(entries);
final List<KeyValue<Integer, String>> allReturned = new ArrayList<>();
final List<KeyValue<Integer, String>> expectedReturned = Arrays.asList(KeyValue.pair(1, "one"), KeyValue.pair(2, "two"));
final Iterator<KeyValue<Integer, String>> iterator = store.all();
while (iterator.hasNext()) {
allReturned.add(iterator.next());
}
assertThat(allReturned, equalTo(expectedReturned));
}
@Test
public void shouldDeleteFromStore() {
store.put(1, "one");
store.put(2, "two");
store.delete(2);
assertNull(store.get(2));
}
@Test
public void shouldReturnSameResultsForGetAndRangeWithEqualKeys() {
final List<KeyValue<Integer, String>> entries = new ArrayList<>();
entries.add(new KeyValue<>(1, "one"));
entries.add(new KeyValue<>(2, "two"));
entries.add(new KeyValue<>(3, "three"));
store.putAll(entries);
final Iterator<KeyValue<Integer, String>> iterator = store.range(2, 2);
assertEquals(iterator.next().value, store.get(2));
assertFalse(iterator.hasNext());
}
@Test
public void shouldNotThrowConcurrentModificationException() {
store.put(0, "zero");
final KeyValueIterator<Integer, String> results = store.range(0, 2);
store.put(1, "one");
assertEquals(new KeyValue<>(0, "zero"), results.next());
}
@Test
public void shouldNotThrowInvalidRangeExceptionWithNegativeFromKey() {
LogCaptureAppender.setClassLoggerToDebug(InMemoryWindowStore.class);
final LogCaptureAppender appender = LogCaptureAppender.createAndRegister();
final KeyValueIterator<Integer, String> iterator = store.range(-1, 1);
assertFalse(iterator.hasNext());
final List<String> messages = appender.getMessages();
assertThat(messages, hasItem("Returning empty iterator for fetch with invalid key range: from > to. "
+ "This may be due to serdes that don't preserve ordering when lexicographically comparing the serialized bytes. "
+ "Note that the built-in numerical serdes do not follow this for negative numbers"));
}
}
| |
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.impl.client.deployment;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
/**
* A set of privileged actions that are not to leak out
* of this package
*
* @version $Revision: $
*/
final class SecurityActions
{
//-------------------------------------------------------------------------------||
// Constructor ------------------------------------------------------------------||
//-------------------------------------------------------------------------------||
/**
* No instantiation
*/
private SecurityActions()
{
throw new UnsupportedOperationException("No instantiation");
}
//-------------------------------------------------------------------------------||
// Utility Methods --------------------------------------------------------------||
//-------------------------------------------------------------------------------||
/**
* Obtains the Thread Context ClassLoader
*/
static ClassLoader getThreadContextClassLoader()
{
return AccessController.doPrivileged(GetTcclAction.INSTANCE);
}
static boolean isClassPresent(String name)
{
try
{
loadClass(name);
return true;
}
catch (Exception e)
{
return false;
}
}
static Class<?> loadClass(String className)
{
try
{
return Class.forName(className, true, getThreadContextClassLoader());
}
catch (ClassNotFoundException e)
{
try
{
return Class.forName(className, true, SecurityActions.class.getClassLoader());
}
catch (ClassNotFoundException e2)
{
throw new RuntimeException("Could not load class " + className, e2);
}
}
}
static <T> T newInstance(final String className, final Class<?>[] argumentTypes, final Object[] arguments, final Class<T> expectedType)
{
@SuppressWarnings("unchecked")
Class<T> implClass = (Class<T>) loadClass(className);
if (!expectedType.isAssignableFrom(implClass)) {
throw new RuntimeException("Loaded class " + className + " is not of expected type " + expectedType);
}
return newInstance(implClass, argumentTypes, arguments);
}
static <T> T newInstance(final String className, final Class<?>[] argumentTypes, final Object[] arguments, final Class<T> expectedType, ClassLoader classLoader)
{
Class<?> clazz = null;
try
{
clazz = Class.forName(className, false, classLoader);
}
catch (Exception e)
{
throw new RuntimeException("Could not load class " + className, e);
}
Object obj = newInstance(clazz, argumentTypes, arguments);
try
{
return expectedType.cast(obj);
}
catch (Exception e)
{
throw new RuntimeException("Loaded class " + className + " is not of expected type " + expectedType, e);
}
}
/**
* Create a new instance by finding a constructor that matches the argumentTypes signature
* using the arguments for instantiation.
*
* @param className Full classname of class to create
* @param argumentTypes The constructor argument types
* @param arguments The constructor arguments
* @return a new instance
* @throws IllegalArgumentException if className, argumentTypes, or arguments are null
* @throws RuntimeException if any exceptions during creation
* @author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
* @author <a href="mailto:andrew.rubinger@jboss.org">ALR</a>
*/
static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments)
{
if (implClass == null)
{
throw new IllegalArgumentException("ImplClass must be specified");
}
if (argumentTypes == null)
{
throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
}
if (arguments == null)
{
throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
}
final T obj;
try
{
Constructor<T> constructor = getConstructor(implClass, argumentTypes);
if(!constructor.isAccessible()) {
constructor.setAccessible(true);
}
obj = constructor.newInstance(arguments);
}
catch (Exception e)
{
throw new RuntimeException("Could not create new instance of " + implClass, e);
}
return obj;
}
/**
* Obtains the Constructor specified from the given Class and argument types
* @param clazz
* @param argumentTypes
* @return
* @throws NoSuchMethodException
*/
static <T> Constructor<T> getConstructor(final Class<T> clazz, final Class<?>... argumentTypes)
throws NoSuchMethodException
{
try
{
return AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<T>>()
{
public Constructor<T> run() throws NoSuchMethodException
{
return clazz.getDeclaredConstructor(argumentTypes);
}
});
}
// Unwrap
catch (final PrivilegedActionException pae)
{
final Throwable t = pae.getCause();
// Rethrow
if (t instanceof NoSuchMethodException)
{
throw (NoSuchMethodException) t;
}
else
{
// No other checked Exception thrown by Class.getConstructor
try
{
throw (RuntimeException) t;
}
// Just in case we've really messed up
catch (final ClassCastException cce)
{
throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
}
}
}
}
/**
* Set a single Field value
*
* @param target The object to set it on
* @param fieldName The field name
* @param value The new value
*/
public static void setFieldValue(final Class<?> source, final Object target, final String fieldName, final Object value) throws NoSuchFieldException
{
try
{
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>()
{
@Override
public Void run() throws Exception
{
Field field = source.getDeclaredField(fieldName);
if(!field.isAccessible())
{
field.setAccessible(true);
}
field.set(target, value);
return null;
}
});
}
// Unwrap
catch (final PrivilegedActionException pae)
{
final Throwable t = pae.getCause();
// Rethrow
if (t instanceof NoSuchFieldException)
{
throw (NoSuchFieldException) t;
}
else
{
// No other checked Exception thrown by Class.getConstructor
try
{
throw (RuntimeException) t;
}
// Just in case we've really messed up
catch (final ClassCastException cce)
{
throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
}
}
}
}
public static List<Field> getFieldsWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass)
{
List<Field> declaredAccessableFields = AccessController.doPrivileged(new PrivilegedAction<List<Field>>()
{
public List<Field> run()
{
List<Field> foundFields = new ArrayList<Field>();
Class<?> nextSource = source;
while (nextSource != Object.class) {
for(Field field : nextSource.getDeclaredFields())
{
if(field.isAnnotationPresent(annotationClass))
{
if(!field.isAccessible())
{
field.setAccessible(true);
}
foundFields.add(field);
}
}
nextSource = nextSource.getSuperclass();
}
return foundFields;
}
});
return declaredAccessableFields;
}
public static List<Method> getMethodsWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass)
{
List<Method> declaredAccessableMethods = AccessController.doPrivileged(new PrivilegedAction<List<Method>>()
{
public List<Method> run()
{
List<Method> foundMethods = new ArrayList<Method>();
Class<?> nextSource = source;
while (nextSource != Object.class) {
for(Method method : nextSource.getDeclaredMethods())
{
if(method.isAnnotationPresent(annotationClass))
{
if(!method.isAccessible())
{
method.setAccessible(true);
}
foundMethods.add(method);
}
}
nextSource = nextSource.getSuperclass();
}
return foundMethods;
}
});
return declaredAccessableMethods;
}
static String getProperty(final String key) {
try {
String value = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
public String run() {
return System.getProperty(key);
}
});
return value;
}
// Unwrap
catch (final PrivilegedActionException pae) {
final Throwable t = pae.getCause();
// Rethrow
if (t instanceof SecurityException) {
throw (SecurityException) t;
}
if (t instanceof NullPointerException) {
throw (NullPointerException) t;
} else if (t instanceof IllegalArgumentException) {
throw (IllegalArgumentException) t;
} else {
// No other checked Exception thrown by System.getProperty
try {
throw (RuntimeException) t;
}
// Just in case we've really messed up
catch (final ClassCastException cce) {
throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
}
}
}
}
//-------------------------------------------------------------------------------||
// Inner Classes ----------------------------------------------------------------||
//-------------------------------------------------------------------------------||
/**
* Single instance to get the TCCL
*/
private enum GetTcclAction implements PrivilegedAction<ClassLoader> {
INSTANCE;
public ClassLoader run()
{
return Thread.currentThread().getContextClassLoader();
}
}
}
| |
/*
* $Id: ColorKey.java,v 1.2 2006/01/19 14:45:48 luca Exp $
*
* This software is provided by NOAA for full, free and open release. It is
* understood by the recipient/user that NOAA assumes no liability for any
* errors contained in the code. Although this software is released without
* conditions or restrictions in its use, it is expected that appropriate
* credit be given to its author and to the National Oceanic and Atmospheric
* Administration should the software be included by the recipient as an
* element in other product development.
*/
package gov.noaa.pmel.sgt;
import gov.noaa.pmel.util.Rectangle2D;
import gov.noaa.pmel.util.Dimension2D;
import gov.noaa.pmel.util.Range2D;
import gov.noaa.pmel.util.Point2D;
import gov.noaa.pmel.util.Debug;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.awt.Point;
import it.unitn.ing.rista.util.Misc;
// jdk1.2
//import java.awt.geom.Rectangle2D;
//import java.awt.geom.Point2D;
/**
* The <code>ColorKey</code> class provides a graphical depiction
* of the relationship between a <code>ColorMap</code>
* and user values. A single <code>ColorKey</code> can be
* attached to a <code>Layer</code>. A <code>ColorMap</code>
* is associated with the Key and therefor with a specific transformation
* and optionally a <code>SGTData</code> object.
*
* @author Donald Denbo
* @version $Revision: 1.2 $, $Date: 2006/01/19 14:45:48 $
* @since 1.0
* @see Ruler
* @see ColorMap
* @see Layer
**/
public class ColorKey implements Cloneable, DataKey,
PropertyChangeListener {
// Scale members
/**@label title
* @link aggregationByValue
* @undirected
*/
private SGLabel title_ = null;
//
private String ident_;
/** @directed */
private Layer layer_;
/**@label scale
* @link aggregationByValue */
private Ruler scale_ = new Ruler(); // mod Tom Ewing
private int valign_;
private int halign_;
private int orient_;
private int style_;
private boolean selected_;
private boolean selectable_;
private boolean visible_;
/**
* maximum bounds of key in p-space
*/
// private Rectangle2D.Double pbounds_;
private Point2D.Double porigin_;
private Dimension2D psize_;
/**
* top, left, bottom, right in p-space
*/
private double[] insets_ = {0.05, 0.15, 0.05, 0.15};
private double barWidth_ = 0.2;
/**
* @label cm
*/
private ColorMap cm_ = null;
/**
* Use plain line border.
*/
public static final int PLAIN_LINE = 0;
/**
* Use raised border.
*/
public static final int RAISED = 1;
/**
* Do not draw a border.
*/
public static final int NO_BORDER = 2;
/**
* Align to top of key.
*/
public static final int TOP = 0;
/**
* Align to middle of key.
*/
public static final int MIDDLE = 1;
/**
* Align to bottom of key.
*/
public static final int BOTTOM = 2;
/**
* Align to left of key.
*/
public static final int LEFT = 0;
/**
* Align to center of key.
*/
public static final int CENTER = 1;
/**
* Align to right of key.
*/
public static final int RIGHT = 2;
/**
* Orient key horizontally.
*/
public static final int HORIZONTAL = 1;
/**
* Orient key vertically.
*/
public static final int VERTICAL = 2;
// private boolean moveable_ = false;
// private PropertyChangeSupport changes_ = new PropertyChangeSupport(this);
/**
* Default <code>ColorKey</code> constructor. The location and size
* must be specified before the <code>ColorKey</code> is
* attached to a layer!
**/
public ColorKey() {
this(new Rectangle2D.Double(), BOTTOM, LEFT);
}
/**
* <code>ColorKey</code> constructor that include location, size,
* and alignment information. Default orientation is
* <code>HORIZONTAL</code>.
*
* @param pr a Rectangle2D object that includes location and size
* @param valign vertical alignment
* @param halign horizontal alignment
**/
public ColorKey(Rectangle2D.Double pr,int valign,int halign) {
this(new Point2D.Double(pr.x, pr.y),
new Dimension2D(pr.width, pr.height),
valign, halign);
}
/**
* @since 3.0
*/
public ColorKey(Point2D.Double pt, Dimension2D size, int valign, int halign) {
porigin_ = pt;
psize_ = size;
// pbounds_ = new Rectangle2D.Double(pt.x, pt.y, size.width, size.height);
valign_ = valign;
halign_ = halign;
//
// set defaults
//
orient_ = HORIZONTAL;
selected_ = false;
selectable_ = true;
visible_ = true;
style_ = PLAIN_LINE;
// moveable_ = false;
}
/**
* Create a copy of <code>ColorKey</code>.
*
* @return a copy of the key
*/
public LayerChild copy() {
ColorKey newKey;
try {
newKey = (ColorKey)clone();
} catch (CloneNotSupportedException e) {
newKey = new ColorKey();
}
return (LayerChild)newKey;
}
/**
* Sets the <code>selected</code> property.
* @since 2.0
*
* @param sel true if selected, false if not.
*/
public void setSelected(boolean sel) {
selected_ = sel;
}
/**
* Returns true if the <code>selected</code> property is set.
*
* @return true is selected, false if not.
*/
public boolean isSelected() {
return selected_;
}
/**
* Sets the selectable property.
* @since 2.0
*/
public void setSelectable(boolean select) {
selectable_ = select;
}
/**
* Tests the selectable property.
* @since 2.0
*/
public boolean isSelectable() {
return selectable_;
}
/**
* Set ColorKey identifier.
*
* @param id key identifier
*/
public void setId(String id) {
ident_ = id;
}
/**
* Get <code>ColorKey</code> identifier
*
* @return identifier
*/
public String getId() {
return ident_;
}
/**
* Set parent <code>Layer</code>. Method should not be called
* directly, called when the <code>Layer.addChild</code>
* method is called.
*
* @param l parent layer
*/
public void setLayer(Layer l) {
layer_ = l;
}
/**
* Returns the layer the ColorKey is attached.
*
* @return The parent layer.
* @see Layer
**/
public Layer getLayer() {
return layer_;
}
/**
* Get the parent pane.
* @since 2.0
*/
public AbstractPane getPane() {
return layer_.getPane();
}
/**
* For internal sgt use.
* @since 2.0
*/
public void modified(String mess) {
// if(Debug.EVENT) System.out.println("ColorKey: modified()");
if(layer_ != null)
layer_.modified(mess);
}
/**
* Set color map.
*
* @param cm color map
*/
public void setColorMap(ColorMap cm) {
if(cm_ == null || !cm_.equals(cm)) {
if(cm_ != null) cm_.removePropertyChangeListener(this);
cm_ = cm;
cm_.addPropertyChangeListener(this);
modified("ColorKey: setColorMap()");
}
}
/**
* Add a GridCartesianRenderer and label to the ColorKey.
*
* @param rend GridCartesianRenderer object
* @param label descriptive label
* @since 3.0
*/
public void addGraph(CartesianRenderer rend, SGLabel label)
throws IllegalArgumentException {
if(!(rend instanceof GridCartesianRenderer))
throw new IllegalArgumentException("Renderer is not a GridCartesianRenderer");
GridAttribute ga = (GridAttribute)((GridCartesianRenderer)rend).getAttribute();
ColorMap cm = ga.getColorMap();
setColorMap(cm);
setTitle(label);
// addVectorGraph((VectorCartesianRenderer)rend, label);
}
/**
* Get color map.
*
* @return color map
*/
public ColorMap getColorMap() {
return cm_;
}
/**
* Set border style.
*
* @param style border style
* @see #PLAIN_LINE
* @see #RAISED
* @see #NO_BORDER
*/
public void setBorderStyle(int style) {
if(style_ != style) {
style_ = style;
modified("LineKey: setBorderStyle()");
}
}
/**
* Get border style.
*
* @return border style
*/
public int getBorderStyle() {
return style_;
}
/**
* Set color key alignment.
*
* @param vert vertical alignment
* @param horz horizontal alignment
*/
public void setAlign(int vert,int horz) {
if(valign_ != vert || halign_ != horz) {
valign_ = vert;
halign_ = horz;
modified("ColorKey: setAlign()");
}
}
/**
* Set orientation.
*
* @param orient key orientation
*/
public void setOrientation(int orient) {
if(orient_ != orient) {
orient_ = orient;
modified("ColorKey: setOrientation()");
}
}
/**
* Set vertical alignment
*
* @param vert vertical alignment
*/
public void setVAlign(int vert) {
if(valign_ != vert) {
valign_ = vert;
modified("ColorKey: setVAlign()");
}
}
/**
* Set horizontal alignment
*
* @param horz horizontal alignment
*/
public void setHAlign(int horz) {
if(halign_ != horz) {
halign_ = horz;
modified("ColorKey: setHAlign()");
}
}
/**
* Get vertical alignment
*
* @return vertical alignment
*/
public int getVAlign() {
return valign_;
}
/**
* Get horizontal alignment
*
* @return horizontal alignment
*/
public int getHAlign() {
return halign_;
}
/**
* Set location of key in physical coordinates.
*
* @param loc key location
*/
public void setLocationP(Point2D.Double loc) {
if(porigin_.x != loc.x || porigin_.y != loc.y) {
// Point2D.Double temp = new Point2D.Double(pbounds_.x, pbounds_.y);
porigin_.x = loc.x;
porigin_.y = loc.y;
modified("ColorKey: setLocationP()");
// changes_.firePropertyChange("location", temp, loc);
}
}
/**
* Set the size of the key in physical coordinates.
*
* @param d size of key
*/
public void setSizeP(Dimension2D d) {
if(psize_.width != d.width || psize_.height != d.height) {
psize_.width = d.width;
psize_.height = d.height;
modified("ColorKey: setSizeP()");
}
}
/**
* Set the bounds of the key in physical coordinates.
*
* @param r bounding rectangle
*/
public void setBoundsP(Rectangle2D.Double r) {
if(Debug.EVENT) System.out.println("ColorKey: porigin = " +
porigin_ + ", r = " + r);
setLocationP(new Point2D.Double(r.x, r.y));
setSizeP(new Dimension2D(r.width, r.height));
// if(pbounds_ == null || !pbounds_.equals(r)) {
// pbounds_ = r;
// modified("ColorKey: setBoundsP()");
// }
}
/**
* Get the bounding rectangle for the key in physical
* coordinates.
*
* @return bounding rectangle
*/
public Rectangle2D.Double getBoundsP() {
return new Rectangle2D.Double(porigin_.x, porigin_.y,
psize_.width, psize_.height);
}
/**
* Gets the bounding rectangle in device
* coordinates.
*
* @return bounding rectangle
*/
public Rectangle getBounds() {
int x, y, height, width;
x = layer_.getXPtoD(porigin_.x);
y = layer_.getYPtoD(porigin_.y);
width = layer_.getXPtoD(porigin_.x + psize_.width) - x;
height = layer_.getYPtoD(porigin_.y - psize_.height) - y;
switch(halign_) {
case RIGHT:
x = x - width;
break;
case CENTER:
x = x - width/2;
}
switch(valign_) {
case BOTTOM:
y = y - height;
break;
case MIDDLE:
y = y - height/2;
}
if(false) {
StringBuffer sbuf = new StringBuffer("\nColorKey.getBounds(): ");
switch(halign_) {
case RIGHT:
sbuf.append("RIGHT");
break;
case LEFT:
sbuf.append("LEFT");
break;
case CENTER:
sbuf.append("CENTER");
break;
}
sbuf.append(", ");
switch(valign_) {
case TOP:
sbuf.append("TOP");
break;
case BOTTOM:
sbuf.append("BOTTOM");
break;
case MIDDLE:
sbuf.append("MIDDLE");
break;
}
System.out.println(sbuf);
System.out.println(" orig = " + porigin_ + ", " + "size = " + psize_);
System.out.println(" x,y,width,height = " + x + ", " + y + ", " +
width + ", " + height);
System.out.println(" layer.getBounds() = " + layer_.getBounds());
System.out.println(" layer.getBoundsP() = " + layer_.getBoundsP());
}
return new Rectangle(x, y, width, height);
}
/**
* Change the selected objects bounding rectangle in
* device coordinates. The object will move to the new bounding
* rectangle.
*
* @param r new bounding rectangle
*/
public void setBounds(Rectangle r) {
setBounds(r.x, r.y, r.width, r.height);
}
/**
* Change the selected objects bounding rectangle in
* device coordinates. The object will move to the new bounding
* rectangle.
*
* @param x horizontal location, positive right
* @param y vertical location, positive down
* @param width horizontal size
* @param height vertical size
*/
public void setBounds(int x, int y, int width, int height) {
switch(halign_) {
case RIGHT:
x = x + width;
break;
case CENTER:
x = x + width/2;
}
switch(valign_) {
case BOTTOM:
y = y + height;
break;
case MIDDLE:
y = y + height/2;
}
// Point orig = new Point(layer_.getXPtoD(pbounds_.x),
// layer_.getYPtoD(pbounds_.y));
double xp = layer_.getXDtoP(x);
double yp = layer_.getYDtoP(y);
if(porigin_.x != xp || porigin_.y != yp) {
porigin_.x = xp;
porigin_.y = yp;
modified("ColorKey: setBounds()");
// changes_.firePropertyChange("location",
// orig, new Point(x,y));
}
}
/**
* Set the title of the key.
*
* @param title key title
*/
public void setTitle(SGLabel title) {
if(title_ == null || !title_.equals(title)) {
title_ = title;
modified("ColorKey: setTitle()");
}
}
/**
* Get the key's title.
*
* @return the title
*/
public SGLabel getTitle() {
return title_;
}
/**
* Get the <code>Ruler</code> associated
* with the key.
*
* @return the ruler
*/
public Ruler getRuler() {
return scale_;
}
/**
* Draw the ColorKey. This method should not be directly called.
*
* @see Pane#draw
*/
public void draw(Graphics g) {
Rectangle bounds;
double xp, yp; // lower-left coordinates in p-space
double ptop, pbottom, pleft, pright; // insets in p-space
double delta;
if(!visible_) return;
ptop = insets_[0];
pbottom =insets_[2];
pleft = insets_[1];
pright = insets_[3];
xp = porigin_.x;
yp = porigin_.y;
switch(halign_) {
case RIGHT:
xp = xp - psize_.width;
break;
case CENTER:
xp = xp - psize_.width/2;
}
switch(valign_) {
case TOP:
yp = yp - psize_.height;
break;
case MIDDLE:
yp = yp - psize_.height/2;
}
bounds = getBounds();
g.setColor(Color.black);
switch(style_) {
case PLAIN_LINE:
g.drawRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1);
break;
case RAISED:
break;
default:
case NO_BORDER:
}
if(cm_ == null) return;
Range2D uRange = cm_.getRange();
//
if(Double.isNaN(uRange.delta)) {
Range2D rnge = Graph.computeRange(uRange.start, uRange.end, 10);
delta = rnge.delta;
} else {
delta = uRange.delta;
}
if(orient_ == HORIZONTAL) {
drawBar(g, xp + pleft, yp + psize_.height - ptop,
psize_.width - pleft - pright,
psize_.height - ptop - pbottom);
//scale_ = new Ruler(); // mod Tom Ewing
scale_.setOrientation(Ruler.HORIZONTAL);
scale_.setLayer(layer_);
scale_.setTitle(title_);
scale_.setTicPosition(Ruler.NEGATIVE_SIDE);
scale_.setLabelPosition(Ruler.NEGATIVE_SIDE);
scale_.setBoundsP(new Rectangle2D.Double(xp + pleft,
yp + psize_.height - ptop - barWidth_,
psize_.width - pleft - pright,
psize_.height - ptop - pbottom));
scale_.setRangeU(new Range2D(uRange.start, uRange.end, delta));
scale_.draw(g);
} else {
drawBar(g, xp + pleft, yp + pbottom,
psize_.width - pleft - pright,
psize_.height - ptop - pbottom);
//scale_ = new Ruler(); // mod dwd
scale_.setOrientation(Ruler.VERTICAL);
scale_.setLayer(layer_);
scale_.setTitle(title_);
scale_.setTicPosition(Ruler.POSITIVE_SIDE);
scale_.setLabelPosition(Ruler.POSITIVE_SIDE);
scale_.setBoundsP(new Rectangle2D.Double(xp + pleft + barWidth_,
yp + pbottom,
psize_.width - pleft - pright,
psize_.height - ptop - pbottom));
scale_.setRangeU(new Range2D(uRange.start, uRange.end, delta));
scale_.draw(g);
}
}
//
void drawBar(Graphics g,
double plocx, double plocy,
double pwidth, double pheight) {
int yloc, xloc, xend, yend;
int dBarHeight, dBarWidth;
Range2D uRange = cm_.getRange();
AxisTransform sTrans;
if(orient_ == HORIZONTAL) {
dBarHeight = layer_.getYPtoD(plocy - barWidth_) -
layer_.getYPtoD(plocy);
sTrans = new LinearTransform(plocx, plocx + pwidth,
uRange.start, uRange.end);
yloc = layer_.getYPtoD(plocy);
xloc = layer_.getXPtoD(sTrans.getTransP(uRange.start));
xend = layer_.getXPtoD(sTrans.getTransP(uRange.end));
for(int i=xloc; i <= xend; i++) {
g.setColor(cm_.getColor(sTrans.getTransU(layer_.getXDtoP(i))));
g.fillRect(i, yloc, 1, dBarHeight);
}
} else {
dBarWidth = layer_.getXPtoD(plocx + barWidth_) - layer_.getXPtoD(plocx);
sTrans = new LinearTransform(plocy, plocy + pheight,
uRange.start, uRange.end);
xloc = layer_.getXPtoD(plocx);
yloc = layer_.getYPtoD(sTrans.getTransP(uRange.start));
yend = layer_.getYPtoD(sTrans.getTransP(uRange.end));
for(int i=yend; i <= yloc; i++) {
g.setColor(cm_.getColor(sTrans.getTransU(layer_.getXDtoP(i))));
g.fillRect(xloc, i, dBarWidth, 1);
}
}
}
/**
* Get a string representation of the key.
*
* @return string representation
*/
public String toString() {
String name = getClass().getName();
return name.substring(name.lastIndexOf(".")+1) + ": " + ident_;
}
/**
* Check if ColorKey is visible.
* @since 2.0
*/
public boolean isVisible() {
return visible_;
}
/**
* Set visibility state for ColorKey.
* @since 2.0
*/
public void setVisible(boolean visible) {
if(visible_ != visible) {
visible_ = visible;
modified("ColorKey: setVisible()");
}
}
public void propertyChange(PropertyChangeEvent evt) {
modified("ColorKey: propertyChange(" +
evt.getSource().toString() + "[" +
evt.getPropertyName() + "]" + ")");
}
/**
* Set columns. Unimplmented.
* @param col
* @since 3.0
*/
public void setColumns(int col) {}
/**
* Set line lenght. Unimplemented.
* @since 3.0
*/
public void setLineLengthP(double len) {}
}
| |
/*
Copyright 20010 by Sean Luke and George Mason University
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.gp.ge;
import java.io.*;
import java.util.*;
import ec.gp.*;
import ec.*;
import ec.vector.*;
import ec.util.*;
import java.util.regex.*;
/*
* GESpecies.java
*
* Created: Sun Dec 5 11:33:43 EST 2010
* By: Eric Kangas, Joseph Zelibor III, Houston Mooers, and Sean Luke
*
*/
/**
* <p>GESpecies generates GPIndividuals from GEIndividuals through the application of a dagp parse graph
* computed by the GrammarParser.
*
* <p>GESpecies uses a <b>GrammarParser</b> to do its dirty work. This parser's job is to take a dagp (in the form of a BufferedReader)
* and convert it to a tree of GrammarNodes which define the parse graph of the dagp. The GESpecies then interprets his parse graph
* according to the values in the GEIndividual to produce the equivalent GPIndividual, which is then evaluated.
*
* <p>To do this, GESpecies relies on a subsidiary GPSpecies which defines the GPIndividual and various GPFunctionSets from which to
* build the parser. This is a grand hack -- the GPSpecies does not know it's being used this way, and so we must provide various dummy
* parameters to keep the GPSpecies happy even though they'll never be used.
*
* <p>If you are daring, you can replace the GrammarParser with one of your own to customize the parse structure and dagp.
*
* <p><b>ECJ's Default GE Grammar</b> GE traditionally can use any dagp, and builds parse graphs from that. For simplicity, and in order to
* remain as compatable as possible with ECJ's existing GP facilities (and GP tradition), ECJ only uses a single Lisp-like dagp which
* generates standard ECJ trees. This doesn't lose much in generality as the dagp is quite genral.
*
* <p>The dagp assumes that expansion points are enclosed in <> and function are enclosed in (). For example:
*
* <p><tt>
* # This is a comment
* <prog> ::= <op><br>
* <op> ::= (if-food-ahead <op> <op>)<br>
* <op> ::= (progn2 <op> <op>)<br>
* <op> ::= (progn3 <op> <op> <op>)<br>
* <op> ::= (left) | (right) | (move)<br>
* </tt>
*
* <p>alternatively the dagp could also be writen in the following format:
*
* <p><tt>
* <prog> ::= <op><br>
* <op> ::= (if-food-ahead <op> <op>) | (progn2 <op> <op>) | (progn3 <op> <op> <op>) | (left) | (right) | (move)<br>
* </tt>
*
* <p>Note that you can use several lines to define the same dagp rule: for example, <tt><op></tt> was defined by several lines when
* it could have consisted of several elements separated by vertical pipes ( <tt>|</tt> ). Either way is fine, or a combination of both.
*
* <p>GPNodes are included in the dagp by using their name. This includes ERCs, ADFs, ADMs, and ADFArguments, which should all work just fine.
* For example, since most ERC GPNodes are simply named "ERC", if you have only one ERC GPNode in your function set, you can just use <tt>(ERC)</tt>
* in your dagp.
*
* <p>Once the gammar file has been created and setup has been run trees can the be created using the genome (chromosome) of a GEIndividual.
* A genome of an individual is an array of random integers each of which are one int long. These numbers are used when a decision point
* (a rule having more that one choice) is reached within the dagp. Once a particular gene (index) in the genome has been used it will
* not be used again (this may change) when creating the tree.
*
* <p>For example:<br>
* number of chromosomes used = 0<br>
* genome = {23, 654, 86}<br>
* the current rule we are considering is <op>.<br>
* %lt;op> can map into one of the following: (if-food-ahead <op> <op>) | (progn2 <op> <op>) | (progn3 <op> <op> <op>)
* | (left) | (right) | (move)<br>
* Since the rule <op> has more than one choice that it can map to, we must consult the genome to decide which choice to take. In this case
* the number of chromosomes used is 0 so genome[0] is used and number of chromosomes used is incremented. Since values in the genome can
* be negitive values they are offset by 128 (max negitive of a int) giving us a value from 0-255. A modulus is performed on this resulting
* number by the number of choices present for the given rule. In the above example since we are using genome[0] the resulting operation would
* look like: 23+128=151, number of choices for <op> = 6, 151%6=1 so we use choices[1] which is: (progn2 <op> <op>). If all the genes
* in a genome are used and the tree is still incompete an invalid tree error is returned.
*
* <p>Each node in the tree is a GPNode and trees are constructed depth first.
*
*
* <p><b>Parameters</b><br>
* <table>
* <tr><td valign=top><i>base.</i><tt>file</tt><br>
* <font size=-1>String</font></td>
* <td valign=top>(the file is where the rules of the gammar are stored)</td></tr>
*
* <tr><td valign=top><i>base.</i><tt>gp-species</tt><br>
* <font size=-1>classname, inherits and != ec.gp.GPSpecies</font></td>
* <td valign=top>(the GPSpecies subservient to the GESpecies)</td></tr>
*
* <tr><td valign=top><i>base.</i><tt>parser</tt><br>
* <font size=-1>classname, inherits and != ge.GrammarParser</font></td>
* <td valign=top>(the GrammarParser used by the GESpecies)</td></tr>
*
* </table>
*
* <p><b>Default Base</b><br>
* ge.GESpecies
*
* @author Joseph Zelibor III, Eric Kangas, Houston Mooers, and Sean Luke
* @version 1.0
*/
public class GESpecies extends IntegerVectorSpecies
{
private static final long serialVersionUID = 1;
public static final String P_GESPECIES = "species";
public static final String P_FILE = "file";
public static final String P_GPSPECIES = "gp-species";
public static final String P_PARSER = "parser";
public static final String P_PASSES = "passes";
public static final String P_INITSCHEME = "init-scheme" ;
/* Return value which denotes that the tree has grown too large. */
public static final int BIG_TREE_ERROR = -1;
/** The GPSpecies subsidiary to GESpecies. */
public GPSpecies gpspecies;
/**
All the ERCs created so far, the ERCs are mapped as,
"key --> list of ERC nodes", where the key = (genome[i] - minGene[i]);
The ERCBank is "static", beacause we need one identical copy
for all the individuals; Moreover, this copy may be sent to
other sub-populations as well.
*/
public HashMap ERCBank;
/** The parsed grammars. */
public GrammarRuleNode[] grammar;
/** The number of passes permitted through the genome if we're wrapping. Must be >= 1. */
public int passes;
public String initScheme = "default" ;
/** The prototypical parser used to parse the grammars. */
public GrammarParser parser_prototype;
/** Parser for each dagp -- khaled */
public GrammarParser[] grammarParser = null ;
public void setup(final EvolutionState state, final Parameter base)
{
super.setup(state, base);
Parameter p = base;
Parameter def = defaultBase();
p = base.push(P_GPSPECIES);
gpspecies = (GPSpecies) (state.parameters.getInstanceForParameterEq(p,
def.push(P_GPSPECIES), GPSpecies.class));
gpspecies.setup(state, p);
// check to make sure that our individual prototype is a GPIndividual
if (!(i_prototype instanceof IntegerVectorIndividual))
state.output.fatal("The Individual class for the Species "
+ getClass().getName()
+ " is must be a subclass of ge.GEIndividual.", base);
ERCBank = new HashMap();
// load the grammars, one per ADF tree
GPIndividual gpi = (GPIndividual) (gpspecies.i_prototype);
GPTree[] trees = gpi.trees;
int numGrammars = trees.length; // no. of trees = no. of grammars
parser_prototype = (GrammarParser) (state.parameters.getInstanceForParameterEq(
base.push(P_PARSER),
def.push(P_PARSER),
GrammarParser.class));
grammar = new GrammarRuleNode[numGrammars];
grammarParser = new GrammarParser[numGrammars] ;
for(int i = 0; i < numGrammars; i++)
{
p = base.push(P_FILE);
def = defaultBase();
// File grammarFile = state.parameters.getFile(p, def.push(P_FILE).push("" + i));
InputStream grammarFile = state.parameters.getResource(p,
def.push(P_FILE).push("" + i));
if(grammarFile == null)
state.output.fatal("Error retrieving dagp file(s): "
+ def.toString() + "."+ P_FILE + "." + i
+ " is undefined.");
GPFunctionSet gpfs =
trees[i].constraints((GPInitializer) state.initializer).functionset;
// now we need different parser object for each of the grammars,
// why? see GrammarParser.java for details -- khaled
grammarParser[i] = (GrammarParser)parser_prototype.clone();
BufferedReader br = new BufferedReader(new InputStreamReader(grammarFile));
grammar[i] = grammarParser[i].parseRules(state, br, gpfs);
// Enumerate the dagp tree -- khaled
grammarParser[i].enumerateGrammarTree(grammar[i]);
// Generate the predictive parse table -- khaled
grammarParser[i].populatePredictiveParseTable(grammar[i]);
try
{
br.close();
}
catch (IOException e)
{
// do nothing
}
}
// get the initialization scheme -- khaled
initScheme = state.parameters.getString(base.push(P_INITSCHEME), def.push(P_INITSCHEME));
if( initScheme != null && initScheme.equals("sensible"))
state.output.warnOnce("Using a \"hacked\" version of \"sensible initialization\"");
else
state.output.warnOnce("Using default GE initialization scheme");
// setup the "passes" parameters
final int MAXIMUM_PASSES = 1024;
passes = state.parameters.getInt(base.push(P_PASSES), def.push(P_PASSES), 1);
if (passes < 1 || passes > MAXIMUM_PASSES)
state.output.fatal("Number of allowed passes must be >= 1 and <="
+ MAXIMUM_PASSES + ", likely small, such as <= 16.",
base.push(P_PASSES), def.push(P_PASSES));
int oldpasses = passes;
passes = nextPowerOfTwo(passes);
if (oldpasses != passes)
state.output.warning("Number of allowed passes must be a power of 2. Bumping from "
+ oldpasses + " to " + passes,
base.push(P_PASSES), def.push(P_PASSES));
}
int nextPowerOfTwo(int v)
{
// if negative or 0, couldn't bump.
// See http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/**
* This is an ugly hack to simulate the "Sensible Initialization",
* First we create a GPIndividual, then reverse-map it to GEIndividuals,
* We do not need to call IntegerVectorSpecies.newIndividual() since it is overriden
* by the GPSpecies.newIndividual();
*
* Moreover, as in the case for non-identical representations (i,e, GP-GE island
* models etc,), the dagp rules, tree constraints, ERC's etc, are supposed to be
* identical across all islands, so we are using the same "gpspecies" inside this class.
*
* However, the identicality of the GPTree particulars like dagp, constraints, ADFs,
* ERC's may not be universally true.
*/
public Individual newIndividual(final EvolutionState state, int thread)
{
GEIndividual gei = null ;
if(initScheme != null && initScheme.equals("sensible"))
{
GPIndividual gpi = (GPIndividual)gpspecies.newIndividual(state, thread);
gei = reverseMap(state, gpi, thread);
}
else
{
gei = (GEIndividual)super.newIndividual(state, thread);
gei.species = this ;
}
return gei ;
}
/**
* creates all of an individual's trees
* @param state Evolution state
* @param trees array of trees for the individual
* @param ind the GEIndividual
* @param threadnum tread number
* @return number of chromosomes consumed
*/
public int makeTrees(EvolutionState state, GEIndividual ind, GPTree[] trees,
int threadnum, HashMap ercMapsForFancyPrint)
{
int[] genome = ind.genome ;
int position = 0 ;
// We start with one pass, then repeatedly double the genome length and
// try again until it's big enough. This is simple but very costly in terms of
// memory so our maximum pass size is MAXIMUM_PASSES, which should be small enough
// to allow for even pretty long genomes.
for(int i = 1; i <= passes; i *= 2) // note i starts at 1
{
position = makeTrees(state, genome, trees, threadnum, ercMapsForFancyPrint);
if (position < 0 && i < passes) // gotta try again
{
// this is a total hack
int[] old = genome;
genome = new int[old.length * 2];
System.arraycopy(old, 0, genome, 0, old.length);
System.arraycopy(old, 0, genome, old.length, old.length); // duplicate
}
}
return (Math.min(position, ind.genome.length));
}
// called by the above
public int makeTrees(EvolutionState state, int[] genome, GPTree[] trees,
int threadnum, HashMap ercMapsForFancyPrint)
{
int position = 0;
for (int i = 0; i < trees.length; i++)
{
// cannot complete one of the trees with the given chromosome
if(position < 0)
return BIG_TREE_ERROR;
position = makeTree(state, genome, trees[i], position, i, threadnum, ercMapsForFancyPrint);
}
return position;
}
/**
* makeTree, edits the tree that its given by adding a root (and all subtrees attached)
* @param state
* @param ind
* @param tree
* @param position
* @param treeNum
* @param threadnum
* @return the number of chromosomes used, or an BIG_TREE_ERROR sentinel value.
*/
public int makeTree(EvolutionState state, int[] genome, GPTree tree,
int position, int treeNum, int threadnum, HashMap ercMapsForFancyPrint)
{
// hack, use an array to pass an extra value
int[] countNumberOfChromosomesUsed = { position };
GPFunctionSet gpfs = tree.constraints((GPInitializer) state.initializer).functionset;
GPNode root;
try // get the tree, or return an error.
{
root = makeSubtree(countNumberOfChromosomesUsed, genome, state, gpfs,
grammar[treeNum], treeNum, threadnum, ercMapsForFancyPrint, tree, (byte)0);
}
catch (BigTreeException e)
{
return BIG_TREE_ERROR;
}
if(root == null)
state.output.fatal("Invalid tree: tree #" + treeNum);
root.parent = tree;
tree.child = root;
return countNumberOfChromosomesUsed[0];
}
// thrown by makeSubtree when chromosome is not large enough for the generated tree.
static class BigTreeException extends RuntimeException
{
static final long serialVersionUID = 1L;
}
GPNode makeSubtree(int[] index, int[] genome, EvolutionState es, GPFunctionSet gpfs,
GrammarRuleNode rule, int treeNum, int threadnum, HashMap ercMapsForFancyPrint,
GPNodeParent parent, byte argposition)
{
// have we exceeded the length of the genome? No point in going further.
if (index[0] >= genome.length)
throw new BigTreeException();
// expand the rule with the chromosome to get a body element
int i;
// non existant rule got passed in
if (rule == null)
es.output.fatal("An undefined rule exists within the dagp.");
// more than one rule to consider, pick one based off the genome, and consume the current gene
// avoid mod operation as much as possible
if (rule.getNumChoices() > 1)
i = (genome[index[0]] - ((int)this.minGene(index[0]))) % rule.getNumChoices();
else
i = 0;
index[0]++;
GrammarNode choice = rule.getChoice(i);
// if body is another rule head
// look up rule
if(choice instanceof GrammarRuleNode)
{
GrammarRuleNode nextrule = (GrammarRuleNode) choice;
return makeSubtree(index, genome, es, gpfs, nextrule,
treeNum, threadnum, ercMapsForFancyPrint, parent, argposition);
}
else // handle function
{
GrammarFunctionNode funcgrammarnode = (GrammarFunctionNode) choice;
GPNode validNode = funcgrammarnode.getGPNodePrototype();
int numChildren = validNode.children.length;
// index 0 is the node itself
int numChildrenInGrammar = funcgrammarnode.getNumArguments();
// does the dagp contain the correct amount of children that the GPNode requires
if (numChildren != numChildrenInGrammar)
{
es.output.fatal("GPNode " + validNode.toStringForHumans() + " requires "
+ numChildren + " children. "
+ numChildrenInGrammar
+ " children found in the dagp.");
}
// check to see if it is an ERC node
if (validNode instanceof ERC)
{
// have we exceeded the length of the genome? No point in going further.
if (index[0] >= genome.length)
throw new BigTreeException();
// ** do we actually need to maintain two vlaues ? key and originalVal ?
// ** there is no problem if we use the originalVal for both ERCBank and
// ** ercMapsForFancyPrint, moreover, this will also make the reverse-mapping case
// ** easier -- khaled
// these below two lines are from the original code --
// key for ERC hashtable look ups is the current index within the genome. Consume it.
// int key = ((genome[index[0]]) - ((int)(this.minGene(index[0]))));
// int originalVal = genome[index[0]];
// this single line is khaled's mod --
int genomeVal = genome[index[0]];
index[0]++;
validNode = obtainERC(es, genomeVal, threadnum, validNode, ercMapsForFancyPrint);
}
// non ERC node
else
validNode = validNode.lightClone();
// get the rest.
for (int j = 0, childNumber = 0; j < funcgrammarnode.getNumArguments(); j++)
{
// get and link children to the current GPNode
validNode.children[childNumber] = makeSubtree(index, genome, es, gpfs,
(GrammarRuleNode)funcgrammarnode.getArgument(j),
treeNum, threadnum, ercMapsForFancyPrint, validNode, (byte)childNumber);
if(validNode.children[childNumber] == null)
return null;
childNumber++;
}
validNode.argposition = argposition ;
validNode.parent = parent ;
return validNode;
}
}
/**
Loads an ERC from the ERCBank given the value in the genome.
If there is no such ERC, then one is created and randomized,
then added to the bank. The point of this mechanism is to enable
ERCs to appear in multiple places in a GPTree.
*/
public GPNode obtainERC(EvolutionState state, int genomeVal, int threadnum, GPNode node, HashMap ercMapsForFancyPrint)
{
ArrayList ERCList = (ArrayList) (ERCBank.get(Integer.valueOf(genomeVal)));
// No such ERC, create a new ERCList.
if (ERCList == null)
{
ERCList = new ArrayList();
ERCBank.put(new Integer(genomeVal), ERCList);
}
GPNode dummy = null;
// search array list for an ERC of the same type we want
for (int i = 0; i < ERCList.size(); i++)
{
dummy = (GPNode) ERCList.get(i);
// ERC was found inside the arraylist
if (dummy.nodeEquivalentTo(node))
if (ercMapsForFancyPrint != null) ercMapsForFancyPrint.put(new Integer(genomeVal), dummy);
return dummy.lightClone();
}
// erc was not found in the array list lets make one
node = node.lightClone();
node.resetNode(state, threadnum);
ERCList.add(node);
if (ercMapsForFancyPrint != null) ercMapsForFancyPrint.put(new Integer(genomeVal), node);
return node;
}
public Object clone()
{
GESpecies other = (GESpecies) (super.clone());
other.gpspecies = (GPSpecies) (gpspecies.clone());
// ERCBank isn't cloned
// ** I think we need to clone it -- khaled
return other;
}
public Parameter defaultBase()
{
return GEDefaults.base().push(P_GESPECIES);
}
/** Returns the number of elements consumed from the GEIndividual array to produce
the tree, else returns -1 if an error occurs, specifically if all elements were
consumed and the tree had still not been completed. */
public int consumed(EvolutionState state, GEIndividual ind, int threadnum)
{
// create a dummy individual
GPIndividual newind = ((GPIndividual) (gpspecies.i_prototype)).lightClone();
// do the mapping and return the number consumed
return makeTrees(state, ind, newind.trees, threadnum, null);
}
/**
Returns a dummy GPIndividual with a single tree which was built by mapping
over the elements of the given GEIndividual. Null is returned if an error occurs,
specifically, if all elements were consumed and the tree had still not been completed.
If you pass in a non-null HashMap for ercMapsForFancyPrint, then ercMapsForFancyPrint will be loaded
with key->ERCvalue pairs of ERC mappings used in this map.
*/
public GPIndividual map(EvolutionState state, GEIndividual ind, int threadnum, HashMap ercMapsForFancyPrint)
{
// create a dummy individual
GPIndividual newind = ((GPIndividual) (gpspecies.i_prototype)).lightClone();
// Do NOT initialize its trees
// Set the fitness to the IntegerVectorIndividual's fitness
newind.fitness = ind.fitness;
newind.evaluated = false;
// Set the species to me
newind.species = gpspecies;
// do the mapping
if (makeTrees(state, ind, newind.trees, threadnum, ercMapsForFancyPrint) < 0) // error
return null;
else
return newind;
}
/** Flattens an S-expression */
public List flattenSexp(EvolutionState state, int threadnum, GPTree tree)
{
List nodeList = gatherNodeString(state, threadnum, tree.child, 0);
return nodeList ;
}
/** Used by the above function */
public List gatherNodeString(EvolutionState state, int threadnum, GPNode node, int index)
{
List list = new ArrayList();
if(node instanceof ERC)
{
// Now, get the "key" from the "node", NOTE: the "node" is inside an ArrayList,
// since the ERCBank is mapped as key --> ArrayList of GPNodes.
// The "key" is the corresponding int value for the ERC.
list.add(node.name().trim()); // add "ERC"
// then add the ERC key (original genome value)
list.add(getKeyFromNode(state, threadnum, node, index).trim());
}
else
list.add(node.toString().trim());
if(node.children.length > 0)
{
for(int i = 0 ; i < node.children.length ; i++)
{
index++ ;
List sublist =
gatherNodeString(state, threadnum, node.children[i], index);
list.addAll(sublist);
}
}
return list ;
}
public String getKeyFromNode(EvolutionState state, int threadnum, GPNode node, int index)
{
String str = null ;
// ERCBank has some contents at least.
if(ERCBank != null && !ERCBank.isEmpty())
{
Iterator iter = ERCBank.entrySet().iterator() ;
while(iter.hasNext())
{
Map.Entry pairs = (Map.Entry)iter.next();
ArrayList nodeList = (ArrayList)pairs.getValue();
if(Collections.binarySearch(
nodeList,
node,
new Comparator(){
public int compare(Object o1, Object o2)
{
if(o1 instanceof GPNode && o2 instanceof GPNode)
return ((GPNode)o1).toString().
compareTo(((GPNode)o2).toString());
return 0;
}
}) >= 0 )
{
// a match found, save the key, break loop.
str = ((Integer)pairs.getKey()).toString();
break ;
}
}
}
// If a suitable match is not found in the above loop,
// Add the node in a new list and add it to the ERCBank
// with a new random value as a key.
if(str == null)
{
// if the hash-map is not created yet
if(ERCBank == null) ERCBank = new HashMap();
// if the index is still in the range of minGene.length, use it.
// otherwise use the minGene[0] value.
int minIndex = 0 ; if(index < minGene.length) minIndex = index ;
// now generate a new key
Integer key = Integer.valueOf((int)minGene[minIndex]
+ state.random[threadnum].nextInt(
(int)(maxGene[minIndex] - minGene[minIndex] + 1)));
ArrayList list = new ArrayList();
list.add(node.lightClone());
ERCBank.put(key, list);
str = key.toString();
}
return str ;
}
/**
* The LL(1) parsing algorithm to parse the lisp tree, the lisp tree is actually
* fed as a flattened list, the parsing code uses the "exact" (and as-is) procedure
* described in the dragon book.
**/
public int[] parseSexp(ArrayList flatSexp, GrammarParser gp)
{
// We can't use array here, because we don't know how we are going to traverse
// the dagp tree, so the length is not known beforehand.
ArrayList intList = new ArrayList();
Queue input = new LinkedList((ArrayList)flatSexp.clone()) ;
Stack stack = new Stack();
stack.push(((GrammarNode)gp.productionRuleList.get(0)).getHead());
int index = 0 ;
while(!input.isEmpty())
{
String token = (String)input.remove();
while(true)
{
if(stack.peek().equals(token))
{
// if found a match, pop it from the stack
stack.pop();
// if the stack top is an ERC, read the next token
if(token.equals("ERC"))
{
token = (String)input.remove();
intList.add(Integer.valueOf(token));
}
break;
}
else
{
int rIndex = ((Integer)gp.ruleHeadToIndex.get(stack.peek())).intValue();
int fIndex = ((Integer)gp.functionHeadToIndex.get(token)).intValue();
Integer ruleIndex = new Integer(gp.predictiveParseTable[rIndex][fIndex]);
// get the action (rule) to expand
GrammarNode action = (GrammarNode)gp.indexToRule.get(ruleIndex);
// if the index is still in the range of minGene.length, use it.
// otherwise use the minGene[0] value.
int minIndex = 0 ; if(index < minGene.length) minIndex = index ;
// now add
intList.add(new Integer(((Integer)gp.absIndexToRelIndex.get(ruleIndex)).intValue() + (int)minGene[minIndex]));
index++;
stack.pop();
action = action.children.get(0);
if(action instanceof GrammarFunctionNode)
{
// push the rule (action) arguments in reverse way
for(int i = ((GrammarFunctionNode)action).getNumArguments() - 1
; i >= 0 ; i--)
stack.push(((GrammarFunctionNode)action).getArgument(i).getHead());
// the rule (action) head should be on the top
stack.push(action.getHead());
}
else if(action instanceof GrammarRuleNode) // push as usual
stack.push(((GrammarRuleNode)action).getHead());
}
}
}
// now convert the list into an array
int[] genomeVals = new int[intList.size()];
for(int i = 0 ; i < intList.size() ; i++) { genomeVals[i] = ((Integer)intList.get(i)).intValue() ; }
return genomeVals ;
}
/**
Reverse of the original map() function, takes a GPIndividual and returns
a corresponding GEIndividual; The GPIndividual may contain more than one trees,
and such cases are handled accordingly, see the 3rd bullet below --
NOTE:
* This reverse mapping is only valid for S-expression trees ;
* This procedure supports ERC for the current population (not for population
/subpopulation from other islands); However, that could be done by merging
all ERCBanks from all the sub-populations but that is not done yet ;
* Support for the ADF's are done as follows -- suppose in one GPIndividual,
there are N trees -- T1, T2, ,,, Tn and each of them follows n different
grammars G1, G2, ,,, Gn respectively; now if they are reverse-mapped to
int arrays, there will be n int arrays A1[], A2[], ,,, An[]; and suppose
the i-th tree Ti is reverse mapped to int array Ai[] and morevoer Ai[] is
the longest among all the arrays (Bj[]s); so Bi[] is sufficient to build
all ADF trees Tjs.
*/
public GEIndividual reverseMap(EvolutionState state, GPIndividual ind, int threadnum)
{
// create a dummy individual
GEIndividual newind = (GEIndividual)i_prototype.clone();
// The longest int will be able to contain all ADF trees.
int longestIntLength = -1 ;
int[] longestInt = null ;
// Now go through all the ADF trees.
for(int treeIndex = 0 ; treeIndex < ind.trees.length ; treeIndex++)
{
// Flatten the Lisp tree
ArrayList flatSexp = (ArrayList)flattenSexp(state, threadnum,
ind.trees[treeIndex]);
// Now convert the flatten list into an array of ints
// no. of trees == no. of grammars
int[] genomeVals = parseSexp(flatSexp, grammarParser[treeIndex]);
// store the longest int array
if(genomeVals.length >= longestIntLength)
{
longestIntLength = genomeVals.length ;
longestInt = new int[genomeVals.length] ;
System.arraycopy(genomeVals, 0, longestInt, 0, genomeVals.length);
}
genomeVals = null ;
}
// assign the longest int to the individual's genome
newind.genome = longestInt ;
// update the GPIndividual's fitness information
newind.fitness = ind.fitness ;
newind.evaluated = false;
// Set the species to me ? not sure.
newind.species = this;
// return it
return newind ;
}
}
| |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.volatility.surface;
import java.util.Arrays;
import org.testng.annotations.Test;
import com.opengamma.analytics.financial.model.finitedifference.applications.PDEUtilityTools;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.analytics.math.function.Function;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.integration.Integrator1D;
import com.opengamma.analytics.math.integration.RungeKuttaIntegrator1D;
import com.opengamma.analytics.math.surface.FunctionalDoublesSurface;
import com.opengamma.analytics.math.surface.Surface;
import com.opengamma.util.test.TestGroup;
/**
* The stock price, S_t, is given by S_t = (F_t-D_t)X_t + D_t where F_t is the forward, D_t is the discounted value of future dividend payments
* and X_t is the "pure stock price" process. See Buehler, Hans. Volatility and Dividends
*/
@Test(groups = TestGroup.UNIT)
public class PureStockPriceImpliedVolTest {
private static final Integrator1D<Double, Double> DEFAULT_INTEGRATOR = new RungeKuttaIntegrator1D();
private static final double SPOT = 100.;
private static final double RISK_FREE_RATE = 0.04;
private static final double PURE_STOCK_VOL = 0.4;
private static int N_DIVS = 10;
private static final double[] TAU = new double[N_DIVS];
private static final double[] ALPHA = new double[N_DIVS];
private static final double[] BETA = new double[N_DIVS];
private static final Function1D<Double, Double> R;
private static final Function1D<Double, Double> D;
private static final Function1D<Double, Double> F;
private static final Surface<Double, Double, Double> OTM_PRICE_SURFACE;
static {
for (int i = 0; i < N_DIVS; i++) {
final double t = 0.1 + 0.5 * i;
TAU[i] = t;
}
// Arrays.fill(ALPHA, 0.1);
Arrays.fill(ALPHA, 0, N_DIVS, 1.0);
Arrays.fill(BETA, 0, N_DIVS, 0.01);
// for (int i = 5; i < 10; i++) {
// ALPHA[i] = 2.0 * (9. - i) / 5.;
// BETA[i] = 0.02 * (i - 5.) / 5.;
// }
// Arrays.fill(BETA, 10, N_DIVS, 0.02);
R = new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double t) {
int index = 0;
double prod = Math.exp(t * RISK_FREE_RATE);
while (index < N_DIVS && t >= TAU[index]) {
prod *= 1 - BETA[index];
index++;
}
return prod;
}
};
D = new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double t) {
final double r_t = R.evaluate(t);
double sum = 0.0;
for (int index = 0; index < N_DIVS; index++) {
if (TAU[index] > t) {
sum += ALPHA[index] / R.evaluate(TAU[index]);
}
}
return sum * r_t;
}
};
F = new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double t) {
final double r_t = R.evaluate(t);
double sum = 0.0;
for (int index = 0; index < N_DIVS; index++) {
if (TAU[index] <= t) {
sum += ALPHA[index] / R.evaluate(TAU[index]);
}
}
return r_t * (SPOT - sum);
}
};
final Function<Double, Double> price = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tk) {
final double t = tk[0];
final double k = tk[1];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final boolean isCall = k > f;
final double x = (k - d) / (f - d);
final double result = BlackFormulaRepository.price(1.0, x, t, PURE_STOCK_VOL, isCall) * (f - d);
return result;
}
};
OTM_PRICE_SURFACE = FunctionalDoublesSurface.from(price);
}
@Test(enabled = false)
public void printForward() {
System.out.println("PureStockPriceImpliedVolTest.printForward");
for (int i = 0; i < 101; i++) {
final double t = 0.7 * i / 100.;
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final double r = R.evaluate(t);
System.out.println(t + "\t" + f + "\t" + d + "\t" + r);
}
}
@Test(enabled = false)
public void testFlatImpledVol() {
System.out.println("PureStockPriceImpliedVolTest.testFlatImpledVol");
final double impVol = 0.4;
final Function<Double, Double> pureImpVolFunc = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tx) {
final double t = tx[0];
final double x = tx[1];
final boolean isCall = x > 1.0;
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final double k = (f - d) * x + d;
final double price = BlackFormulaRepository.price(f, k, t, impVol, isCall) / (f - d);
return BlackFormulaRepository.impliedVolatility(price, 1.0, x, t, isCall);
}
};
final Surface<Double, Double, Double> pureImpVolSurface = FunctionalDoublesSurface.from(pureImpVolFunc);
PDEUtilityTools.printSurface("pure implied vol", pureImpVolSurface, 0.01, 2.0, 0.5, 2.0);
}
@Test(enabled = false)
public void testFlatPureImpledVol() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double pureImpVol = 0.4;
final Function<Double, Double> impVolFunc = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tk) {
final double t = tk[0];
final double k = tk[1];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final boolean isCall = k > f;
final double x = (k - d) / (f - d);
final double price = BlackFormulaRepository.price(1.0, x, t, pureImpVol, isCall) * (f - d);
return BlackFormulaRepository.impliedVolatility(price, f, k, t, isCall);
}
};
final Surface<Double, Double, Double> impVolSurface = FunctionalDoublesSurface.from(impVolFunc);
PDEUtilityTools.printSurface("implied vol", impVolSurface, 0.01, 2.0, 30, 200);
}
@Test(enabled = false)
public void testFlatPureImpledVol2() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double pureImpVol = 0.4;
final Function<Double, Double> impVolFunc = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tx) {
final double t = tx[0];
final double k = tx[1];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
return (k - d) / k * pureImpVol;
}
};
final Surface<Double, Double, Double> impVolSurface = FunctionalDoublesSurface.from(impVolFunc);
PDEUtilityTools.printSurface("implied vol", impVolSurface, 0.01, 0.2, 20, 200);
}
@Test(enabled = false)
public void calandarSpreadTest() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double pureImpVol = 0.4;
final double kM = 110;
final double t = 0.1;
final double dt = 1e-12;
//before
final double fM = F.evaluate(t - dt);
final double dM = D.evaluate(t - dt);
final double xM = (kM - dM) / (fM - dM);
final double ppM = BlackFormulaRepository.price(1.0, xM, t - dt, pureImpVol, true);
final double pM = (fM - dM) * ppM;
final double pivM = BlackFormulaRepository.impliedVolatility(ppM, 1.0, xM, t - dt, true);
final double ivM = BlackFormulaRepository.impliedVolatility(pM, fM, kM, t - dt, true);
//after
final double k = (1 - BETA[0]) * kM - ALPHA[0];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final double x = (k - d) / (f - d);
final double x2 = (kM - d) / (f - d);
System.out.println("x: " + x + "\t" + x2);
final double pp = BlackFormulaRepository.price(1.0, x, t, pureImpVol, true);
final double p = pp * (f - d);
final double piv = BlackFormulaRepository.impliedVolatility(pp, 1.0, x, t, true);
final double iv = BlackFormulaRepository.impliedVolatility(p, f, k, t, true);
System.out.println(fM + "\t" + f + "|\t" + ppM + "\t" + pp + "|\t" + (1 - BETA[0]) * pM + "\t" + p + "|\t" + pivM + "\t" + piv + "|\t" + ivM + "\t" + iv);
final double delta = BlackFormulaRepository.delta(fM, kM, t - dt, 0.37, true);
System.out.println(delta);
final double dd = BlackFormulaRepository.dualDelta(1.0, xM, t - dt, pureImpVol, true);
final double corrDelta = ppM / (fM - dM) - xM * dd;
System.out.println(corrDelta);
}
@Test(enabled = false)
public void calandarSpreadTest2() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double impVol = 0.4;
final double kM = 110;
final double t = 0.1;
final double dt = 1e-12;
//before
final double fM = F.evaluate(t - dt);
final double dM = D.evaluate(t - dt);
final double xM = (kM - dM) / (fM - dM);
final double pM = BlackFormulaRepository.price(fM, kM, t - dt, impVol, true);
final double ppM = pM / (fM - dM);
final double ivM = BlackFormulaRepository.impliedVolatility(pM, fM, kM, t - dt, true);
final double pivM = BlackFormulaRepository.impliedVolatility(ppM, 1.0, xM, t - dt, true);
//after
final double k = (1 - BETA[0]) * kM - ALPHA[0];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final double x = (kM - d) / (f - d);
final double p = BlackFormulaRepository.price(f, k, t, impVol, true);
final double pp = p / (f - d);
final double iv = BlackFormulaRepository.impliedVolatility(p, f, k, t, true);
final double piv = BlackFormulaRepository.impliedVolatility(pp, 1.0, x, t, true);
System.out.println(fM + "\t" + f + "|\t" + ppM + "\t" + pp + "|\t" + (1 - BETA[0]) * pM + "\t" + p + "|\t" + pivM + "\t" + piv + "|\t" + ivM + "\t" + iv);
final double delta = BlackFormulaRepository.delta(fM, kM, t - dt, impVol, true);
System.out.println(delta);
}
@Test(enabled = false)
public void calandarSpreadTest3() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double t = 0.1;
final double dt = 1e-12;
final double p = 0.2;
final double pM = p / (1 - BETA[0]);
final double kM = 70;
final double k = (1 - BETA[0]) * kM - ALPHA[0];
final double fM = F.evaluate(t - dt);
final double f = F.evaluate(t);
final double ivM = BlackFormulaRepository.impliedVolatility(pM, fM, kM, t - dt, false);
final double iv = BlackFormulaRepository.impliedVolatility(p, f, k, t, false);
System.out.println(ivM + "\t" + iv);
}
@Test(enabled = false)
public void testRoundTrip() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double impVol = 0.4;
final Function<Double, Double> pureImpVolFunc = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tx) {
final double t = tx[0];
final double x = tx[1];
final boolean isCall = x > 1.0;
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final double k = (f - d) * x + d;
final double price = BlackFormulaRepository.price(f, k, t, impVol, isCall) / (f - d);
return BlackFormulaRepository.impliedVolatility(price, 1.0, x, t, isCall);
}
};
final Function<Double, Double> impVolFunc = new Function<Double, Double>() {
@Override
public Double evaluate(final Double... tk) {
final double t = tk[0];
final double k = tk[1];
final double f = F.evaluate(t);
final double d = D.evaluate(t);
final boolean isCall = k > f;
final double x = (k - d) / (f - d);
final double price = BlackFormulaRepository.price(1.0, x, t, pureImpVolFunc.evaluate(t, x), isCall) * (f - d);
return BlackFormulaRepository.impliedVolatility(price, f, k, t, isCall);
}
};
final Surface<Double, Double, Double> impVolSurface = FunctionalDoublesSurface.from(impVolFunc);
PDEUtilityTools.printSurface("implied vol", impVolSurface, 0.01, 3.0, 50.0, 200.0);
}
@Test(enabled = false)
public void varianceSwapTest() {
System.out.println("PureStockPriceImpliedVolTest.testFlatPureImpledVol");
final double expiry = 0.11;
final Function1D<Double, Double> integral = new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double k) {
final double price = OTM_PRICE_SURFACE.getZValue(expiry, k);
return price / k / k;
}
};
final double f = F.evaluate(expiry);
double var = DEFAULT_INTEGRATOR.integrate(integral, 0.01 * f, 10.0 * f);
int index = 0;
while (index < N_DIVS && TAU[index] <= expiry) {
final double temp = correction(index);
System.out.println("correction " + index + " " + temp + " " + var);
var -= temp;
index++;
}
var *= 2 / expiry;
System.out.println("k:" + Math.sqrt(var));
}
private double correction(final int index) {
final double expiry = TAU[index];
final Function1D<Double, Double> integral = new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double k) {
final double price = OTM_PRICE_SURFACE.getZValue(expiry, k);
final double dPP = dPPrime(k, index);
return price * dPP;
}
};
double res = DEFAULT_INTEGRATOR.integrate(integral, 0.1, 1000.0);
final double f = F.evaluate(expiry);
res += d(f, index);
return res;
}
private double h(final double x, final int index) {
final double a = ALPHA[index];
final double b = BETA[index];
return (x * b + a) / (x + a);
}
private double hPrime(final double x, final int index) {
final double a = ALPHA[index];
final double b = BETA[index];
final double temp = x + a;
return a * (b - 1) / temp / temp;
}
private double hPPrime(final double x, final int index) {
final double a = ALPHA[index];
final double b = BETA[index];
final double temp = x + a;
return 2 * a * (1 - b) / temp / temp / temp;
}
private double d(final double x, final int index) {
final double a = ALPHA[index];
final double b = BETA[index];
final double h = h(x, index);
return Math.log(x * (1 - b) / (x + a)) + h - 0.5 * h * h;
}
private double dPPrime(final double x, final int index) {
final double h = h(x, index);
final double hPrime = hPrime(x, index);
final double hPPrime = hPPrime(x, index);
final double temp = x + ALPHA[index];
final double res = -1 / x / x + 1 / temp / temp + (1 - 2 * h) * hPPrime - 2 * hPrime * hPrime;
return res;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.transport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.base.Splitter;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.config.Config;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.transport.messages.*;
import org.apache.cassandra.utils.Hex;
import org.apache.cassandra.utils.JVMStabilityInspector;
import org.apache.cassandra.utils.MD5Digest;
import static org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions;
public class Client extends SimpleClient
{
public Client(String host, int port, ClientEncryptionOptions encryptionOptions)
{
super(host, port, encryptionOptions);
}
public void run() throws IOException
{
// Start the connection attempt.
System.out.print("Connecting...");
establishConnection();
System.out.println();
// Read commands from the stdin.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;)
{
System.out.print(">> ");
System.out.flush();
String line = in.readLine();
if (line == null) {
break;
}
Message.Request req = parseLine(line.trim());
if (req == null)
{
System.out.println("! Error parsing line.");
continue;
}
try
{
Message.Response resp = execute(req);
System.out.println("-> " + resp);
}
catch (Exception e)
{
JVMStabilityInspector.inspectThrowable(e);
System.err.println("ERROR: " + e.getMessage());
}
}
close();
}
private Message.Request parseLine(String line)
{
Splitter splitter = Splitter.on(' ').trimResults().omitEmptyStrings();
Iterator<String> iter = splitter.split(line).iterator();
if (!iter.hasNext())
return null;
String msgType = iter.next().toUpperCase();
if (msgType.equals("STARTUP"))
{
Map<String, String> options = new HashMap<String, String>();
options.put(StartupMessage.CQL_VERSION, "3.0.0");
while (iter.hasNext())
{
String next = iter.next();
if (next.toLowerCase().equals("snappy"))
{
options.put(StartupMessage.COMPRESSION, "snappy");
connection.setCompressor(FrameCompressor.SnappyCompressor.instance);
}
}
return new StartupMessage(options);
}
else if (msgType.equals("QUERY"))
{
line = line.substring(6);
// Ugly hack to allow setting a page size, but that's playground code anyway
String query = line;
int pageSize = -1;
if (line.matches(".+ !\\d+$"))
{
int idx = line.lastIndexOf('!');
query = line.substring(0, idx-1);
try
{
pageSize = Integer.parseInt(line.substring(idx+1, line.length()));
}
catch (NumberFormatException e)
{
return null;
}
}
return new QueryMessage(query, QueryOptions.create(ConsistencyLevel.ONE, Collections.<ByteBuffer>emptyList(), false, pageSize, null, null));
}
else if (msgType.equals("PREPARE"))
{
String query = line.substring(8);
return new PrepareMessage(query);
}
else if (msgType.equals("EXECUTE"))
{
try
{
byte[] id = Hex.hexToBytes(iter.next());
List<ByteBuffer> values = new ArrayList<ByteBuffer>();
while(iter.hasNext())
{
String next = iter.next();
ByteBuffer bb;
try
{
int v = Integer.parseInt(next);
bb = Int32Type.instance.decompose(v);
}
catch (NumberFormatException e)
{
bb = UTF8Type.instance.decompose(next);
}
values.add(bb);
}
return new ExecuteMessage(MD5Digest.wrap(id), QueryOptions.forInternalCalls(ConsistencyLevel.ONE, values));
}
catch (Exception e)
{
return null;
}
}
else if (msgType.equals("OPTIONS"))
{
return new OptionsMessage();
}
else if (msgType.equals("CREDENTIALS"))
{
System.err.println("[WARN] CREDENTIALS command is deprecated, use AUTHENTICATE instead");
CredentialsMessage msg = new CredentialsMessage();
msg.credentials.putAll(readCredentials(iter));
return msg;
}
else if (msgType.equals("AUTHENTICATE"))
{
Map<String, String> credentials = readCredentials(iter);
if(!credentials.containsKey(IAuthenticator.USERNAME_KEY) || !credentials.containsKey(IAuthenticator.PASSWORD_KEY))
{
System.err.println("[ERROR] Authentication requires both 'username' and 'password'");
return null;
}
return new AuthResponse(encodeCredentialsForSasl(credentials));
}
else if (msgType.equals("REGISTER"))
{
String type = line.substring(9).toUpperCase();
try
{
return new RegisterMessage(Collections.singletonList(Enum.valueOf(Event.Type.class, type)));
}
catch (IllegalArgumentException e)
{
System.err.println("[ERROR] Unknown event type: " + type);
return null;
}
}
return null;
}
private Map<String, String> readCredentials(Iterator<String> iter)
{
final Map<String, String> credentials = new HashMap<String, String>();
while (iter.hasNext())
{
String next = iter.next();
String[] kv = next.split("=");
if (kv.length != 2)
{
System.err.println("[ERROR] Default authentication requires username & password");
return null;
}
credentials.put(kv[0], kv[1]);
}
return credentials;
}
private byte[] encodeCredentialsForSasl(Map<String, String> credentials)
{
byte[] username = credentials.get(IAuthenticator.USERNAME_KEY).getBytes(StandardCharsets.UTF_8);
byte[] password = credentials.get(IAuthenticator.PASSWORD_KEY).getBytes(StandardCharsets.UTF_8);
byte[] initialResponse = new byte[username.length + password.length + 2];
initialResponse[0] = 0;
System.arraycopy(username, 0, initialResponse, 1, username.length);
initialResponse[username.length + 1] = 0;
System.arraycopy(password, 0, initialResponse, username.length + 2, password.length);
return initialResponse;
}
public static void main(String[] args) throws Exception
{
Config.setClientMode(true);
// Print usage if no argument is specified.
if (args.length != 2)
{
System.err.println("Usage: " + Client.class.getSimpleName() + " <host> <port>");
return;
}
// Parse options.
String host = args[0];
int port = Integer.parseInt(args[1]);
ClientEncryptionOptions encryptionOptions = new ClientEncryptionOptions();
System.out.println("CQL binary protocol console " + host + "@" + port);
new Client(host, port, encryptionOptions).run();
System.exit(0);
}
}
| |
package tintor.common;
import java.lang.instrument.Instrumentation;
import java.util.Arrays;
import java.util.Iterator;
@SuppressWarnings("unchecked")
public final class OpenAddressingHashSet<T> implements IHashSet<T> {
private Object[] array;
private int size;
public OpenAddressingHashSet() {
this(5);
}
public OpenAddressingHashSet(int capacity) {
array = new Object[Math.max(8, Util.roundUpPowerOf2(capacity / 5 * 8))];
}
public int size() {
return size;
}
public long deepSizeOfWithoutElements(Instrumentation ins) {
return ins.getObjectSize(this) + ins.getObjectSize(array);
}
public int capacity() {
return array.length / 8 * 5; // 62.5%
}
public void clear() {
Arrays.fill(array, null);
size = 0;
}
public boolean contains(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
while (true) {
if (array[a] == null)
return false;
if (array[a].equals(e))
return true;
a = (a + 1) & mask;
}
}
public T get(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
while (true) {
if (array[a] == null)
return null;
if (array[a].equals(e))
return (T) array[a];
a = (a + 1) & mask;
}
}
public boolean remove(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
int z = a;
while (true) {
if (array[a] == null)
return false;
if (array[a].equals(e))
break;
a = (a + 1) & mask;
}
size -= 1;
int b = (a + 1) & mask;
if (array[b] == null) {
array[a] = null;
return true;
}
while (true) {
int w = (z - 1) & mask;
if (array[w] == null)
break;
z = w;
}
while (true) {
if (between(hash(array[b]) & mask, z, a)) {
array[a] = array[b];
a = b;
}
b = (b + 1) & mask;
if (array[b] == null)
break;
}
array[a] = null;
return true;
}
private static boolean between(int c, int z, int a) {
return (z <= a) ? (z <= c && c <= a) : (z <= c || c <= a);
}
// return true if this was Insert (as opposed to Update)
public boolean set(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
while (array[a] != null) {
if (array[a].equals(e)) {
array[a] = e;
return false;
}
a = (a + 1) & mask;
}
array[a] = e;
grow();
return true;
}
public boolean insert(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
while (array[a] != null) {
if (array[a].equals(e))
return false;
a = (a + 1) & mask;
}
array[a] = e;
grow();
return true;
}
public boolean update(T e) {
final int mask = array.length - 1;
int a = hash(e) & mask;
while (array[a] != null) {
if (array[a].equals(e)) {
array[a] = e;
return true;
}
a = (a + 1) & mask;
}
return false;
}
private void grow() {
if (++size <= capacity())
return;
if (array.length * 2 <= array.length)
throw new Error("can't grow anymore");
final Object[] oarray = array;
array = new Object[array.length * 2];
final int mask = array.length - 1;
for (Object e : oarray)
if (e != null) {
int a = hash(e) & mask;
while (array[a] != null)
a = (a + 1) & mask;
array[a] = e;
}
}
private static int hash(Object a) {
return a.hashCode();
}
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
while (true) {
if (index >= array.length)
return false;
if (array[index] != null)
return true;
index += 1;
}
}
public T next() {
return (T) array[index++];
}
int index;
};
}
public Remover<T> remover() {
return new Remover<T>() {
public T remove() {
if (size == 0)
return null;
while (array[index] == null)
index = (index + 1) & (array.length - 1);
T e = (T) array[index];
OpenAddressingHashSet.this.remove(e);
return e;
}
private int index;
};
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.treeView;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.openapi.util.AsyncResult;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.WaitFor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.util.*;
import static com.intellij.testFramework.PlatformTestUtil.notNull;
abstract class AbstractTreeBuilderTest extends BaseTreeTestCase<BaseTreeTestCase.NodeElement> {
protected MyStructure myStructure;
Node myRoot;
DefaultTreeModel myTreeModel;
Node myCom;
Node myOpenApi;
Node myIde;
Node myRunner;
Node myRcp;
boolean myEnsureSelection = false;
AbstractTreeBuilderTest.Node myFabrique;
Map<NodeElement, ElementEntry> myElementUpdate = new TreeMap<>();
ElementUpdateHook myElementUpdateHook;
Map<String, Integer> mySortedParent = new TreeMap<>();
NodeDescriptor.NodeComparator.Delegate<NodeDescriptor<?>> myComparator;
Node myIntellij;
protected final Set<NodeElement> myChanges = new HashSet<>();
protected AbstractTreeBuilderTest(boolean passThrough) {
super(passThrough);
}
protected AbstractTreeBuilderTest(boolean yieldingUiBuild, boolean bgStructureBuilding) {
super(yieldingUiBuild, bgStructureBuilding);
}
@Override
protected void setUp() throws Exception {
super.setUp();
myComparator = new NodeDescriptor.NodeComparator.Delegate<>(new NodeDescriptor.NodeComparator<NodeDescriptor<?>>() {
@Override
public int compare(NodeDescriptor<?> o1, NodeDescriptor<?> o2) {
return AlphaComparator.INSTANCE.compare(o1, o2);
}
});
mySortedParent.clear();
myTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode(null));
myTreeModel.addTreeModelListener(new TreeModelListener() {
@Override
public void treeNodesChanged(TreeModelEvent e) {
assertEdt();
}
@Override
public void treeNodesInserted(TreeModelEvent e) {
assertEdt();
}
@Override
public void treeNodesRemoved(TreeModelEvent e) {
assertEdt();
}
@Override
public void treeStructureChanged(TreeModelEvent e) {
assertEdt();
}
});
myTree = new Tree(myTreeModel);
myStructure = new MyStructure();
myRoot = new Node(null, "/");
initBuilder(new MyBuilder());
myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
assertEdt();
}
});
myTree.addTreeExpansionListener(new TreeExpansionListener() {
@Override
public void treeExpanded(TreeExpansionEvent event) {
assertEdt();
}
@Override
public void treeCollapsed(TreeExpansionEvent event) {
assertEdt();
}
});
}
@Override
protected void tearDown() throws Exception {
try {
myElementUpdate.clear();
myElementUpdateHook = null;
myStructure.setReValidator(null);
}
finally {
super.tearDown();
}
}
@Nullable
Node removeFromParentButKeepRef(NodeElement child) {
NodeElement parent = (NodeElement)myStructure.getParentElement(child);
AbstractTreeBuilderTest.Node node = myStructure.getNodeFor(parent).remove(child, false);
assertEquals(parent, myStructure.getParentElement(child));
assertFalse(Arrays.asList(myStructure._getChildElements(parent, false)).contains(child));
return node;
}
void assertSorted(String expected) {
Iterator<String> keys = mySortedParent.keySet().iterator();
StringBuilder result = new StringBuilder();
while (keys.hasNext()) {
String each = keys.next();
result.append(each);
int count = mySortedParent.get(each);
if (count > 1) {
result.append(" (").append(count).append(")");
}
if (keys.hasNext()) {
result.append("\n");
}
}
assertEquals(expected, result.toString());
mySortedParent.clear();
}
private void addEntry(String value) {
if (mySortedParent.containsKey(value)) {
mySortedParent.put(value, mySortedParent.get(value) + 1);
} else {
mySortedParent.put(value, 0);
}
}
void assertUpdates(String expected) {
List<Object> entries = Arrays.asList(myElementUpdate.values().toArray());
assertEquals(expected + "\n", PlatformTestUtil.print(entries) + "\n");
myElementUpdate.clear();
}
void buildStructure(final Node root) throws Exception {
buildStructure(root, true);
}
void buildStructure(final Node root, final boolean activate) throws Exception {
doAndWaitForBuilder(() -> {
myCom = root.addChild("com");
myIntellij = myCom.addChild("intellij");
myOpenApi = myIntellij.addChild("openapi");
myFabrique = root.addChild("jetbrains").addChild("fabrique");
myIde = myFabrique.addChild("ide");
myRunner = root.addChild("xUnit").addChild("runner");
myRcp = root.addChild("org").addChild("eclipse").addChild("rcp");
if (activate) {
getBuilder().getUi().activate(true);
}
});
}
protected void activate() throws Exception {
doAndWaitForBuilder(() -> getBuilder().getUi().activate(true));
}
void hideTree() throws Exception {
assertFalse(getMyBuilder().myWasCleanedUp);
invokeLaterIfNeeded(() -> getBuilder().getUi().deactivate());
final WaitFor waitFor = new WaitFor() {
@Override
protected boolean condition() {
return getMyBuilder().myWasCleanedUp || myCancelRequest != null;
}
};
if (myCancelRequest != null) {
throw new Exception(myCancelRequest);
}
waitFor.assertCompleted("Tree cleanup was not performed. isCancelledReadyState=" + getBuilder().getUi().isCancelledReady());
assertTrue(getMyBuilder().myWasCleanedUp);
}
void buildNode(String elementText, boolean select) throws Exception {
buildNode(new NodeElement(elementText), select);
}
void buildNode(Node node, boolean select) throws Exception {
buildNode(node.myElement, select);
}
void buildNode(final NodeElement element, final boolean select) throws Exception {
buildNode(element, select, true);
}
void buildNode(final NodeElement element, final boolean select, final boolean addToSelection) throws Exception {
final boolean[] done = new boolean[] {false};
doAndWaitForBuilder(() -> {
if (select) {
getBuilder().select(element, () -> done[0] = true, addToSelection);
} else {
getBuilder().expand(element, () -> done[0] = true);
}
}, o -> done[0]);
assertNotNull(findNode(element, select));
}
@Nullable
DefaultMutableTreeNode findNode(String elementText, boolean shouldBeSelected) {
return findNode(new NodeElement(elementText), shouldBeSelected);
}
@Nullable
DefaultMutableTreeNode findNode(NodeElement element, boolean shouldBeSelected) {
return findNode((DefaultMutableTreeNode)myTree.getModel().getRoot(), element, shouldBeSelected);
}
@Nullable
private DefaultMutableTreeNode findNode(DefaultMutableTreeNode treeNode, NodeElement toFind, boolean shouldBeSelected) {
final Object object = treeNode.getUserObject();
assertNotNull(object);
if (!(object instanceof NodeDescriptor)) return null;
final NodeElement element = (NodeElement)((NodeDescriptor)object).getElement();
if (toFind.equals(element)) return treeNode;
for (int i = 0; i < treeNode.getChildCount(); i++) {
final DefaultMutableTreeNode result = findNode((DefaultMutableTreeNode)treeNode.getChildAt(i), toFind, shouldBeSelected);
if (result != null) {
if (shouldBeSelected) {
final TreePath path = new TreePath(result.getPath());
assertTrue("Path should be selected: " + path, myTree.isPathSelected(path));
}
return result;
}
}
return null;
}
class Node {
final NodeElement myElement;
final ArrayList<Node> myChildElements = new ArrayList<>();
Node(Node parent, String textName) {
this(parent, new NodeElement(textName));
}
Node(Node parent, NodeElement name) {
myElement = name;
setParent(parent);
}
private void setParent(Node parent) {
myStructure.register(parent != null ? parent.myElement : null, this);
}
public NodeElement getElement() {
return myElement;
}
public Node addChild(Node node) {
myChildElements.add(node);
node.setParent(this);
return node;
}
public Node addChild(String name) {
final Node node = new Node(this, name);
myChildElements.add(node);
return node;
}
public Node addChild(NodeElement element) {
final Node node = new Node(this, element);
myChildElements.add(node);
return node;
}
@Override
public String toString() {
return myElement.toString();
}
public void removeAll() {
myChildElements.clear();
}
@Nullable
public Node getChildNode(String name) {
for (Node each : myChildElements) {
if (name.equals(each.myElement.myName)) return each;
}
return null;
}
public Object[] getChildElements() {
Object[] elements = new Object[myChildElements.size()];
for (int i = 0; i < myChildElements.size(); i++) {
elements[i] = myChildElements.get(i).myElement;
}
return elements;
}
public void delete() {
final NodeElement parent = (NodeElement)myStructure.getParentElement(myElement);
assertNotNull(myElement.toString(), parent);
myStructure.getNodeFor(parent).remove(myElement, true);
}
@Nullable
private Node remove(final NodeElement name, boolean removeRefToParent) {
final Iterator<Node> kids = myChildElements.iterator();
Node removed = null;
while (kids.hasNext()) {
Node each = kids.next();
if (name.equals(each.myElement)) {
kids.remove();
removed = each;
break;
}
}
if (removeRefToParent) {
myStructure.myChild2Parent.remove(name);
}
return removed;
}
}
class MyStructure extends BaseStructure {
private final Map<NodeElement, NodeElement> myChild2Parent = new HashMap<>();
private final Map<NodeElement, Node> myElement2Node = new HashMap<>();
private final Set<NodeElement> myLeaves = new HashSet<>();
private ReValidator myReValidator;
@NotNull
@Override
public Object getRootElement() {
return myRoot.myElement;
}
public void reInitRoot(Node root) {
myRoot = root;
myElement2Node.clear();
myLeaves.clear();
myElement2Node.put(root.myElement, root);
}
@Override
public Object[] doGetChildElements(Object element) {
onElementAction("getChildren", (NodeElement)element);
final AbstractTreeBuilderTest.Node node = myElement2Node.get((NodeElement)element);
return node.getChildElements();
}
@Override
public Object getParentElement(@NotNull final Object element) {
NodeElement nodeElement = (NodeElement)element;
return nodeElement.getForcedParent() != null ? nodeElement.getForcedParent() : myChild2Parent.get(nodeElement);
}
@Override
public boolean isAlwaysLeaf(@NotNull Object element) {
//noinspection SuspiciousMethodCalls
return myLeaves.contains(element);
}
public void addLeaf(NodeElement element) {
myLeaves.add(element);
}
public void removeLeaf(NodeElement element) {
myLeaves.remove(element);
}
@Override
@NotNull
public NodeDescriptor doCreateDescriptor(final Object element, final NodeDescriptor parentDescriptor) {
return new PresentableNodeDescriptor(null, parentDescriptor) {
@Override
protected void update(@NotNull PresentationData presentation) {
onElementAction("update", (NodeElement)element);
presentation.clear();
presentation.addText(new ColoredFragment(getElement().toString(), SimpleTextAttributes.REGULAR_ATTRIBUTES));
if (myChanges.contains(element)) {
myChanges.remove(element);
presentation.setChanged(true);
}
}
@Nullable
@Override
public PresentableNodeDescriptor getChildToHighlightAt(int index) {
return null;
}
@Override
public Object getElement() {
return element;
}
@Override
public String toString() {
List<ColoredFragment> coloredText = getPresentation().getColoredText();
StringBuilder result = new StringBuilder();
for (ColoredFragment each : coloredText) {
result.append(each.getText());
}
return result.toString();
}
};
}
public void register(final NodeElement parent, final Node child) {
myChild2Parent.put(child.myElement, parent);
myElement2Node.put(child.myElement, child);
}
public void clear() {
myChild2Parent.clear();
myElement2Node.clear();
myElement2Node.put(myRoot.myElement, myRoot);
}
public Node getNodeFor(NodeElement element) {
return myElement2Node.get(element);
}
@NotNull
@Override
public AsyncResult<Object> revalidateElement(@NotNull Object element) {
return myReValidator != null ? myReValidator.revalidate((NodeElement)element) : super.revalidateElement(element);
}
public void setReValidator(@Nullable ReValidator reValidator) {
myReValidator = reValidator;
}
}
interface ReValidator {
@NotNull
AsyncResult<Object> revalidate(@NotNull NodeElement element);
}
final class MyBuilder extends BaseTreeBuilder {
MyBuilder() {
super(AbstractTreeBuilderTest.this.myTree, AbstractTreeBuilderTest.this.myTreeModel, AbstractTreeBuilderTest.this.myStructure, myComparator, false);
initRootNode();
}
@Override
protected void sortChildren(Comparator<? super TreeNode> nodeComparator, DefaultMutableTreeNode node, List<? extends TreeNode> children) {
super.sortChildren(nodeComparator, node, children);
addEntry(node.toString());
}
@Override
public boolean isToEnsureSelectionOnFocusGained() {
return myEnsureSelection;
}
}
private void onElementAction(String action, NodeElement element) {
myElementUpdate.computeIfAbsent(element, k -> new ElementEntry(element)).onElementAction(action);
if (myElementUpdateHook != null) {
myElementUpdateHook.onElementAction(action, element);
}
}
interface ElementUpdateHook {
void onElementAction(String action, Object element);
}
private class ElementEntry {
NodeElement myElement;
int myUpdateCount;
int myGetChildrenCount;
private ElementEntry(NodeElement element) {
myElement = element;
}
void onElementAction(String action) {
try {
if ("update".equals(action)) {
myUpdateCount++;
} else if ("getChildren".equals(action)) {
assertTrue("getChildren() is called before update(), node=" + myElement, myUpdateCount > 0);
myGetChildrenCount++;
}
}
catch (Throwable e) {
myCancelRequest = e;
}
}
@Override
public String toString() {
return (myElement + ": " + asString(myUpdateCount, "update") + " " + asString(myGetChildrenCount, "getChildren")).trim();
}
private String asString(int count, String text) {
if (count == 0) return "";
return count > 1 ? text + " (" + count + ")" : text;
}
}
MyBuilder getMyBuilder() {
return (MyBuilder)getBuilder();
}
interface TreeAction {
void run(Runnable onDone);
}
TreePath getPath(String s) {
return new TreePath(notNull(findNode(s, false)).getPath());
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.model;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.Map.Entry;
import org.apache.poi.ss.usermodel.FontFamily;
import org.apache.poi.ss.usermodel.FontScheme;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorders;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellStyleXfs;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellXfs;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDxf;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDxfs;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFills;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFonts;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTNumFmt;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTNumFmts;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.StyleSheetDocument;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
/**
* Table of styles shared across all sheets in a workbook.
*
* @author ugo
*/
public class StylesTable extends POIXMLDocumentPart {
private final Map<Integer, String> numberFormats = new LinkedHashMap<Integer,String>();
private final List<XSSFFont> fonts = new ArrayList<XSSFFont>();
private final List<XSSFCellFill> fills = new ArrayList<XSSFCellFill>();
private final List<XSSFCellBorder> borders = new ArrayList<XSSFCellBorder>();
private final List<CTXf> styleXfs = new ArrayList<CTXf>();
private final List<CTXf> xfs = new ArrayList<CTXf>();
private final List<CTDxf> dxfs = new ArrayList<CTDxf>();
/**
* The first style id available for use as a custom style
*/
public static final int FIRST_CUSTOM_STYLE_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX + 1;
private StyleSheetDocument doc;
/**
* Create a new, empty StylesTable
*/
public StylesTable() {
super();
doc = StyleSheetDocument.Factory.newInstance();
doc.addNewStyleSheet();
// Initialization required in order to make the document readable by MSExcel
initialize();
}
public StylesTable(PackagePart part, PackageRelationship rel) throws IOException {
super(part, rel);
readFrom(part.getInputStream());
}
/**
* Read this shared styles table from an XML file.
*
* @param is The input stream containing the XML document.
* @throws IOException if an error occurs while reading.
*/
protected void readFrom(InputStream is) throws IOException {
try {
doc = StyleSheetDocument.Factory.parse(is);
// Grab all the different bits we care about
if(doc.getStyleSheet().getNumFmts() != null)
for (CTNumFmt nfmt : doc.getStyleSheet().getNumFmts().getNumFmtArray()) {
numberFormats.put((int)nfmt.getNumFmtId(), nfmt.getFormatCode());
}
if(doc.getStyleSheet().getFonts() != null){
int idx = 0;
for (CTFont font : doc.getStyleSheet().getFonts().getFontArray()) {
XSSFFont f = new XSSFFont(font, idx);
fonts.add(f);
idx++;
}
}
if(doc.getStyleSheet().getFills() != null)
for (CTFill fill : doc.getStyleSheet().getFills().getFillArray()) {
fills.add(new XSSFCellFill(fill));
}
if(doc.getStyleSheet().getBorders() != null)
for (CTBorder border : doc.getStyleSheet().getBorders().getBorderArray()) {
borders.add(new XSSFCellBorder(border));
}
CTCellXfs cellXfs = doc.getStyleSheet().getCellXfs();
if(cellXfs != null) xfs.addAll(Arrays.asList(cellXfs.getXfArray()));
CTCellStyleXfs cellStyleXfs = doc.getStyleSheet().getCellStyleXfs();
if(cellStyleXfs != null) styleXfs.addAll(Arrays.asList(cellStyleXfs.getXfArray()));
CTDxfs styleDxfs = doc.getStyleSheet().getDxfs();
if(styleDxfs != null) dxfs.addAll(Arrays.asList(styleDxfs.getDxfArray()));
} catch (XmlException e) {
throw new IOException(e.getLocalizedMessage());
}
}
// ===========================================================
// Start of style related getters and setters
// ===========================================================
public String getNumberFormatAt(int idx) {
return numberFormats.get(idx);
}
public int putNumberFormat(String fmt) {
if (numberFormats.containsValue(fmt)) {
// Find the key, and return that
for(Integer key : numberFormats.keySet() ) {
if(numberFormats.get(key).equals(fmt)) {
return key;
}
}
throw new IllegalStateException("Found the format, but couldn't figure out where - should never happen!");
}
// Find a spare key, and add that
int newKey = FIRST_CUSTOM_STYLE_ID;
while(numberFormats.containsKey(newKey)) {
newKey++;
}
numberFormats.put(newKey, fmt);
return newKey;
}
public XSSFFont getFontAt(int idx) {
return fonts.get(idx);
}
public int putFont(XSSFFont font) {
int idx = fonts.indexOf(font);
if (idx != -1) {
return idx;
}
fonts.add(font);
return fonts.size() - 1;
}
public XSSFCellStyle getStyleAt(int idx) {
int styleXfId = 0;
// 0 is the empty default
if(xfs.get(idx).getXfId() > 0) {
styleXfId = (int) xfs.get(idx).getXfId();
}
return new XSSFCellStyle(idx, styleXfId, this);
}
public int putStyle(XSSFCellStyle style) {
CTXf mainXF = style.getCoreXf();
if(! xfs.contains(mainXF)) {
xfs.add(mainXF);
}
return xfs.indexOf(mainXF);
}
public XSSFCellBorder getBorderAt(int idx) {
return borders.get(idx);
}
public int putBorder(XSSFCellBorder border) {
int idx = borders.indexOf(border);
if (idx != -1) {
return idx;
}
borders.add(border);
return borders.size() - 1;
}
public XSSFCellFill getFillAt(int idx) {
return fills.get(idx);
}
public List<XSSFCellBorder> getBorders(){
return borders;
}
public List<XSSFCellFill> getFills(){
return fills;
}
public List<XSSFFont> getFonts(){
return fonts;
}
public Map<Integer, String> getNumberFormats(){
return numberFormats;
}
public int putFill(XSSFCellFill fill) {
int idx = fills.indexOf(fill);
if (idx != -1) {
return idx;
}
fills.add(fill);
return fills.size() - 1;
}
public CTXf getCellXfAt(int idx) {
return xfs.get(idx);
}
public int putCellXf(CTXf cellXf) {
xfs.add(cellXf);
return xfs.size();
}
public CTXf getCellStyleXfAt(int idx) {
return styleXfs.get(idx);
}
public int putCellStyleXf(CTXf cellStyleXf) {
styleXfs.add(cellStyleXf);
return styleXfs.size();
}
/**
* get the size of cell styles
*/
public int getNumCellStyles(){
return styleXfs.size();
}
/**
* For unit testing only
*/
public int _getNumberFormatSize() {
return numberFormats.size();
}
/**
* For unit testing only
*/
public int _getXfsSize() {
return xfs.size();
}
/**
* For unit testing only
*/
public int _getStyleXfsSize() {
return styleXfs.size();
}
/**
* For unit testing only!
*/
public CTStylesheet getCTStylesheet() {
return doc.getStyleSheet();
}
/**
* Write this table out as XML.
*
* @param out The stream to write to.
* @throws IOException if an error occurs while writing.
*/
public void writeTo(OutputStream out) throws IOException {
XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS);
// Work on the current one
// Need to do this, as we don't handle
// all the possible entries yet
// Formats
CTNumFmts formats = CTNumFmts.Factory.newInstance();
formats.setCount(numberFormats.size());
for (Entry<Integer, String> fmt : numberFormats.entrySet()) {
CTNumFmt ctFmt = formats.addNewNumFmt();
ctFmt.setNumFmtId(fmt.getKey());
ctFmt.setFormatCode(fmt.getValue());
}
doc.getStyleSheet().setNumFmts(formats);
int idx;
// Fonts
CTFonts ctFonts = CTFonts.Factory.newInstance();
ctFonts.setCount(fonts.size());
CTFont[] ctfnt = new CTFont[fonts.size()];
idx = 0;
for(XSSFFont f : fonts) ctfnt[idx++] = f.getCTFont();
ctFonts.setFontArray(ctfnt);
doc.getStyleSheet().setFonts(ctFonts);
// Fills
CTFills ctFills = CTFills.Factory.newInstance();
ctFills.setCount(fills.size());
CTFill[] ctf = new CTFill[fills.size()];
idx = 0;
for(XSSFCellFill f : fills) ctf[idx++] = f.getCTFill();
ctFills.setFillArray(ctf);
doc.getStyleSheet().setFills(ctFills);
// Borders
CTBorders ctBorders = CTBorders.Factory.newInstance();
ctBorders.setCount(borders.size());
CTBorder[] ctb = new CTBorder[borders.size()];
idx = 0;
for(XSSFCellBorder b : borders) ctb[idx++] = b.getCTBorder();
ctBorders.setBorderArray(ctb);
doc.getStyleSheet().setBorders(ctBorders);
// Xfs
if(xfs.size() > 0) {
CTCellXfs ctXfs = CTCellXfs.Factory.newInstance();
ctXfs.setCount(xfs.size());
ctXfs.setXfArray(
xfs.toArray(new CTXf[xfs.size()])
);
doc.getStyleSheet().setCellXfs(ctXfs);
}
// Style xfs
if(styleXfs.size() > 0) {
CTCellStyleXfs ctSXfs = CTCellStyleXfs.Factory.newInstance();
ctSXfs.setCount(styleXfs.size());
ctSXfs.setXfArray(
styleXfs.toArray(new CTXf[styleXfs.size()])
);
doc.getStyleSheet().setCellStyleXfs(ctSXfs);
}
// Style dxfs
if(dxfs.size() > 0) {
CTDxfs ctDxfs = CTDxfs.Factory.newInstance();
ctDxfs.setCount(dxfs.size());
ctDxfs.setDxfArray(dxfs.toArray(new CTDxf[dxfs.size()])
);
doc.getStyleSheet().setDxfs(ctDxfs);
}
// Save
doc.save(out, options);
}
@Override
protected void commit() throws IOException {
PackagePart part = getPackagePart();
OutputStream out = part.getOutputStream();
writeTo(out);
out.close();
}
private void initialize() {
//CTFont ctFont = createDefaultFont();
XSSFFont xssfFont = createDefaultFont();
fonts.add(xssfFont);
CTFill[] ctFill = createDefaultFills();
fills.add(new XSSFCellFill(ctFill[0]));
fills.add(new XSSFCellFill(ctFill[1]));
CTBorder ctBorder = createDefaultBorder();
borders.add(new XSSFCellBorder(ctBorder));
CTXf styleXf = createDefaultXf();
styleXfs.add(styleXf);
CTXf xf = createDefaultXf();
xf.setXfId(0);
xfs.add(xf);
}
private static CTXf createDefaultXf() {
CTXf ctXf = CTXf.Factory.newInstance();
ctXf.setNumFmtId(0);
ctXf.setFontId(0);
ctXf.setFillId(0);
ctXf.setBorderId(0);
return ctXf;
}
private static CTBorder createDefaultBorder() {
CTBorder ctBorder = CTBorder.Factory.newInstance();
ctBorder.addNewBottom();
ctBorder.addNewTop();
ctBorder.addNewLeft();
ctBorder.addNewRight();
ctBorder.addNewDiagonal();
return ctBorder;
}
private static CTFill[] createDefaultFills() {
CTFill[] ctFill = new CTFill[]{CTFill.Factory.newInstance(),CTFill.Factory.newInstance()};
ctFill[0].addNewPatternFill().setPatternType(STPatternType.NONE);
ctFill[1].addNewPatternFill().setPatternType(STPatternType.DARK_GRAY);
return ctFill;
}
private static XSSFFont createDefaultFont() {
CTFont ctFont = CTFont.Factory.newInstance();
XSSFFont xssfFont=new XSSFFont(ctFont, 0);
xssfFont.setFontHeightInPoints(XSSFFont.DEFAULT_FONT_SIZE);
xssfFont.setColor(XSSFFont.DEFAULT_FONT_COLOR);//setTheme
xssfFont.setFontName(XSSFFont.DEFAULT_FONT_NAME);
xssfFont.setFamily(FontFamily.SWISS);
xssfFont.setScheme(FontScheme.MINOR);
return xssfFont;
}
protected CTDxf getDxf(int idx) {
if (dxfs.size()==0) {
return CTDxf.Factory.newInstance();
}
return dxfs.get(idx);
}
protected int putDxf(CTDxf dxf) {
this.dxfs.add(dxf);
return this.dxfs.size();
}
public XSSFCellStyle createCellStyle() {
CTXf xf = CTXf.Factory.newInstance();
xf.setNumFmtId(0);
xf.setFontId(0);
xf.setFillId(0);
xf.setBorderId(0);
xf.setXfId(0);
int xfSize = styleXfs.size();
int indexXf = putCellXf(xf);
return new XSSFCellStyle(indexXf - 1, xfSize - 1, this);
}
/**
* Finds a font that matches the one with the supplied attributes
*/
public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) {
for (XSSFFont font : fonts) {
if ( (font.getBoldweight() == boldWeight)
&& font.getColor() == color
&& font.getFontHeight() == fontHeight
&& font.getFontName().equals(name)
&& font.getItalic() == italic
&& font.getStrikeout() == strikeout
&& font.getTypeOffset() == typeOffset
&& font.getUnderline() == underline)
{
return font;
}
}
return null;
}
}
| |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.specification.ws.internal;
import static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;
import static java.nio.charset.StandardCharsets.US_ASCII;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;
import org.kaazing.k3po.lang.el.Function;
import org.kaazing.k3po.lang.el.spi.FunctionMapperSpi;
public final class Functions {
// See RFC-6455, section 1.3 Opening Handshake
private static final byte[] WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(US_ASCII);
private static final Random RANDOM = new Random();
private static final int MAX_ACCEPTABLE_HEADER_LENGTH = 200;
@Function
public static String base64Encode(String login) {
byte[] bytes = login.getBytes();
return new String(Base64.encode(bytes));
}
@Function
public static String append(String... strings) {
StringBuilder x = new StringBuilder();
for (String s:strings) {
x.append(s);
}
return x.toString();
}
@Function
public static String handshakeKey() {
byte[] bytes = new byte[16];
RANDOM.nextBytes(bytes);
return new String(Base64.encode(bytes), US_ASCII);
}
@Function
public static String handshakeHash(String wsKey) throws NoSuchAlgorithmException {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
sha1.update(wsKey.getBytes(US_ASCII));
byte[] digest = sha1.digest(WEBSOCKET_GUID);
return new String(Base64.encode(digest), US_ASCII);
}
@Function
public static byte[] randomBytes(int length) {
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = (byte) RANDOM.nextInt(0x100);
}
return bytes;
}
@Function
public static byte[] randomBytesUTF8(int length) {
byte[] bytes = new byte[length];
randomBytesUTF8(bytes, 0, length);
return bytes;
}
@Function
public static byte[] randomBytesInvalidUTF8(int length) {
// TODO: make invalid UTF-8 bytes less like valid UTF-8 (!)
byte[] bytes = new byte[length];
bytes[0] = (byte) 0x80;
randomBytesUTF8(bytes, 1, length - 1);
return bytes;
}
@Function
public static byte[] randomBytesUnalignedUTF8(int length, int unalignAt) {
assert unalignAt < length;
byte[] bytes = new byte[length];
int straddleWidth = RANDOM.nextInt(3) + 2;
int straddleAt = unalignAt - straddleWidth + 1;
randomBytesUTF8(bytes, 0, straddleAt);
int realignAt = randomCharBytesUTF8(bytes, straddleAt, straddleWidth);
randomBytesUTF8(bytes, realignAt, length);
return bytes;
}
@Function
public static byte[] copyOfRange(byte[] original, int from, int to) {
return Arrays.copyOfRange(original, from, to);
}
/**
* Takes a string and randomizes which letters in the text are upper or
* lower case
* @param text
* @return
*/
@Function
public static String randomizeLetterCase(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (RANDOM.nextBoolean()) {
c = toUpperCase(c);
} else {
c = toLowerCase(c);
}
result.append(c);
}
return result.toString();
}
@Function
public static String randomHeaderNot(String header) {
// random strings from bytes can generate random bad chars like \n \r \f \v etc which are not allowed
// except under special conditions, and will crash the http pipeline
String commonHeaderChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "1234567890!@#$%^&*()_+-=`~[]\\{}|;':\",./<>?";
StringBuilder result = new StringBuilder();
do {
int randomHeaderLength = RANDOM.nextInt(MAX_ACCEPTABLE_HEADER_LENGTH) + 1;
for (int i = 0; i < randomHeaderLength; i++) {
result.append(commonHeaderChars.charAt(RANDOM.nextInt(commonHeaderChars.length())));
}
} while (result.toString().equalsIgnoreCase(header));
return result.toString();
}
@Function
public static String randomCaseNot(String value) {
String result;
char[] resultChars = new char[value.length()];
do {
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
resultChars[i] = RANDOM.nextBoolean() ? toUpperCase(c) : toLowerCase(c);
}
result = new String(resultChars);
} while(!result.equals(value));
return result;
}
@Function
public static String randomMethodNot(String method) {
String[] methods = new String[]{"GET", "OPTIONS", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT"};
String result;
do {
result = methods[RANDOM.nextInt(methods.length)];
} while (result.equalsIgnoreCase(method));
return result;
}
private static void randomBytesUTF8(byte[] bytes, int start, int end) {
for (int offset = start; offset < end;) {
int remaining = end - offset;
int width = Math.min(RANDOM.nextInt(4) + 1, remaining);
offset = randomCharBytesUTF8(bytes, offset, width);
}
}
private static int randomCharBytesUTF8(byte[] bytes, int offset, int width) {
switch (width) {
case 1:
bytes[offset++] = (byte) RANDOM.nextInt(0x80);
break;
case 2:
bytes[offset++] = (byte) (0xc0 | RANDOM.nextInt(0x20) | 1 << (RANDOM.nextInt(4) + 1));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x40));
break;
case 3:
// UTF-8 not legal for 0xD800 through 0xDFFF (see RFC 3269)
bytes[offset++] = (byte) (0xe0 | RANDOM.nextInt(0x08) | 1 << RANDOM.nextInt(3));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x40));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x40));
break;
case 4:
// UTF-8 ends at 0x10FFFF (see RFC 3269)
bytes[offset++] = (byte) (0xf0 | RANDOM.nextInt(0x04) | 1 << RANDOM.nextInt(2));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x10));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x40));
bytes[offset++] = (byte) (0x80 | RANDOM.nextInt(0x40));
break;
}
return offset;
}
public static class Mapper extends FunctionMapperSpi.Reflective {
public Mapper() {
super(Functions.class);
}
@Override
public String getPrefixName() {
return "ws";
}
}
private Functions() {
// utility
}
}
| |
package au.com.bytecode.opencsv;
/**
Copyright 2005 Bytecode Pty Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* A very simple CSV writer released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
public class CSVWriter implements Closeable {
public static final int INITIAL_STRING_SIZE = 128;
private Writer rawWriter;
private PrintWriter pw;
private char separator;
private char quotechar;
private char escapechar;
private String lineEnd;
/** The character used for escaping quotes. */
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/** The quote constant to use when you wish to suppress all quoting. */
public static final char NO_QUOTE_CHARACTER = '\u0000';
/** The escape constant to use when you wish to suppress all escaping. */
public static final char NO_ESCAPE_CHARACTER = '\u0000';
/** Default line terminator uses platform encoding. */
public static final String DEFAULT_LINE_END = "\n";
private ResultSetHelper resultService = new ResultSetHelperService();
/**
* Constructs CSVWriter using a comma for the separator.
*
* @param writer
* the writer to an underlying CSV source.
*/
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVWriter with supplied separator.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVWriter(Writer writer, char separator) {
this(writer, separator, DEFAULT_QUOTE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVWriter(Writer writer, char separator, char quotechar) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) {
this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd);
}
/**
* Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
this.rawWriter = writer;
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
/**
* Writes the entire list to a CSV file. The list is assumed to be a
* String[]
*
* @param allLines
* a List of String[], with each String[] representing a line of
* the file.
*/
public void writeAll(List<String[]> allLines) {
for (String[] line : allLines) {
writeNext(line);
}
}
protected void writeColumnNames(ResultSet rs)
throws SQLException {
writeNext(resultService.getColumnNames(rs));
}
/**
* Writes the entire ResultSet to a CSV file.
*
* The caller is responsible for closing the ResultSet.
*
* @param rs the recordset to write
* @param includeColumnNames true if you want column names in the output, false otherwise
*
* @throws java.io.IOException thrown by getColumnValue
* @throws java.sql.SQLException thrown by getColumnValue
*/
public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException {
if (includeColumnNames) {
writeColumnNames(rs);
}
while (rs.next())
{
writeNext(resultService.getColumnValues(rs));
}
}
/**
* Writes the next line to the file.
*
* @param nextLine
* a string array with each comma-separated element as a separate
* entry.
*/
public void writeNext(String[] nextLine) {
if (nextLine == null)
return;
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement);
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
private boolean stringContainsSpecialCharacters(String line) {
return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1;
}
protected StringBuilder processLine(String nextElement)
{
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
return sb;
}
/**
* Flush underlying stream to writer.
*
* @throws IOException if bad things happen
*/
public void flush() throws IOException {
pw.flush();
}
/**
* Close the underlying stream writer flushing any buffered content.
*
* @throws IOException if bad things happen
*
*/
public void close() throws IOException {
flush();
pw.close();
rawWriter.close();
}
/**
* Checks to see if the there has been an error in the printstream.
*/
public boolean checkError() {
return pw.checkError();
}
public void setResultService(ResultSetHelper resultService) {
this.resultService = resultService;
}
}
| |
package com.cyngn.exovert.generate.entity;
import com.cyngn.exovert.util.MetaData;
import com.cyngn.exovert.util.Udt;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.UserType;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.Field;
import com.datastax.driver.mapping.annotations.FrozenKey;
import com.datastax.driver.mapping.annotations.FrozenValue;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.google.common.base.CaseFormat;
import com.google.common.reflect.TypeToken;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import javax.lang.model.element.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* Shared functions for generating entity code.
*
* @author truelove@cyngn.com (Jeremy Truelove) 8/28/15
*/
public class EntityGeneratorHelper {
/**
* Handle getting the class names for parameterized types.
*
* @param type the cassandra data type to extract from
* @return the parameterized type result
*/
public static TypeResult getClassWithTypes(DataType type) {
ClassName outer = getRawType(type);
List<TypeName> generics = new ArrayList<>();
boolean hasFrozenType = false;
for(DataType genericType : type.getTypeArguments()) {
if(Udt.instance.isUdt(genericType)) {
generics.add(MetaData.getClassNameForUdt((UserType) genericType));
if(genericType.isFrozen()) {
hasFrozenType = true;
}
} else {
generics.add(getRawType(genericType).box());
}
}
return new TypeResult(ParameterizedTypeName.get(outer, generics.toArray(new TypeName[generics.size()])), hasFrozenType);
}
/**
* Gets the custom type class name in string form if the DataType passed in is a Cassandra CustomType, i.e. UDT
*
* @param type the DataType to check
* @return the custom type class name or null if the DataType isn't a custom type
*/
public static String getCustomTypeName(DataType type) {
String customTypeName = null;
if (type instanceof DataType.CustomType) {
customTypeName = ((DataType.CustomType) type).getCustomTypeClassName();
}
return customTypeName;
}
/**
* Get the raw java type of a Cassandra DataStax driver type
*
* @param type the column type off the java driver
* @return the java poet ClassName representation of a java type
*/
public static ClassName getRawType(DataType type) {
TypeToken<?> typeToken = MetaData.instance.getCodecRegistry().codecFor(type).getJavaType();
ClassName className = ClassName.get(typeToken.getRawType());
// instead of Date LocalDate gets returned now by the new codec system
if("LocalDate".equals(className.simpleName())) { className = ClassName.get(Date.class); }
return className;
}
/**
* Get a setter spec for a entity field.
*
* @param field the field name
* @param type the cassandra field type
* @return the setter method spec
*/
public static MethodSpec getSetter(String field, DataType type) {
String methodRoot = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field);
String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field);
MethodSpec.Builder spec;
if (type.getTypeArguments().size() == 0) {
if(Udt.instance.isUdt(type)) {
spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(MetaData.getClassNameForUdt((UserType) type), paramName);
} else {
spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(getRawType(type), paramName);
}
} else {
TypeResult result = getClassWithTypes(type);
spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(result.type, paramName);
}
spec.addModifiers(Modifier.PUBLIC).addStatement("this.$L = $L", paramName, paramName);
return spec.build();
}
/**
* Get a getter spec for a entity field.
*
* @param field the field name
* @param type the cassandra field type
* @return the getter method spec
*/
public static MethodSpec getGetter(String field, DataType type) {
String methodRoot = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field);
String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field);
MethodSpec.Builder spec;
if (type.getTypeArguments().size() == 0) {
if(Udt.instance.isUdt(type)) {
spec = MethodSpec.methodBuilder("get" + methodRoot).returns(MetaData.getClassNameForUdt((UserType) type));
} else {
spec = MethodSpec.methodBuilder("get" + methodRoot).returns(getRawType(type));
}
} else {
TypeResult result = getClassWithTypes(type);
spec = MethodSpec.methodBuilder("get" + methodRoot).returns(result.type);
}
spec.addModifiers(Modifier.PUBLIC).addStatement("return $L", paramName);
return spec.build();
}
/**
* Get a FieldSpec for an entity field.
*
* @param field the field name
* @param type the field type
* @param isUdtClass is this a UDT entity?
* @return the FieldSpec representing the cassandra field
*/
public static FieldSpec getFieldSpec(String field, DataType type, boolean isUdtClass) {
return getFieldSpec(field, type, isUdtClass, new ArrayList<>());
}
/**
* Get a FieldSpec for an entity field.
*
* @param field the field name
* @param type the field type
* @param isUdtClass is this a UDT entity?
* @param extraAnnotations additional annotations to put on the field
* @return the FieldSpec representing the cassandra field
*/
public static FieldSpec getFieldSpec(String field, DataType type, boolean isUdtClass,
List<AnnotationSpec> extraAnnotations) {
String fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field);
FieldSpec.Builder spec;
boolean hasFrozen = type.isFrozen();
if (type.getTypeArguments().size() == 0) {
if(Udt.instance.isUdt(type)) {
spec = FieldSpec.builder(MetaData.getClassNameForUdt((UserType)type), fieldName, Modifier.PUBLIC);
} else {
spec = FieldSpec.builder(getRawType(type), fieldName, Modifier.PUBLIC);
}
} else {
TypeResult result = getClassWithTypes(type);
hasFrozen |= result.hasFrozenType;
spec = FieldSpec.builder(result.type, fieldName, Modifier.PUBLIC);
}
if(hasFrozen) { spec.addAnnotation(getFrozenValueAnnotation()); }
if (isUdtClass) { spec.addAnnotation(getFieldAnnotation(field)); }
else { spec.addAnnotation(getColumnAnnotation(field)); }
spec.addAnnotation(MetaData.getJsonAnnotation(field));
for(AnnotationSpec annotationSpec : extraAnnotations) {
spec.addAnnotation(annotationSpec);
}
return spec.build();
}
/**
* Get the Column annotation for a table field.
* @param field the field name to put the annotation on
* @return the annotation
*/
public static AnnotationSpec getColumnAnnotation(String field) {
AnnotationSpec.Builder builder = AnnotationSpec.builder(Column.class);
if(MetaData.isSnakeCase(field)) {
builder.addMember("value", "name = $S", field);
}
return builder.build();
}
/**
* Get the Field annotation for a UDT field.
* @param field the field name to put the annotation on
* @return the annotation
*/
public static AnnotationSpec getFieldAnnotation(String field) {
AnnotationSpec.Builder builder = AnnotationSpec.builder(Field.class);
if(MetaData.isSnakeCase(field)) {
builder.addMember("value", "name = $S", field);
}
return builder.build();
}
/**
* Get a FrozenKey annotation for a field.
* @return the annotation
*/
public static AnnotationSpec getFrozenKeyAnnotation() {
return AnnotationSpec.builder(FrozenKey.class).build();
}
/**
* Get a FrozenValue annotation for a field.
* @return the annotation
*/
public static AnnotationSpec getFrozenValueAnnotation() {
return AnnotationSpec.builder(FrozenValue.class).build();
}
/**
* Get the PartitionKey annotation for a Table field.
* @param position the order of the field in the partition key
* @return the annotation
*/
public static AnnotationSpec getPartitionKeyAnnotation(int position) {
return AnnotationSpec.builder(PartitionKey.class).addMember("value", "$L", position).build();
}
/**
* Get the ClusteringColumn annotation for a Table field.
* @param position the order of the field in the partition key
* @return the annotation
*/
public static AnnotationSpec getClusteringAnnotation(int position) {
return AnnotationSpec.builder(ClusteringColumn.class).addMember("value", "$L", position).build();
}
/**
* Given a list of class fields and the class name generate a 'toString' method.
* @param fields the class fields
* @param className the class name
* @return a new toString method
*/
public static MethodSpec getToString(List<String> fields, String className) {
MethodSpec.Builder builder = MethodSpec.methodBuilder("toString")
.addAnnotation(Override.class)
.returns(String.class)
.addModifiers(Modifier.PUBLIC);
builder.addCode("return $S $L\n", className + "{", "+");
boolean first = true;
for (String field : fields) {
String fieldStr = field + "=";
if(!first) {
fieldStr = ", " + fieldStr;
} else {
first = false;
}
builder.addCode("$S + $N +\n", fieldStr, field);
}
builder.addStatement("$S", "}");
return builder.build();
}
/**
* Get the primary key for a Cassandra table
*
* @param table the Cassandra table
* @return the names in order of the primary key fields
*/
public static List<String> getPrimaryKey(TableMetadata table) {
return table.getPrimaryKey().stream().map(ColumnMetadata::getName).collect(Collectors.toList());
}
}
| |
package gov.va.isaac.gui.enhancedsearchview.model.type.text;
import gov.va.isaac.AppContext;
import gov.va.isaac.gui.ConceptNode;
import gov.va.isaac.gui.enhancedsearchview.SearchTypeEnums.ComponentSearchType;
import gov.va.isaac.gui.enhancedsearchview.SearchTypeEnums.FilterType;
import gov.va.isaac.gui.enhancedsearchview.SearchTypeEnums.SearchType;
import gov.va.isaac.gui.enhancedsearchview.filters.Invertable;
import gov.va.isaac.gui.enhancedsearchview.filters.IsAFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.IsDescendantOfFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.LuceneSearchTypeFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.NonSearchTypeFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.RegExpSearchTypeFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.SearchTypeFilter;
import gov.va.isaac.gui.enhancedsearchview.filters.SingleNidFilter;
import gov.va.isaac.gui.enhancedsearchview.model.EnhancedSavedSearch;
import gov.va.isaac.gui.enhancedsearchview.model.SearchModel;
import gov.va.isaac.gui.enhancedsearchview.model.SearchTypeModel;
import gov.va.isaac.gui.enhancedsearchview.model.type.SearchTypeSpecificView;
import gov.va.isaac.util.OTFUtility;
import gov.vha.isaac.ochre.api.component.concept.ConceptSnapshot;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.VBox;
import org.apache.mahout.math.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TextSearchTypeView implements SearchTypeSpecificView {
private static HBox componentSearchTypeControlsHbox = new HBox();
private static ComboBox<ComponentSearchType> componentSearchTypeComboBox = new ComboBox<ComponentSearchType>();
private static GridPane searchFilterGridPane = new GridPane();
private static Button addIsDescendantOfFilterButton;
private static boolean beenSet = false;
private static ComponentSearchType previousSearchType = ComponentSearchType.LUCENE;
private static final Logger LOG = LoggerFactory.getLogger(TextSearchTypeView.class);
private static VBox componentContentParentPane = new VBox(5);
SearchModel searchModel = new SearchModel();
static {
componentSearchTypeComboBox.setItems(FXCollections.observableArrayList(ComponentSearchType.LUCENE, ComponentSearchType.REGEXP));
componentSearchTypeComboBox.getSelectionModel().select(ComponentSearchType.LUCENE);
}
public static ComponentSearchType getCurrentComponentSearchType() {
return componentSearchTypeComboBox.getSelectionModel().getSelectedItem();
}
@Override
public Pane setContents(SearchTypeModel typeModel) {
if (!componentContentParentPane.getChildren().isEmpty()) {
componentContentParentPane.getChildren().clear();
}
HBox controlAndTypePart = new HBox(5);
controlAndTypePart.getChildren().add(componentSearchTypeControlsHbox);
controlAndTypePart.getChildren().add(componentSearchTypeComboBox);
componentContentParentPane.getChildren().add(controlAndTypePart);
componentContentParentPane.getChildren().add(searchFilterGridPane);
TextSearchTypeModel componentContentModel = (TextSearchTypeModel)typeModel;
if (addIsDescendantOfFilterButton == null) {
addIsDescendantOfFilterButton = new Button("Add Filter");
}
addIsDescendantOfFilterButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
IsDescendantOfFilter newFilter = new IsDescendantOfFilter();
addSearchFilter(newFilter, componentContentModel);
componentContentModel.getFilters().add(newFilter);
}
});
// Force single selection
componentSearchTypeComboBox.setCellFactory((p) -> {
final ListCell<ComponentSearchType> cell = new ListCell<ComponentSearchType>() {
@Override
protected void updateItem(ComponentSearchType a, boolean bln) {
super.updateItem(a, bln);
if(a != null){
setText(a.toString() + " Search");
}else{
setText(null);
}
}
};
return cell;
});
componentSearchTypeComboBox.setButtonCell(new ListCell<ComponentSearchType>() {
@Override
protected void updateItem(ComponentSearchType componentSearchType, boolean bln) {
super.updateItem(componentSearchType, bln);
if (bln && !beenSet) {
setText("");
this.setGraphic(null);
componentSearchTypeControlsHbox.getChildren().clear();
componentSearchTypeControlsHbox.setUserData(null);
componentContentModel.setSearchType(null);
} else {
if (componentSearchType == null) {
componentSearchType = previousSearchType;
}
beenSet = true;
setText(componentSearchType.toString() + " Search");
this.setGraphic(null);
componentSearchTypeControlsHbox.getChildren().clear();
SearchTypeFilter<?> filter = null;
componentSearchTypeControlsHbox.getChildren().add(addIsDescendantOfFilterButton);
if (componentSearchType == ComponentSearchType.LUCENE) {
LuceneSearchTypeFilter displayableLuceneFilter = null;
Label searchParamLabel = new Label("Lucene Param");
searchParamLabel.setPadding(new Insets(5.0));
TextField searchParamTextField = new TextField();
if (componentContentModel.getSearchType() != null && componentContentModel.getSearchType().getComponentSearchType() == componentSearchType) {
searchParamTextField.setText(componentContentModel.getSearchType().getSearchParameterProperty().get());
displayableLuceneFilter = ((LuceneSearchTypeFilter)componentContentModel.getSearchType());
} else {
displayableLuceneFilter = new LuceneSearchTypeFilter();
filter = displayableLuceneFilter;
componentContentModel.setSearchType(filter);
}
addAllSearchFilters(componentContentModel);
searchParamTextField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(
ObservableValue<? extends String> observable,
String oldValue, String newValue) {
componentContentModel.getSearchType().getSearchParameterProperty().set(newValue);
}
});
searchParamTextField.setPadding(new Insets(5.0));
searchParamTextField.setPromptText("Enter search text");
if (displayableLuceneFilter.getSearchParameter() != null) {
searchParamTextField.setText(displayableLuceneFilter.getSearchParameter());
}
componentSearchTypeControlsHbox.getChildren().addAll(searchParamLabel, searchParamTextField);
EnhancedSavedSearch.refreshSavedSearchComboBox();
} else if (componentSearchType == ComponentSearchType.REGEXP) {
RegExpSearchTypeFilter displayableRegExpFilter = null;
Label searchParamLabel = new Label("RegExp Param");
searchParamLabel.setPadding(new Insets(5.0));
TextField searchParamTextField = new TextField();
if (componentContentModel.getSearchType() != null && componentContentModel.getSearchType().getComponentSearchType() == componentSearchType) {
searchParamTextField.setText(ComponentSearchTypeHelper.stripAllSurroundingRegExpSlashes(componentContentModel.getSearchType().getSearchParameterProperty().get()));
displayableRegExpFilter = ((RegExpSearchTypeFilter)componentContentModel.getSearchType());
} else {
displayableRegExpFilter = new RegExpSearchTypeFilter();
filter = displayableRegExpFilter;
componentContentModel.setSearchType(filter);
}
addAllSearchFilters(componentContentModel);
searchParamTextField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(
ObservableValue<? extends String> observable,
String oldValue, String newValue) {
componentContentModel.getSearchType().getSearchParameterProperty().set(ComponentSearchTypeHelper.addSurroundingRegExpSlashesIfNotAlreadyThere(ComponentSearchTypeHelper.stripAllSurroundingRegExpSlashes(newValue)));
}
});
searchParamTextField.setPadding(new Insets(5.0));
searchParamTextField.setPromptText("Enter regexp text");
if (displayableRegExpFilter.getSearchParameter() != null) {
searchParamTextField.setText(ComponentSearchTypeHelper.stripAllSurroundingRegExpSlashes(displayableRegExpFilter.getSearchParameter()));
}
componentSearchTypeControlsHbox.getChildren().addAll(searchParamLabel, searchParamTextField);
EnhancedSavedSearch.refreshSavedSearchComboBox();
}
else {
LOG.warn("Unsupported ComponentSearchType {}", componentSearchType);
// throw new RuntimeException("Unsupported ComponentSearchType " + componentSearchType);
}
componentSearchTypeControlsHbox.setUserData(filter);
}
}
});
componentSearchTypeComboBox.setOnAction((event) -> {
LOG.trace("searchModel.getResultsTypeComboBox() event (selected: " + searchModel.getResultsTypeComboBox().getSelectionModel().getSelectedItem() + ")");
SearchModel.getSearchResultsTable().getResults().getItems().clear();
SearchModel.getSearchResultsTable().initializeSearchResultsTable(SearchType.TEXT, searchModel.getResultsTypeComboBox().getSelectionModel().getSelectedItem());
previousSearchType = componentSearchTypeComboBox.getSelectionModel().getSelectedItem();
});
return componentContentParentPane;
}
private void removeSearchFilter(final NonSearchTypeFilter<?> filter, TextSearchTypeModel model) {
// Create temp save list of nodes from searchFilterGridPane
List<Node> newNodes = new ArrayList<>(searchFilterGridPane.getChildren());
HBox row = null;
for (Node gridPaneNode : searchFilterGridPane.getChildren()) {
if (gridPaneNode.getUserData() == filter) {
row = (HBox)gridPaneNode;
}
}
if (row == null) {
LOG.error("Specified filter not found in searchFilterGridPane containing {} nodes: {}", searchFilterGridPane.getChildren().size(), filter);
}
// Remove this node from temp save list of nodes
newNodes.remove(row);
// Remove this filter from searchModel
int preRemovalSize = model.getFilters().size();
model.getFilters().remove(filter);
int postRemovalSize = model.getFilters().size();
// Check before/after list size because bugs could cause identical componentContentModel.getFilters() to be created that should be the same exact filter
// which would otherwise silently prevent removal from list
if (postRemovalSize >= preRemovalSize || model.getFilters().contains(filter)) {
LOG.error("FAILED removing filter " + filter + " from searchModel NonSearchTypeFilter list: " + Arrays.toString(model.getFilters().toArray()));
} else {
LOG.debug("searchModel no longer contains filter " + filter + ": " + Arrays.toString(model.getFilters().toArray()));
}
// Remove all nodes from searchFilterGridPane
removeAllSearchFilters();
// Recreate and add each node to searchFilterGridPane
for (NonSearchTypeFilter<?> filterToAdd : model.getFilters()) {
addSearchFilter(filterToAdd, model);
}
}
private void removeAllSearchFilters() {
searchFilterGridPane.getChildren().clear();
}
public void addAllSearchFilters(TextSearchTypeModel model) {
removeAllSearchFilters();
for (NonSearchTypeFilter<?> filter : model.getFilters()) {
addSearchFilter(filter, model);
}
}
private void addSearchFilter(final NonSearchTypeFilter<?> filter, TextSearchTypeModel model) {
final int index = searchFilterGridPane.getChildren().size();
HBox row = new HBox();
HBox.setMargin(row, new Insets(5, 5, 5, 5));
row.setUserData(filter);
Button removeFilterButton = new Button("Remove");
removeFilterButton.setMinWidth(55);
removeFilterButton.setPadding(new Insets(5.0));
removeFilterButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
removeSearchFilter(filter, model);
}
});
row.getChildren().add(removeFilterButton);
if (filter instanceof IsDescendantOfFilter) {
IsDescendantOfFilter displayableIsDescendantOfFilter = (IsDescendantOfFilter)filter;
Label searchParamLabel = new Label("Ancestor");
searchParamLabel.setPadding(new Insets(5.0));
searchParamLabel.setMinWidth(70);
CheckBox excludeMatchesCheckBox = new CheckBox("Exclude Matches");
excludeMatchesCheckBox.setPadding(new Insets(5.0));
excludeMatchesCheckBox.setMinWidth(150);
excludeMatchesCheckBox.setSelected(((IsDescendantOfFilter) filter).getInvert());
excludeMatchesCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(
ObservableValue<? extends Boolean> observable,
Boolean oldValue,
Boolean newValue) {
((IsDescendantOfFilter) filter).setInvert(newValue);
}});
final ConceptNode cn = new ConceptNode(null, false);
cn.setPromptText("Type, drop or select a concept to add");
//HBox.setHgrow(cn.getNode(), Priority.SOMETIMES);
//HBox.setMargin(cn.getNode(), new Insets(5, 5, 5, 5));
cn.getConceptProperty().addListener(new ChangeListener<ConceptSnapshot>()
{
@Override
public void changed(ObservableValue<? extends ConceptSnapshot> observable, ConceptSnapshot oldValue, ConceptSnapshot newValue)
{
if (newValue != null)
{
displayableIsDescendantOfFilter.setNid(newValue.getNid());
LOG.debug("isDescendantFilter should now contain concept with NID " + displayableIsDescendantOfFilter.getNid() + ": " + Arrays.toString(model.getFilters().toArray()));
} else {
displayableIsDescendantOfFilter.setNid(0);
}
}
});
if (filter.isValid()) {
cn.set(OTFUtility.getConceptVersion(((IsDescendantOfFilter) filter).getNid()));
}
row.getChildren().addAll(searchParamLabel, cn.getNode(), excludeMatchesCheckBox);
} else if (filter instanceof IsAFilter) {
IsAFilter displayableIsAFilter = (IsAFilter)filter;
Label searchParamLabel = new Label("Match");
searchParamLabel.setPadding(new Insets(5.0));
searchParamLabel.setMinWidth(70);
CheckBox excludeMatchesCheckBox = new CheckBox("Exclude Matches");
excludeMatchesCheckBox.setPadding(new Insets(5.0));
excludeMatchesCheckBox.setMinWidth(150);
excludeMatchesCheckBox.setSelected(((IsAFilter) filter).getInvert());
excludeMatchesCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(
ObservableValue<? extends Boolean> observable,
Boolean oldValue,
Boolean newValue) {
((IsAFilter) filter).setInvert(newValue);
}});
final ConceptNode cn = new ConceptNode(null, false);
cn.setPromptText("Type, drop or select a concept to add");
//HBox.setHgrow(cn.getNode(), Priority.SOMETIMES);
//HBox.setMargin(cn.getNode(), new Insets(5, 5, 5, 5));
cn.getConceptProperty().addListener(new ChangeListener<ConceptSnapshot>()
{
@Override
public void changed(ObservableValue<? extends ConceptSnapshot> observable, ConceptSnapshot oldValue, ConceptSnapshot newValue)
{
if (newValue != null)
{
displayableIsAFilter.setNid(newValue.getNid());
LOG.debug("isAFilter should now contain concept with NID " + displayableIsAFilter.getNid() + ": " + Arrays.toString(model.getFilters().toArray()));
} else {
displayableIsAFilter.setNid(0);
}
}
});
if (filter.isValid()) {
cn.set(OTFUtility.getConceptVersion(((IsAFilter) filter).getNid()));
}
row.getChildren().addAll(searchParamLabel, cn.getNode(), excludeMatchesCheckBox);
}
else {
String msg = "Failed creating DisplayableFilter GridPane cell for filter of unsupported type " + filter.getClass().getName();
LOG.error(msg);
throw new RuntimeException(msg);
}
ComboBox<FilterType> filterTypeComboBox = new ComboBox<>();
filterTypeComboBox.setEditable(false);
filterTypeComboBox.setItems(FXCollections.observableArrayList(FilterType.values()));
filterTypeComboBox.getSelectionModel().select(FilterType.valueOf(filter.getClass()));
filterTypeComboBox.setOnAction((event) -> {
LOG.trace("filterTypeComboBox event (selected: " + filterTypeComboBox.getSelectionModel().getSelectedItem() + ")");
if (model.getFilters().size() >= (index + 1)) {
// Model already has filter at this index
if (FilterType.valueOf(model.getFilters().get(index).getClass()) == filterTypeComboBox.getSelectionModel().getSelectedItem()) {
// Same type as existing filter. Do nothing.
} else {
try {
NonSearchTypeFilter<?> newFilter = filterTypeComboBox.getSelectionModel().getSelectedItem().getClazz().newInstance();
NonSearchTypeFilter<?> existingFilter = model.getFilters().get(index);
// Attempt to retain existing filter parameters, if possible
if ((existingFilter instanceof Invertable) && (newFilter instanceof Invertable)) {
((Invertable)newFilter).setInvert(((Invertable)existingFilter).getInvert());
}
if ((existingFilter instanceof SingleNidFilter) && (newFilter instanceof SingleNidFilter)) {
((SingleNidFilter)newFilter).setNid(((SingleNidFilter)existingFilter).getNid());
}
model.getFilters().set(index, newFilter);
// Remove all nodes from searchFilterGridPane
removeAllSearchFilters();
// Recreate and add each node to searchFilterGridPane
for (NonSearchTypeFilter<?> f : model.getFilters()) {
addSearchFilter(f, model);
}
} catch (Exception e) {
String msg = "Failed creating new " + filterTypeComboBox.getSelectionModel().getSelectedItem() + " filter at index " + index;
String details = msg + ". Caught " + e.getClass().getName() + " \"" + e.getLocalizedMessage() + "\"";
String title = "Failed creating new filter";
AppContext.getCommonDialogs().showErrorDialog(title, msg, details, AppContext.getMainApplicationWindow().getPrimaryStage());
e.printStackTrace();
}
}
}
});
row.getChildren().add(filterTypeComboBox);
searchFilterGridPane.addRow(index, row);
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setVgrow(Priority.NEVER);
searchFilterGridPane.getRowConstraints().add(index, rowConstraints);
}
/*
* This method adds new DisplayableFilter to both GridPane and searchModel,
* if DisplayableFilter not already in searchModel
*
* It also adds a Remove button that removes the specified DisplayableFilter from
* both the GridPane and the searchModel
*
*/
}
| |
/*
* Copyright 2015 Ayuget
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ayuget.redface.data.api.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.common.base.Preconditions;
import java.util.Date;
public class PrivateMessage implements Parcelable {
private final long id;
private final String recipient;
private final String subject;
private final int totalMessages;
private final boolean hasUnreadMessages;
private final Date lastResponseDate;
private final String lastResponseAuthor;
private final boolean hasBeenReadByRecipient;
private final int pagesCount;
private PrivateMessage(long id, String recipient, String subject, int totalMessages, boolean hasUnreadMessages, Date lastResponseDate, String lastResponseAuthor, boolean hasBeenReadByRecipient, int pagesCount) {
this.id = id;
this.recipient = recipient;
this.totalMessages = totalMessages;
this.subject = subject;
this.hasUnreadMessages = hasUnreadMessages;
this.lastResponseDate = lastResponseDate;
this.lastResponseAuthor = lastResponseAuthor;
this.hasBeenReadByRecipient = hasBeenReadByRecipient;
this.pagesCount = pagesCount;
}
public long getId() {
return id;
}
public String getRecipient() {
return recipient;
}
public int getTotalMessages() {
return totalMessages;
}
public boolean hasUnreadMessages() {
return hasUnreadMessages;
}
public boolean hasBeenReadByRecipient() {
return hasBeenReadByRecipient;
}
public Date getLastResponseDate() {
return lastResponseDate;
}
public String getLastResponseAuthor() {
return lastResponseAuthor;
}
public String getSubject() {
return subject;
}
public int getPagesCount() {
return pagesCount;
}
public static class Builder {
private long id;
private String recipient;
private String subject;
private int totalMessages;
private boolean hasUnreadMessages;
private Date lastResponseDate;
private String lastResponseAuthor;
private boolean hasBeenReadByRecipient;
private int pagesCount;
public Builder() {
this.hasUnreadMessages = false;
this.hasBeenReadByRecipient = true;
}
public Builder forRecipient(String recipient) {
this.recipient = recipient;
return this;
}
public Builder withSubject(String subject) {
this.subject = subject;
return this;
}
public Builder withId(long id) {
this.id = id;
return this;
}
public Builder withPagesCount(int pagesCount) {
this.pagesCount = pagesCount;
return this;
}
public Builder withLastResponse(String author, Date responseDate) {
this.lastResponseDate = responseDate;
this.lastResponseAuthor = author;
return this;
}
public Builder withUnreadMessages(boolean hasUnreadMessages) {
this.hasUnreadMessages = hasUnreadMessages;
return this;
}
public Builder asReadByRecipient(boolean hasBeenReadByRecipient) {
this.hasBeenReadByRecipient = hasBeenReadByRecipient;
return this;
}
public Builder withTotalMessages(int totalMessages) {
this.totalMessages = totalMessages;
return this;
}
public PrivateMessage build() {
Preconditions.checkNotNull(id);
Preconditions.checkNotNull(totalMessages);
Preconditions.checkNotNull(lastResponseAuthor);
Preconditions.checkNotNull(lastResponseDate);
Preconditions.checkNotNull(subject);
Preconditions.checkNotNull(recipient);
return new PrivateMessage(id, recipient, subject, totalMessages, hasUnreadMessages, lastResponseDate, lastResponseAuthor, hasBeenReadByRecipient, pagesCount);
}
}
/**
* /!\ Boilerplate code below (parcelable and equals) /!\
*/
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.recipient);
dest.writeString(this.subject);
dest.writeInt(this.totalMessages);
dest.writeByte(hasUnreadMessages ? (byte) 1 : (byte) 0);
dest.writeLong(lastResponseDate != null ? lastResponseDate.getTime() : -1);
dest.writeString(this.lastResponseAuthor);
dest.writeByte(hasBeenReadByRecipient ? (byte) 1 : (byte) 0);
dest.writeInt(this.pagesCount);
}
private PrivateMessage(Parcel in) {
this.id = in.readLong();
this.recipient = in.readString();
this.subject = in.readString();
this.totalMessages = in.readInt();
this.hasUnreadMessages = in.readByte() != 0;
long tmpLastResponseDate = in.readLong();
this.lastResponseDate = tmpLastResponseDate == -1 ? null : new Date(tmpLastResponseDate);
this.lastResponseAuthor = in.readString();
this.hasBeenReadByRecipient = in.readByte() != 0;
this.pagesCount = in.readInt();
}
public static final Parcelable.Creator<PrivateMessage> CREATOR = new Parcelable.Creator<PrivateMessage>() {
public PrivateMessage createFromParcel(Parcel source) {
return new PrivateMessage(source);
}
public PrivateMessage[] newArray(int size) {
return new PrivateMessage[size];
}
};
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PrivateMessage that = (PrivateMessage) o;
if (id != that.id) return false;
if (totalMessages != that.totalMessages) return false;
if (hasUnreadMessages != that.hasUnreadMessages) return false;
if (hasBeenReadByRecipient != that.hasBeenReadByRecipient) return false;
if (!recipient.equals(that.recipient)) return false;
if (!subject.equals(that.subject)) return false;
if (!lastResponseDate.equals(that.lastResponseDate)) return false;
if (pagesCount != that.pagesCount) return false;
return lastResponseAuthor.equals(that.lastResponseAuthor);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + recipient.hashCode();
result = 31 * result + subject.hashCode();
result = 31 * result + totalMessages;
result = 31 * result + (hasUnreadMessages ? 1 : 0);
result = 31 * result + lastResponseDate.hashCode();
result = 31 * result + lastResponseAuthor.hashCode();
result = 31 * result + (hasBeenReadByRecipient ? 1 : 0);
result = 31 * result + pagesCount;
return result;
}
public Topic asTopic() {
return Topic.builder()
.id((int) getId())
.title(subject)
.pagesCount(pagesCount)
.isPrivateMessage(true)
.build();
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PrivateMessage{");
sb.append("id=").append(id);
sb.append(", recipient='").append(recipient).append('\'');
sb.append(", subject='").append(subject).append('\'');
sb.append('}');
return sb.toString();
}
}
| |
package com.github.hypfvieh.config.xml;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.junit.jupiter.api.Test;
import com.github.hypfvieh.AbstractBaseUtilTest;
public class XmlConfigurationTest extends AbstractBaseUtilTest {
@Test
public void testGetString() throws IOException {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder().setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml").build();
String readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("SubValue1", readValue);
readValue = xmlConfiguration.getString("Config/Key3/SubKeyList/SubListEntry");
assertEquals("SubListEntry1", readValue);
readValue = xmlConfiguration.getString("Not/existing");
assertNull(readValue);
}
@Test
public void testGetList() throws IOException {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder().setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml").build();
List<String> readValue = xmlConfiguration.getStringList("Config/Key2/SubKey1");
assertEquals(1, readValue.size());
assertEquals("SubValue1", readValue.get(0));
readValue = null;
readValue = xmlConfiguration.getStringList("Config/Key3/SubKeyList/SubListEntry");
assertEquals(4, readValue.size());
assertEquals("SubListEntry2", readValue.get(1));
assertEquals("SubListEntry3", readValue.get(3));
readValue = null;
readValue = xmlConfiguration.getStringList("Config/Key3/SubKeyList");
assertEquals(4, readValue.size());
assertEquals("SubListEntry2", readValue.get(1));
assertEquals("SubListEntry3", readValue.get(3));
}
@Test
public void testSetString() throws IOException {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder().setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml").build();
String readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("SubValue1", readValue);
xmlConfiguration.setString("Config/Key2/SubKey1", false, "NewValue1");
readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("NewValue1", readValue);
}
@Test
public void testSetValues() throws IOException {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder().setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml").build();
String readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("SubValue1", readValue);
readValue = xmlConfiguration.getString("Config/Key4/NotInt");
assertEquals("A", readValue);
readValue = xmlConfiguration.getString("Config/Key4/Int");
assertEquals("100", readValue);
Map<String, String> values = new HashMap<>();
values.put("Config/Key2/SubKey1", "NewValue1");
values.put("Config/Key4/NotInt", "B");
values.put("Config/Key4/Int", "2000");
xmlConfiguration.setValues(values, false);
readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("NewValue1", readValue);
readValue = xmlConfiguration.getString("Config/Key4/NotInt");
assertEquals("B", readValue);
readValue = xmlConfiguration.getString("Config/Key4/Int");
assertEquals("2000", readValue);
}
@Test
public void testSaveToFile() throws IOException {
File tempFile = File.createTempFile(getClass().getSimpleName() + getMethodName(), ".xml");
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setOutputFile(tempFile).build();
String readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("SubValue1", readValue);
xmlConfiguration.setString("Config/Key2/SubKey1", false, "NewValue1");
readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("NewValue1", readValue);
xmlConfiguration.save();
xmlConfiguration = null;
xmlConfiguration = new XmlConfigBuilder()
.setInputFile(tempFile).build();
readValue = xmlConfiguration.getString("Config/Key2/SubKey1");
assertEquals("NewValue1", readValue);
tempFile.delete();
}
@Test
public void testGetStringProperty() {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setSkipRoot(true)
.setKeyDelimiter(".")
.setAllowKeyOverrideFromEnvironment(true)
.build();
// correct value found
assertEquals("Value1", xmlConfiguration.getString("Key1", "Key2"));
// key found, but wrong value
assertNotEquals("fail", xmlConfiguration.getString("Key1", "fail"));
// wrong key, wrong value
assertNotEquals("fail", xmlConfiguration.getString("foo", "bar"));
// wrong key, correct default
assertEquals("fail", xmlConfiguration.getString("foo", "fail"));
// correct key, overridden by environment
System.getProperties().setProperty("Key2.SubKey1", "Jambalaja");
assertEquals("Jambalaja", xmlConfiguration.getString("Key2.SubKey1", "default"));
}
@Test
public void testGetStringListProperty() {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setSkipRoot(true)
.setKeyDelimiter(".")
.build();
List<String> stringList = xmlConfiguration.getStringList("Key3.SubKeyList.SubListEntry");
assertFalse(stringList.isEmpty());
assertTrue(stringList.size() == 4);
assertEquals("SubListEntry1", stringList.get(0));
}
@Test
public void testGetStringSetProperty() {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setKeyDelimiter(".")
.setSkipRoot(true)
.build();
Set<String> stringList = xmlConfiguration.getStringSet("Key3.SubKeyList.SubListEntry", TreeSet.class);
assertFalse(stringList.isEmpty());
assertTrue(stringList.size() == 3);
}
@Test
public void testGetIntProperty() {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setSkipRoot(true)
.setKeyDelimiter(".")
.build();
// key found, but not integer
assertEquals(-1, xmlConfiguration.getInt("Key4.NotInt", -1));
// key found and is integer
assertEquals(100, xmlConfiguration.getInt("Key4.Int", -1));
}
@Test
public void testGetBooleanProperty() {
XmlConfiguration xmlConfiguration = new XmlConfigBuilder()
.setInputFile("src/test/resources/xmlConfigTest/xmlConfigTest.xml")
.setSkipRoot(true)
.setKeyDelimiter(".")
.build();
// key found, but not bool, expect default
assertEquals(false, xmlConfiguration.getBoolean("Key5.NotBool", false));
// key found and is boolean
assertEquals(true, xmlConfiguration.getBoolean("Key5.Bool", false));
}
}
| |
package com.alibaba.jstorm.kafka;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.Message;
import kafka.message.MessageAndOffset;
import kafka.common.ErrorMapping;
import backtype.storm.Config;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.utils.Utils;
/**
*
* @author feilaoda
*
*/
public class PartitionConsumer {
private static Logger LOG = LoggerFactory.getLogger(PartitionConsumer.class);
static enum EmitState {
EMIT_MORE, EMIT_END, EMIT_NONE
}
private int partition;
private KafkaConsumer consumer;
private PartitionCoordinator coordinator;
private KafkaSpoutConfig config;
private LinkedList<MessageAndOffset> emittingMessages = new LinkedList<MessageAndOffset>();
private SortedSet<Long> pendingOffsets = new TreeSet<Long>();
private SortedSet<Long> failedOffsets = new TreeSet<Long>();
private long emittingOffset;
private long lastCommittedOffset;
private ZkState zkState;
private Map stormConf;
private long consumerSleepEndTime = 0;
public PartitionConsumer(Map conf, KafkaSpoutConfig config, int partition, ZkState offsetState) {
this.stormConf = conf;
this.config = config;
this.partition = partition;
this.consumer = new KafkaConsumer(config);
this.zkState = offsetState;
Long jsonOffset = null;
try {
Map<Object, Object> json = offsetState.readJSON(zkPath());
if (json != null) {
// jsonTopologyId = (String)((Map<Object,Object>)json.get("topology"));
jsonOffset = (Long) json.get("offset");
}
} catch (Throwable e) {
LOG.warn("Error reading and/or parsing at ZkNode: " + zkPath(), e);
}
try {
if (config.fromBeginning) {
emittingOffset = consumer.getOffset(config.topic, partition, kafka.api.OffsetRequest.EarliestTime());
} else {
if (jsonOffset == null) {
lastCommittedOffset = consumer.getOffset(config.topic, partition, kafka.api.OffsetRequest.LatestTime());
} else {
lastCommittedOffset = jsonOffset;
}
emittingOffset = lastCommittedOffset;
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public EmitState emit(SpoutOutputCollector collector) {
if (emittingMessages.isEmpty()) {
fillMessages();
}
int count = 0;
while (true) {
MessageAndOffset toEmitMsg = emittingMessages.pollFirst();
if (toEmitMsg == null) {
return EmitState.EMIT_END;
}
count ++;
Iterable<List<Object>> tups = generateTuples(toEmitMsg.message());
if (tups != null) {
for (List<Object> tuple : tups) {
LOG.debug("emit message {}", new String(Utils.toByteArray(toEmitMsg.message().payload())));
collector.emit(tuple, new KafkaMessageId(partition, toEmitMsg.offset()));
}
if(count>=config.batchSendCount) {
break;
}
} else {
ack(toEmitMsg.offset());
}
}
if (emittingMessages.isEmpty()) {
return EmitState.EMIT_END;
} else {
return EmitState.EMIT_MORE;
}
}
private void fillMessages() {
ByteBufferMessageSet msgs;
try {
long start = System.currentTimeMillis();
if(config.fromBeginning){
msgs = consumer.fetchMessages(partition, emittingOffset);
}else {
msgs = consumer.fetchMessages(partition, emittingOffset + 1);
}
if (msgs == null) {
short fetchResponseCode = consumer.getAndResetFetchResponseCode();
if (fetchResponseCode == ErrorMapping.OffsetOutOfRangeCode()) {
this.emittingOffset = consumer.getOffset(config.topic, partition, kafka.api.OffsetRequest.LatestTime());
LOG.warn("reset kafka offset {}", emittingOffset);
}else if(fetchResponseCode == ErrorMapping.NotLeaderForPartitionCode()){
consumer.setConsumer(null);
LOG.warn("current consumer is not leader, reset kafka simpleConsumer");
}else{
this.consumerSleepEndTime = System.currentTimeMillis() + 100;
LOG.warn("sleep until {}", consumerSleepEndTime);
}
LOG.warn("fetch null message from offset {}", emittingOffset);
return;
}
int count = 0;
for (MessageAndOffset msg : msgs) {
count += 1;
emittingMessages.add(msg);
emittingOffset = msg.offset();
pendingOffsets.add(emittingOffset);
LOG.debug("fillmessage fetched a message:{}, offset:{}", msg.message().toString(), msg.offset());
}
long end = System.currentTimeMillis();
if(count == 0){
this.consumerSleepEndTime = System.currentTimeMillis() + 100;
LOG.warn("sleep until {}", consumerSleepEndTime);
}
LOG.info("fetch message from partition:"+partition+", offset:" + emittingOffset+", size:"+msgs.sizeInBytes()+", count:"+count +", time:"+(end-start));
} catch (Exception e) {
e.printStackTrace();
LOG.error(e.getMessage(),e);
}
}
public boolean isSleepingConsumer(){
return System.currentTimeMillis() < this.consumerSleepEndTime;
}
public void commitState() {
try {
long lastOffset = 0;
if (pendingOffsets.isEmpty() || pendingOffsets.size() <= 0) {
lastOffset = emittingOffset;
} else {
lastOffset = pendingOffsets.first();
}
if (lastOffset != lastCommittedOffset) {
Map<Object, Object> data = new HashMap<Object, Object>();
data.put("topology", stormConf.get(Config.TOPOLOGY_NAME));
data.put("offset", lastOffset);
data.put("partition", partition);
data.put("broker", ImmutableMap.of("host", consumer.getLeaderBroker().host(), "port", consumer.getLeaderBroker().port()));
data.put("topic", config.topic);
zkState.writeJSON(zkPath(), data);
lastCommittedOffset = lastOffset;
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public void ack(long offset) {
try {
pendingOffsets.remove(offset);
} catch (Exception e) {
LOG.error("offset ack error " + offset);
}
}
public void fail(long offset) {
failedOffsets.remove(offset);
}
public void close() {
coordinator.removeConsumer(partition);
consumer.close();
}
@SuppressWarnings("unchecked")
public Iterable<List<Object>> generateTuples(Message msg) {
Iterable<List<Object>> tups = null;
ByteBuffer payload = msg.payload();
if (payload == null) {
return null;
}
tups = Arrays.asList(Utils.tuple(Utils.toByteArray(payload)));
return tups;
}
private String zkPath() {
return config.zkRoot + "/kafka/offset/topic/" + config.topic + "/" + config.clientId + "/" + partition;
}
public PartitionCoordinator getCoordinator() {
return coordinator;
}
public void setCoordinator(PartitionCoordinator coordinator) {
this.coordinator = coordinator;
}
public int getPartition() {
return partition;
}
public void setPartition(int partition) {
this.partition = partition;
}
public KafkaConsumer getConsumer() {
return consumer;
}
public void setConsumer(KafkaConsumer consumer) {
this.consumer = consumer;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.